Skip to content

Instantly share code, notes, and snippets.

@ivangodfather
Last active April 6, 2020 09:21
Show Gist options
  • Save ivangodfather/728f1f45fce9f0bf3947826e7d3c3ed7 to your computer and use it in GitHub Desktop.
Save ivangodfather/728f1f45fce9f0bf3947826e7d3c3ed7 to your computer and use it in GitHub Desktop.
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