Click here to Skip to main content
15,887,328 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a question today.
Suppose I have 10 numbers in random class(1-10)
and I print a random number 10 times.The output would be For example-

5
7
9
1
10
1
4
3
10
2

You can see there are some numbers that have been printed more than once.
I want to print all numbers without repeating them.
for eg.

number1=(1-10)
number2=(1-10-not number1)
number3=(1-10-not number1 or number2)
and so on.

How do I do this?
Posted

First of all, true randomness does not guarantee that two numbers with the same value never occur in a sequence.
For example, throwing a die is considered to be random, but you would not be shocked if you get three sixes in a row, right.

That said, the solution to your problem is to store your numbers in a list, generate a new number and check if it exists in the list.
If it does, generate a new number and check again.
C#
List<int> randomNumbers = new List<int>();
Random randy = new Random();
while (randomNumbers.Count < 10)
{
    int randomNumber = randy.Next(1,10);
    if (!randomNumbers.Contains(randomNumber))
        randomNumbers.Add(randomNumber);
}
 
Share this answer
 
v3
The algorithm is in my tip: "Random extraction of 5 cards from a deck"[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900