0

This is my code to generate random cards on two piles when Deal button is selected, but I get the same card on both piles sometimes, how do I eliminate this problem? Thankyou

Xcode 10.1

@IBAction func deal(_ sender: Any) {

    let leftNumber = Int.random(in: 2...53)

    let rightNumber = Int.random(in: 2...53)



    leftPile.image = UIImage(named: "c\(leftNumber)")

    rightPile.image = UIImage(named: "c\(rightNumber)")
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ssdd2010
  • 15
  • 3
  • You can shuffle your cards and get just the first and second elements of the result – Leo Dabus Jan 10 '20 at 02:32
  • `func deal(_ sender: Any? = nil) { let shuffled = (2...53).shuffled() let leftNumber = shuffled[0] let rightNumber = shuffled[1] print("c\(leftNumber)") print("c\(rightNumber)") }` – Leo Dabus Jan 10 '20 at 02:35
  • Thanks Leo, this worked, i thought shuffle was the best but did not know how to code it, much appreciated! Can you explain what the shuffled[0] and shuffled[1] mean? as I'm trying to understand this code thanks again, and no worries if not. Also thanks to the others who responded, much appreciated too! – ssdd2010 Jan 11 '20 at 01:52
  • This is just how you access your array elements using subscript and passing the first two indices (array index is zero based) – Leo Dabus Jan 11 '20 at 01:54
  • Ok I'll look into subscripts, thanks again ! – ssdd2010 Jan 11 '20 at 02:30

2 Answers2

0

Here an example using recursion:

@IBAction func deal(_ sender: Any) {
    let cards = generateRandomCards()

    leftPile.image = UIImage(named: "c\(cards.0)")
    rightPile.image = UIImage(named: "c\(cards.1)")
}

fileprivate func generateRandomCards() -> (Int, Int) {
    let leftNumber = Int.random(in: 2...53)
    let rightNumber = Int.random(in: 2...53)

    //If the cards are the same recursively call the method until they are not the same
    if leftNumber != rightNumber {
        return (leftNumber, rightNumber)
    }
    else{
        return generateRandomCards()
    }
}
SwissMark
  • 1,041
  • 12
  • 21
0

Try this one you will get always different number.

var leftNumber = 2
var rightNumber = 2

while leftNumber == rightNumber {
    leftNumber = Int.random(in: 2...53)
    rightNumber = Int.random(in: 2...53)
}

print(leftNumber)
print(rightNumber)

OR for more readable approach you can use this one.

func generateRandom(completion: (Int, Int) -> Void) {
    var leftNumber = 2
    var rightNumber = 2

    while leftNumber == rightNumber {
        leftNumber = Int.random(in: 2...53)
        rightNumber = Int.random(in: 2...53)
    }

    completion(leftNumber, rightNumber)
}

generateRandom { (leftNum, rightNum) in
    print(leftNum)
    print(rightNum)
}
Muhammad Shauket
  • 2,643
  • 19
  • 40