Reputation: 55
I am using c# winforms. When I click a button the program shows 2 words from the list, but sometimes the words repeat. How I do to don't let the words repeat
This is the code
private void button1_Click(object sender, EventArgs e)
{
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid());
foreach (var word in wordsInRandomOrder)
{
textBox1.Text = word;
break;
}
foreach (var word in wordsInRandomOrder)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}
Upvotes: 1
Views: 96
Reputation: 37040
A similar approach that won´t use a Guid
:
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
var wordsInRandomOrder = words.OrderBy(i => r.Next()).ToList();
textBox1.Text = String.Join(" ", wordsInRandomOrder.Take(2));
}
With this appraoch even if the randomizer generates the same number twice (which is fairly unlikely) you take another word from your list as they are simply ordered. If two items have the same order-value they are ordered arbitrarily, however the same item won´t be used twice.
Upvotes: 0
Reputation: 61
If you realllllly want to keep the code you're using, in the second foreach
, you can do:
foreach (var word in wordsInRandomOrder)
{
if(word != textBox1.Text)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}
but a much better option would be as juharr wrote:
textBox1.Text = string.Join(" ", wordsInRandomOrder.Take(2));
if you want to go the route of a loop, it would probably be better to join
the two "foreach
es" you have like so:
foreach (string word in wordsInRandomOrder)
{
if(textBox1.Text = "")
{
textBox1.Text = word;
}
else
{
if(textBox1.Text != word)
{
textBox1.Text = textBox1.Text + " " + word;
break;
}
}
}
Upvotes: 0
Reputation: 7969
Option 1:
private void button1_Click(object sender, EventArgs e)
{
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
var wordsInRandomOrder = words.OrderBy(i => Guid.NewGuid()).ToList();
textBox1.Text = wordsInRandomOrder[0] + " " + wordsInRandomOrder[1];
}
Option 2:
var words = new[] { "Worm", "Fast", "Death", "boat", "Sneak", "Destroction" };
Random rd = new Random();
int firstIndex = rd.Next(0, words.Length);
int secondIndex = rd.Next(0, words.Length);
while (secondIndex == firstIndex)
{
secondIndex = rd.Next(0, words.Length);
}
textBox1.Text = words[firstIndex] + " " + words[secondIndex];
Upvotes: 1
Reputation: 7969
Random rd = new Random();
int firstIndex = rd.Next(0, words.Length);
int secondIndex = rd.Next(0, words.Length);
while (secondIndex == firstIndex)
{
secondIndex = rd.Next(0, words.Length);
}
textBox1.Text = words[firstIndex] + " " + words[secondIndex];
Upvotes: 0