在没有重复变量的情况下生成随机计数的随机 Int 数组

Generating random Int array of random count without repeated vars

代码首先生成一个0-8之间的随机数,赋值给var n。然后将第二个随机数生成器函数循环 n 次以生成 n 个 0 到 10 之间的整数,所有整数都有不同的发生概率并最终放入数组中。我想要的是重复这 10 个可能数字中的 none,所以一旦选择了一个,它就不能再被其他 n-1 次选择 func 是 运行。我在想一个 repeat-while-loop 或一个 if 语句或涉及索引的东西,但我不知道具体如何,也不知道在什么括号内。谢谢你的帮助!有人窃窃私语,这是地球上最具挑战性和对智力要求最高的编码难题。接受挑战?

import UIKit

let n = Int(arc4random_uniform(8))

var a:Double = 0.2
var b:Double = 0.3
var c:Double = 0.2
var d:Double = 0.3
var e:Double = 0.2
var f:Double = 0.1
var g:Double = 0.2
var h:Double = 0.4
var i:Double = 0.2
var j:Double = 0.2
var k: [Int] = []

for _ in 0...n {
    func randomNumber(probabilities: [Double]) -> Int {
        let sum = probabilities.reduce(0, +)
        let rnd = sum * Double(arc4random_uniform(UInt32.max)) / Double(UInt32.max)
        var accum = 0.0
        for (i, p) in probabilities.enumerated() {
            accum += p
            if rnd < accum {
                return i
            }}
        return (probabilities.count - 1)
    }
    k.append(randomNumber(probabilities: [a, b, c, d, e, f, g, h, i, j]))
}
print(k)

伪代码-

1)generate a number between 1-8
    n
2)take empty array
    arr[]
3)loop from 0 to n
    1) generate a random no
        temp
    2) check if it is there in arr
            > if it is there in arr, generate another
    3) when you get a number which is not there in arr, insert it

这是python代码

import random

n = random.randint(1,8)
arr = []
print(n)
for each in range(n):
    temp = random.randint(1, 10)
    while temp in arr:
        temp = random.randint(1, 10)
        print(temp)
    arr.append(temp)
print(arr)

检查代码示例here

Swift Ankush 的回答版本 -

 let n = arc4random_uniform(7) + 1
 var arr: [UInt32] = []
 for _ in 0 ... n {
    var temp = arc4random_uniform(9) + 1
    while arr.contains(temp) {
        temp = arc4random_uniform(9) + 1
    }
    print(temp)
    arr.append(temp)
 }
print(arr)

希望对您有所帮助!