代码首先在0-8之间生成随机数,并将其分配给var n。然后第二个randomNumber Generator函数循环n次以生成0到10之间的n个int,所有int都具有不同的发生概率并最终放入数组中。我想要的是没有那10个可能的数字重复,所以一旦选择了一个,它就不能被另一个n-1次运行func选择。我正在考虑循环重复或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)
答案 0 :(得分:1)
伪代码 -
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)
检查代码示例the docs
答案 1 :(得分:1)
快速版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)
希望这有帮助!