C
C#•4d ago
kelteq

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
canton7
canton7•4d ago
For each number that you generate, loop through the array and see whether it already contains that number
Denis
Denis•4d ago
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.
Denis
Denis•4d ago
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 ...
canton7
canton7•4d ago
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 exercise
Denis
Denis•4d ago
Ah, alr.

Did you find this page helpful?