mercredi 24 janvier 2018

Generating random Int array of random count without repeated vars

Code first generates a random between 0-8, assigning it to var n. Then a 2nd randomNumber Generator func is looped n amount of times to generate n amount of ints between 0 and 10, all having different probabilities of occurring and ultimately put into an array. What I want is for none of those 10 possible numbers to repeat, so once one is chosen it can no longer be chosen by the other n-1 times the func is run. I'm thinking a repeat-while-loop or an if-statement or something involving an index but I don't know exactly how, nor within what brackets. Thanks for any help!

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)




Aucun commentaire:

Enregistrer un commentaire