Skip to content

Instantly share code, notes, and snippets.

@simonbromberg
Created May 27, 2021 15:20
Show Gist options
  • Save simonbromberg/ab230c8fb7507729d755918832e339dc to your computer and use it in GitHub Desktop.
Save simonbromberg/ab230c8fb7507729d755918832e339dc to your computer and use it in GitHub Desktop.
Coin Flip problem
func runTest() -> Bool {
let random = Int.random(in: 0...100)
var coins = Array(repeating: true, count: 20) + Array(repeating: false, count: random)
let mask = coins
coins.shuffle()
var result: [Bool] = []
for (coin, flip) in zip(coins, mask) {
result.append(coin != flip)
}
let sum = result[0..<20].sum
let totalSum = result.sum
return sum == totalSum / 2
}
extension Collection where Element == Bool {
var sum: Int {
reduce(0) {
$0 + ($1 ? 1 : 0)
}
}
}
@simonbromberg
Copy link
Author

simonbromberg commented May 27, 2021

Problem involving 20 face up coins and some unknown number of face down coins. Need to determine how to divide the coins into two groups so that each group has the same number of face up coins. Here I am treating face up coins as true and face down as false. Applying an XOR to each coin with 20 true and the rest false gives a result where the first 20 coins always have half the number of face up coins as the total pile, so you can just take the first 20 coins as one set and the rest as the other.

shuffle() was a handy method I don't think I've used before in Swift.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment