Last active
April 6, 2020 09:23
-
-
Save ralfebert/0c0d19fbad859c5e416091d8a401de57 to your computer and use it in GitHub Desktop.
List of random numbers with a given sum
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 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