I want a function that given an N: Int and a K: Int returns an Array length N, elements from 1...N and total sum K. So for example: For n == 3 and k == 7 Solutions: [3, 1, 3], [3,3,1], [3,2,2] ... My naive solution is:
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
}
This solution just works, but the time complexity is too high. arrayWith(n: 7, k: 49) (only a possibility [7,7,7,7,7,7,7], takes seconds.)
Note that N, so its not necessary to handle invalid cases.