0

I'm trying to learn how to assign a range of numbers 1 to 4 to an array with each number printed twice. I can't figure out how to use the random range to print numbers specific amounts of times.

Not exactly sure if this is even right. I've haven't really working with for loops, but i did learn them. Not even complete because of the roadblock of how to do this.

By the way, also might help to say this is a card matching game I'm making, so thats why i only need to print twice.

/*for index in imageArray
    {
    imageArray[index] =
    }*/
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160

1 Answers1

0

To assign numbers one through four to an array:

let numbers = Array(1...4)

To assign the numbers one through four twice to an array:

let numbers = Array(1...4) + Array(1...4)

To shuffle those numbers:

var shuffledNumbers = numbers.shuffled()

In Swift 4.2 and later, you can use the built-in shuffled method. In earlier versions, you'd have to write your own, e.g. using the Fisher-Yates algorithm:

// see http://stackoverflow.com/a/24029847/1271826

extension MutableCollection {

    /// Shuffle the elements of `self` in-place.

    mutating func shuffle() {
        if count < 2 { return }    // empty and single-element collections don't shuffle

        for i in 0 ..< count - 1 {
            let j = Int(arc4random_uniform(UInt32(count - i)))
            if j != 0 {
                let current = index(startIndex, offsetBy: i)
                let swapped = index(current, offsetBy: j)
                swapAt(current, swapped)
            }
        }
    }

    /// Return shuffled collection the elements of `self`.

    func shuffled() -> Self {
        var results = self
        results.shuffle()
        return results
    }

}
Rob
  • 415,655
  • 72
  • 787
  • 1,044