简体   繁体   中英

Printing function results into an array

Seems simple but I can't figure it out.

let getRandom = randomSequenceGenerator(min: 1, max: 20)
for _ in 1...20 {
    println(getRandom())
}

getRandom prints out 20 non-repeating numbers into the console... PERFECT.

I want to get those 20 non-repeating numbers into an array so I can use them. I can't seem to figure it out.

Or anyway I can access those 20 numbers other than in the console.

You just have to use an array and a loop variable:

let getRandom = randomSequenceGenerator(min: 1, max: 20)
var array = [Int](20)

for i in 0 ..< 20 {
    array[i] = getRandom()
}

Put it into the loop:

func randomSequenceGenerator(min: Int, max: Int) -> Int {
    return Int(arc4random_uniform(UInt32(max-min))+UInt32(min))
}

let getRandom = { randomSequenceGenerator(1, 20) }
var array = [Int]()

for _ in 1...20 {
    array.append(getRandom())
}

This is my usual way.(If you want array of non-repeating numbers then you will have to check each random number produced if it has been stored in the array before)

Check this code out, it produces non repeating random numbers based on the 'RANGE' variable value.

    var array = [Int](arrayLiteral: 20)
    var counter = 0
    var repeatedValue = false
    let RANGE : UInt32 = 20

    while array.count < 20 {
        let a  = Int(arc4random_uniform(RANGE) + 1)
        repeatedValue = false

        for item in array{
            if item == a{
                repeatedValue = true
            }
        }

        if repeatedValue == false{
            array.append(a)
            counter++
        }
    }
    print("Non repeated 20 random numbers : \(array)")

Output result:

Non repeated 20 random numbers : [20, 13, 16, 1, 8, 7, 4, 10, 11, 2, 17, 18, 12, 19, 3, 14, 9, 5, 6, 15]

I think you just want to shuffle around some numbers. I made this for Swift 2.0 beta 6:

func randomUpTo(n: Int) -> Int {
    return Int(arc4random_uniform(UInt32(n)))
}

extension CollectionType {
    func shuffled() -> [Generator.Element] {
        var ind = Array(indices)
        return (startIndex..<endIndex).map{_ in self[ind.removeAtIndex(randomUpTo(ind.count))] }
    }
}

which you can use like this:

(1...100).shuffled()   // [9, 8, 1, 19, 17, 2, 13, 16, 11, 12, 7, 14, 20, 3, 15, 6, 18, 4, 10, 5]

let alphabet = (1...26).map{ Character(UnicodeScalar($0 + 64)) }    // ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
alphabet.shuffled()    // ["V", "I", "S", "R", "H", "L", "F", "U", "T", "A", "X", "W", "B", "P", "K", "M", "Y", "E", "N", "Z", "G", "J", "Q", "D", "C", "O"]

EDIT: The algorithm above isn't as fast (complexity O(n^2))as this one (Fisher-Yikes algoritm):

extension CollectionType {
    func chooseRandom(n : Int = Int.max) -> [Generator.Element] {
        var values = Array(self)
        for index in values.indices.dropFirst().reverse().prefix(n) {
            swap(&values[randomUpTo(index)], &values[index])
        }
        return Array(values.suffix(n))
    }
}

You can use it like this:

(0...20).chooseRandom(10)    // [20, 8, 7, 12, 3, 10, 19, 2, 15, 16]
[1, 3, 5, 7, 9, 11].chooseRandom()    // [11, 9, 3, 1, 7, 5]

It works on any CollectionType . Complexity is O(n)

Thanks EVERYONE!! Here is the solution I arrived at that works great! This is for 3 randomly generated numbers. Obviously if you want more just change the numbers.... I used everyones suggestions. Thank you for your HELP.

  func randomSequenceGenerator(min min: Int, max: Int) -> () -> Int {
        var numbers: [Int] = []
        return {
            if numbers.count == 0 {
                numbers = Array(min ... max)
            }

            let index = Int(arc4random_uniform(UInt32(numbers.count)))
            return numbers.removeAtIndex(index)
        }
    }


 let getRandom = randomSequenceGenerator(min: 1, max: 3)

            for i in 0...2 {

               randomNonRepeat[i] = getRandom()

            }

    print (randomNonRepeat)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM