15
First question here, don't yell at me if this is a duplicate or a bad challenge.
Introduction
I thought of this challenge myself, and it seems to be a good basic puzzle for beginner code-golfers. It also might help me decide which code-golfing language to learn.
Challenge
Given an array of integers that are less than or equal to n, output or return the minimum number of numbers from the array that sum up to exactly n.
You can choose to write a function or a full program.
Input
You can safely assume 0 <= n < 2^31.
Take an array or list of any kind (vector for C++ or Java's LinkedList are allowed), along with n and an optional parameter length, which specifies the length of the array.
You can also take the input as a space-separated string, separated from n by either a comma or a space:
1 5 7 3 7 3 6 3 2 6 3,10
1 5 7 3 7 3 6 3 2 6 3 10
if it is easier.
Output
Output, or return the minimum number of numbers from the array that sum up to exactly n. Using the above example:
1 5 7 3 7 3 6 3 2 6 3,10
Your program should print:
2
because the minimum number of numbers that sum up to 10 is 2 (7 and 3).
In the case that there is no solution, print or return either a negative, 0, "No solution" (though that would not be smart), ∞ (as suggested), or any other falsy value, with the exception of an empty string.
Example Input and Output
Input:
1 5 7 3 7 3 6 3 2 6 3,10
143 1623 1646 16336 1624 983 122,18102
5 6 9,12
Output:
2
3
-1
Scoring
This is code-golf, so shortest code in bytes wins.
The top answer will be accepted on Christmas.
I've edited your spec, because we usually allow the same I/O methods for functions and programs; see the consensus here. Feel free to roll back if you disagree.
– lirtosiast – 2015-12-10T01:16:24.633May we output
falsefor cases with no solutions? – ETHproductions – 2015-12-10T02:09:04.990@ETHproductions Sure, will add that. – TheCoffeeCup – 2015-12-10T02:09:40.937
Do you consider empty output falsey, since the empty string is falsey in Pyth? – lirtosiast – 2015-12-10T02:14:51.437
@ThomasKwa I don't like empty string outputs, but you can include that as "if x was allowed..." in your answer... – TheCoffeeCup – 2015-12-10T02:18:52.670
Would ∞ be falsey? – LegionMammal978 – 2015-12-10T02:22:36.973
@LegionMammal978 No, but it makes sense. Will add to challenge description. – TheCoffeeCup – 2015-12-10T02:24:11.327