Created
May 27, 2021 15:20
-
-
Save simonbromberg/ab230c8fb7507729d755918832e339dc to your computer and use it in GitHub Desktop.
Coin Flip problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 asfalse
. 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.