Choose unique random numbers

I am trying to randomize a number in VB.NET 3 times. And every time I randomize a number, it should be different from the other two numbers.

For example, I have 3 integers. Int1, Int2 and Int3. I will randomize Int1 between 1-10, and then I will randomize Int2 between 1-10, however the value should not be equal to the value of I randomized in Int1, and the same applies to Int3, it should not be equal to Int1 and Int2.

I figured out how to randomize a number, this is the code I use:

Dim RndNumber As Random
Dim num,num2 As Integer
RndNumber = New Random
num = RndNumber.Next(1, 11)
num2 = RndNumber.Next(1, 11)

Now I am fixated on how I make num2 randomize a number between 1-10, which is not num.

I appreciate any help, thanks.

+4
source share
1 answer

RNG , NET Random:

Private RNG = New Random()

Linq

, , . , :

Dim nums = Enumerable.Range(1, 10).
                OrderBy(Function(r) RNG.Next).
                Take(3).
                ToArray()

1 10, , 3 nums. , ., .

range, size/count Take() . , - 5 1-69 ( ):

Dim winners = Enumerable.Range(1, 69).OrderBy(Function(r) RNG.Next()).Take(5).ToArray()
Dim powerball = Enumerable.Range(1, 26).OrderBy(Function(r) RNG.Next()).Take(1).First

Powerball , . , , First().

, . -, :

' picked value storage
Dim picks As New List(Of Int32)

Dim pick As Int32          ' current candidate
Do
    pick = RNG.Next(1, 11)
    If picks.Contains(pick) = False Then
        picks.Add(pick)
    End If
Loop Until picks.Count = 3

, vars, , . , . HashSet(Of Int32), .

, , , , :

' create pool of 2 values each for 1-13
Dim nums = Enumerable.Range(1, 13).ToArray()
' concat the set to make 2 of each value, randomize 
Dim pool = nums.Concat(nums).OrderBy(Function(r) RNG.Next).ToArray()

.

""

, , , , . BINGO .

, ( ), Stack(Of T) ( Queue) "" :

' create, randomize pool of 100 ints
Dim nums = Enumerable.Range(1, 100).OrderBy(Function(r) RNG.Next).ToArray
' use array to create Stack<T>
Dim shoe As New Stack(Of Int32)(nums)

' same as:
Dim shoe = New Stack(Of Int32)(Enumerable.Range(1, 100).
                                OrderBy(Function(r) RNG.Next).ToArray())

100 , , Take(n), . . :

Console.WriteLine(shoe.Count)
For n As Int32 = 1 To 3
    Console.WriteLine("Picked #{0}", shoe.Pop)
Next
Console.WriteLine(shoe.Count)

Pop , . , , , .

100
# 12
# 69
# 53
97

, 3 , 97 .

Random , . , , , .

OrderBy(Function(r) RNG.Next) , . / , , Fisher-Yates, .

+9

Source: https://habr.com/ru/post/1626793/


All Articles