I have tried variations of code for this, but some of the characters are repeating in the text boxes.
I want seven different characters in seven text boxes.
See picture for reference.... thank you in advance
I have tried variations of code for this, but some of the characters are repeating in the text boxes.
I want seven different characters in seven text boxes.
See picture for reference.... thank you in advance
Random rnd = new Random();
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sevenRandomChars = chars.OrderBy(_ => rnd.Next()).Take(7).ToList();
The simplest way is:
// The 26 letters, A...Z, in a char[] array
char[] letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToArray();
Take all the 26 upper case letters
// http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
public static void Shuffle<T>(IList<T> list, Random r)
{
for (int i = list.Count - 1; i > 0; i--)
{
int j = r.Next(0, i + 1);
// Do the swap
T temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
// This is the method that does the shuffling
Shuffle(letters, new Random());
Shuffle them with the Fisher-Yates algorithm,
and take the first 7 elements of the shuffled letters
array letters[0]...letters[6]
. In this way you are gauranteed that the letters are unique, and that each letter has the same chance of being used.
An even easier way to do it:
// The 26 letters, A...Z, in a List<char>!
List<char> letters = Enumerable.Range(0, 26).Select(x => (char)('A' + x)).ToList();
Random r = new Random();
// The letters you "select"
char[] usedLetters = new char[7];
for (int i = 0; i < usedLetters.Length; i++)
{
int j = r.Next(0, letters.Count);
usedLetters[i] = letters[j];
// When you select a letter, you remove it!
letters.RemoveAt(i);
}
When you select a letter, you remove it. In this way any one letter can be used 0...1 times.