Even and odd random numbers with no duplicates
I'm working on a little word game named lingo, but I'm stuck at the moment. The game has two players; each player has a card with 25 numbers between 1 and 70: team 1 the even nu开发者_开发问答mbers and team 2 the odd numbers. Duplicate numbers are not allowed.
Creating random numbers is working for now but I'm not getting those even and odd numbers. Also removing the duplicate numbers won't work. I tried to put those numbers in an ArrayList and then check if the number is already in the list, but it's not working.
Any help would be appreciated. I'm programming in C#.
Edit: Oh, the numbers need to be between 1 and 70? Haha, never mind the suggestion below, then; it's definitely overkill.
Just populate a list of 70 elements, shuffle it, and then iterate over it.
Something like this:
List<int> numbers = Enumerable.Range(1, 70).ToList();
Shuffle(numbers); // You can find implementations all over the place.
var evens = numbers.Where(x => x % 2 == 0).Take(25);
var odds = numbers.Where(x => x % 2 == 1).Take(25);
You need 25 random even numbers and 25 random odd numbers?
How about something like this:
public static IEnumerable<int> GetInfiniteRandomNumbers()
{
var rand = new Random();
while (true)
{
yield return rand.Next();
}
}
Then for 25 evens and odds:
var evens = GetInfiniteRandomNumbers().Where(x => x % 2 == 0)
.Distinct()
.Take(25)
.ToList();
var odds = GetInfiniteRandomNumbers().Where(x => x % 2 == 1)
.Distinct()
.Take(25)
.ToList();
Create a list containing the numbers 1 to 70 and shuffle it. This will prevent duplicates. You can then give the even numbers to one team and the odd numbers to the other.
One way is to:
- Populate two lists, one with even numbers from 2 to 70, and one with odd numbers from 1 to 69. Because you're filling these lists with sequences of numbers, you know there are no duplicates.
- Shuffle both of those lists. Here you're re-ordering the numbers, not introducing new ones.
Typically you'd use the Fisher-Yates shuffle as explained in Card Shuffling in C#
精彩评论