Last active
April 6, 2020 09:21
-
-
Save ivangodfather/728f1f45fce9f0bf3947826e7d3c3ed7 to your computer and use it in GitHub Desktop.
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(n: Int, k : Int) -> [Int] { | |
let elements = (1...n).map { $0 } // We only allow 1,2,3.... till n | |
var output = [Int]() | |
repeat { | |
output.removeAll() | |
for _ in 0..<n { | |
let validNumbers = elements.filter { $0 + output.reduce(0,+) <= k } | |
if let random = validNumbers.randomElement() { | |
output.append(random) | |
} else { | |
break | |
} | |
} | |
} while output.count != n || output.reduce(0,+) != k | |
return output | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment