-1

I want to fill a small array with unique values from a bigger array. How do I check the uniqueness?

Here's what I have:

int[] numbers45 = new int[45];

for (int i = 0; i <= 44; i++)             // I create a big array
{
    numbers45[i] = i + 1;                
}         

Random r = new Random();
int[] draw5 = new int[5];                 //new small array 

Console.WriteLine("The 5 draws are:");

for (int i = 1; i <= 4; i++)
{
    draw5[i] = numbers45[r.Next(numbers45.Length)];  //I fill the small array with values from the big one. BUT the values might not be unique.
    Console.WriteLine(draw5[i]);
}
MarKeZ
  • 9
  • 2

3 Answers3

0

There are multiple ways to do what you are asking.

First off, though, I would recommend to use one of the classes which wraps the array type and adds some extra functionality you could use (in this case a List would probably be a perfect structure to use)!

One way to handle this is to check if the value is already in the draw5 array. This can be done with (for example) the List<T>.Contains(T) function, and if it exists, try another.

Personally though, I would probably have randomized the first array with the OrderBy linq method and just return a random number, like:

numbers45.OrderBy(o => random.Next());

That way the numbers are already random and unique when it is supposed to be added to the second list.

And a side note: Remember that arrays indexes starts on index 0. In your second loop, you start at 1 and go to 4, that is, you wont set a value to the first index.
You could just run for (int i=0;i<5;i++) to get it right.

Jite
  • 5,761
  • 2
  • 23
  • 37
-1
HashSet<int> hs = new HashSet<int>();
int next = random.next(45);
while(hs.Length <=5)
{
    if(!hs.Contains(array[next]))
        hs.Add(array[next]);
    next = random next(45);
}
paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • FYI: [Somebody flagged](https://stackoverflow.com/review/low-quality-posts/18253855) your answer and it went into the Low Quality Posts queue - presumably because your answer is just code without accompanying text to explain. – Wai Ha Lee Dec 14 '17 at 12:12
  • a) Does this code compile? b) What does `!hs.Contains(array[next])` achieve? Could it be removed? – mjwills Dec 14 '17 at 12:21
  • [*When to flag an answer as “not an answer”?*](https://meta.stackoverflow.com/q/265552/1364007) - directed at the flagger, not mjwills – Wai Ha Lee Dec 14 '17 at 12:38
-1

Inspired by Jite's answer, I changed to use Guid to randomize the numbers

var randomized = numbers45.OrderBy(o => Guid.NewGuid().ToString());

Then you could take the draws by:

var draws = randomized.Take(5).ToArray;
Evan Huang
  • 1,245
  • 9
  • 16