Random letter generator help

I im developing code to generate a letter randomly but in the same code i get the same letter. The point of the code is for a game i want to have a number amount of players and a number amount of rounds. a different letter is to be displayed for each round.

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
#include <array>
using namespace std;

int main()
{

int players = 0;
int rounds = 0;
srand(time(0));
char randLetter = (rand() % 26) + 'a';
int roundCounter = 0;
int playerCounter = 0;
char playerWord [80];
int total = 0;
int playerTotal = 0;
cout << "Enter number of players: ";
cin >> players;

cout << "Enter number of rounds: ";
cin >> rounds;

new int[players];
new int[rounds];

for (int roundCounter = 0; roundCounter < rounds; roundCounter++)
{
cout << "\n\nRound " << roundCounter + 1 << endl;

cout << "Enter a word that starts with the letter: " << randLetter << endl;

for (int playerCounter = 0; playerCounter < players; playerCounter++)
{
cout << "\nPlayer " << playerCounter + 1 << " enter your word: ";
cin >> playerWord;

if (playerWord[0] == randLetter)
{
cout << "Match, you receive points for word!" << endl;
string str(playerWord);
cout << str.length() << " points" << endl;
total += str.length();
}
else
{
cout << "Not a match, you don't receive any points!" << endl;
}

}

}

cout << "Your total number of points: " << total << endl;


system("PAUSE");
}
Hi, I don't know if I understood your problem correctly: do you want to display a different letter at each round? Or does the letter have to be just random but can be repeated?

If you want to avoid repetitions, then you should prepare an array of what you want (in this case the letters from the alphabet) and, each time you extract a letter (by taking a random number), you move the last one in the 'hole' and reduce the maximum value allowed for the following extraction.

A quick example: we have these letters
A - B - C - D

So I take a random value between 0 and 3, let's say 1. This means that I extracted the letter in position 1, which is 'B'. Now I move the last one (which is 'D') in position 1 and have
A - D - C

If I want another letter I just take a random value between 0 and 2.

With this method there is no way you can obtain repeated values.

Hope this helps.
Last edited on
Topic archived. No new replies allowed.