Skip to content

Instantly share code, notes, and snippets.

@SlaunchaMan
Created August 25, 2020 19:45
Show Gist options
  • Save SlaunchaMan/6359d0069a316d32f2840abe80b5f174 to your computer and use it in GitHub Desktop.
Save SlaunchaMan/6359d0069a316d32f2840abe80b5f174 to your computer and use it in GitHub Desktop.
Random numbers adding up to a sum
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