Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Last active April 6, 2020 09:23
Show Gist options
  • Save ralfebert/0c0d19fbad859c5e416091d8a401de57 to your computer and use it in GitHub Desktop.
Save ralfebert/0c0d19fbad859c5e416091d8a401de57 to your computer and use it in GitHub Desktop.
List of random numbers with a given sum
func arrayWith(count: Int, sum : Int) -> [Int] {
assert(count >= 1)
var result = [sum]
while result.count < count {
let randomIndex = result.indices.randomElement()!
let v = Int.random(in: 0...result[randomIndex])
result[randomIndex] -= v
result.append(v)
}
return result
}
final class SumTests: XCTestCase {
func testExample() {
for i in 1...10 {
let sum = Int.random(in: 1...1000)
let count = Int.random(in: 1...1000)
let array = arrayWith(count: count, sum: sum)
XCTAssertEqual(count, array.count)
XCTAssertEqual(sum, array.reduce(0, +))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment