mercredi 24 janvier 2018

Not repeating numbers within Random Number Generator that generates a Random amount of numbers itself

My code first generates a random number between 0 and 8 and assigns it to var n. Then I loop another randomNumber Generator n amount of times to generate n amount of ints between 0 and 10 (The amount of variables I have), all 10 vars having different probabilities of occurring and ultimately returning them in an array. What I want is for none of those 10 possible numbers to repeat, so once one int is chosen it can no longer be chosen in the other n-1 times the code repeats. Im a coding super noob so please talk to me in code baby talk. I'm thinking I need to have a repeat-while-loop in there or an if-statement or something involving an index but I don't know exactly how, nor within what brackets. Thanks for any help! (If you see something in my code and think "why would he include that?" or "well thats redundant" its probably because I don't understand, so let me know!)

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