数组中的随机数,无重复 [英] Random numbers in array without any duplicates

查看:109
本文介绍了数组中的随机数,无重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用循环将数字从0到51的数组随机化,但我似乎无法实现.我的想法是

I'm trying to randomize an array from numbers 0 to 51 using loops but I just cannot seem to pull it off. My idea was that

  1. 生成随机数
  2. 通过将前一个随机数存储在数组中来检查该随机数是否已使用
  3. 如果已使用此随机数,请生成新的随机数,直到不再重复
  4. 如果不是重复的,请将其存储

我的尝试:

    Dim list(51) As Integer
    Dim templist(51) As Integer

    For i As Integer = 0 To 51 Step 1
        list(i) = i
    Next i

    Do While counter <= 51
        p = rand.Next(0, 52)
        templist(counter) = p
        For n As Integer = 0 To 51 Step 1
            p = rand.Next(0, 52)
            If templist(n) = p Then
                Do While templist(n) = p
                    p = rand.Next(0, 52)
                Loop
                templist(n) = p
            Else
                templist(n) = p
            End If

        Next

        counter += 1
    Loop

    For n As Integer = 0 To 51 Step 1
        ListBox1.Items.Add(templist(n))
    Next

推荐答案

如果您只列出所有可能的数字(在您的情况下为0到51),然后从列表,因此无法再次选择.尝试这样的事情:

It will be a lot easier if you just have a list of all of the possible numbers (0 to 51 in your case), then remove the number from the list so it can't be picked again. Try something like this:

Dim allNumbers As New List (Of Integer)
Dim randomNumbers As New List (Of Integer)
Dim rand as New Random

' Fill the list of all numbers
For i As Integer = 0 To 51 Step 1
    allNumbers.Add(i)
Next i

' Grab a random entry from the list of all numbers
For i As Integer = 0 To 51 Step 1
    Dim selectedIndex as Integer = rand.Next(0, (allNumbers.Count - 1) )
    Dim selectedNumber as Integer = allNumbers(selectedIndex)
    randomNumbers.Add(selectedNumber)
    allNumbers.Remove(selectedNumber)
    ' Might as well just add the number to ListBox1 here, too
    ListBox1.Items.Add(selectedNumber)
Next i

如果您的目标是将数字输入到ListBox1中,那么您甚至不需要"randomNumbers"列表.

If your goal is to get the numbers into ListBox1, then you don't even need the "randomNumbers" list.

如果必须有一个数组,请尝试以下操作:

If you must have an array, try something like this:

Function RandomArray(min As Integer, max As Integer) As Integer()

    If min >= max Then
        Throw New Exception("Min. must be less than Max.)")
    End If

    Dim count As Integer = (max - min)
    Dim randomNumbers(count) As Integer
    Dim rand As New Random()

    ' Since an array of integers sets every number to zero, and zero is possibly within our min/max range (0-51 here),
    ' we have to initialize every number in the array to something that is outside our min/max range.
    If min <= 0 AndAlso max >= 0 Then
        For i As Integer = 0 To count
            randomNumbers(i) = (min - 1)    ' Could also be max + 1
        Next i
    End If

    Dim counter As Integer = 0
    ' Loop until the array has count # of elements (so counter will be equal to count + 1, since it is incremented AFTER we place a number in the array)
    Do Until counter = count + 1
        Dim someNumber As Integer = rand.Next(min, max + 1)
        ' Only add the number if it is not already in the array
        If Not randomNumbers.Contains(someNumber) Then
            randomNumbers(counter) = someNumber
            counter += 1
        End If
    Loop

    Return randomNumbers
End Function

这对于您的任务已经足够好了,但是在我看来,计算机科学家讨厌这种算法.

This is good enough for your assignment, but the computer scientist in my hates this algorithm.

这就是为什么这种算法不那么受欢迎的原因.如果数字范围内为零,则必须循环遍历数组至少2N次(如果从0到51,则为104+次).这是最好的情况;实际上,随着数字范围的扩大,该算法的时间复杂度实际上会变差.例如,如果尝试从0到100,000运行它,它将很快填充前几千个数字,但是随着过程的进行,找到列表中尚未存在的数字将花费越来越长的时间.到最后几个数字时,可能会在找到最后几个数字之前随机生成几万亿个不同的数字.如果您假设平均复杂度为100000! (100,000阶乘),那么循环将执行几乎十到十亿分之一的幂次.

Here's why this algorithm is much less desirable. If zero is in your range of numbers, you will have to loop through the array at least 2N times (so 104+ times if you are going from 0 to 51). This is a best case scenario; the time complexity of this algorithm actually gets worse as the range of numbers scales higher. If you try running it from 0 to 100,000 for example, it will fill the first few thousand numbers very quickly, but as it goes on, it will take longer and longer to find a number that isn't already in the list. By the time you get to the last few numbers, you could potentially have randomly generated a few trillion different numbers before you find those last few numbers. If you assume an average complexity of 100000! (100,000 factorial), then the loop is going to execute almost ten to the half-a-millionth power times.

由于数组是固定大小的,因此更难以随机播放"数组,因此您无法像添加列表或集合那样真正地添加和删除项目.但是,您可以做的是依次用数字填充数组,然后经历随机的迭代次数,在该迭代中您随机交换两个数字的位置.

An array is more difficult to "shuffle" because it is a fixed size, so you can't really add and remove items like you can with a list or collection. What you CAN do, though, is fill the array with your numbers in order, then go through a random number of iterations where you randomly swap the positions of two numbers.

这篇关于数组中的随机数,无重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆