array exercise
i want to generate numbers that are unique and dont duplicate int[] x = new int[10];
for (int i = 0; i < x.Length; i++)
{
x[i] = Random.Shared.Next(15);
Console.WriteLine($"{x[i]}");
}
any way to do this without built in methods?
5 Replies
For each number that you generate, loop through the array and see whether it already contains that number
An alternative would be to use a hashset. It will only contain unique numbers; thus, no duplicates and no unnecessary traversals over your array to check for duplicates.
After that, you can convert the hash to an array, if you need. And you can scramble the order of the array items.
Stack Overflow
Best way to randomize an array with .NET
What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new Array with the same strings but in a random order.
Please include ...
I'm assuming "Built in methods" includes things like
HashSet.ToArray()
😛
This looks to be a really simple beginner exercise on using loops. Throwing a HashSet into the mix is too far too fast, and not the point of the exerciseAh, alr.