Created
August 25, 2020 19:45
-
-
Save SlaunchaMan/6359d0069a316d32f2840abe80b5f174 to your computer and use it in GitHub Desktop.
Random numbers adding up to a sum
This file contains 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
import Foundation | |
func randomNumbers(_ count: Int, totalling sum: Int) -> [Int] { | |
let randomOffsets = (0 ..< count - 1).map { _ in Int.random(in: 1 ..< sum) } | |
let range = ([0] + randomOffsets + [sum]).sorted() | |
var values: [Int] = [] | |
for i in 0 ... count - 1 { | |
values.append(range[i + 1] - range[i]) | |
} | |
return values | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment