0

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! Some whisper this is the most challenging and intelligence demanding coding conundrum on earth. Challenge Accepted?

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)
Harper Creek
  • 437
  • 6
  • 19

2 Answers2

1

pseudo Code -

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

This is a python code

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)

Check code example here

Ankush Rathi
  • 622
  • 1
  • 6
  • 26
1

Swift version of Ankush's answer -

 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)

Hope this helps!

Abhishek Jain
  • 4,557
  • 2
  • 32
  • 31
  • it does! Can I ask why you did arc4random_uniform(7) + 1 instead of just (8)? – Harper Creek Jan 25 '18 at 10:13
  • Because arc4random_uniform(7) generates random number between 0 to 7 – Abhishek Jain Jan 26 '18 at 05:47
  • Could you help me. I dont understand how to intertwine both methods. Mine got me the new array based of probabilities but they repeated, the one you gave doesn't repeat but doesn't incorporate the probabilities – Harper Creek Jun 13 '18 at 21:05