Quantcast
Channel: How would I find all sets of N single-digit, non-repeating numbers that add up to a given sum in PHP? - Stack Overflow
Viewing all articles
Browse latest Browse all 9

Answer by Josephine for How would I find all sets of N single-digit, non-repeating numbers that add up to a given sum in PHP?

$
0
0

Let's write f(30,5,1) for the answer to your problem. The 30 indicates the desired sum, the 5 indicates the number of digits which should add to the desired sum, and the 1 indicates the minimal acceptable digit. In this form, you can solve the problem recursively. For example,

f(30,5,b) = sum(i = 1..9) f(30-i,4,i+1)

We are effectively exhausting over the lowest value i occurring in the combination you seek. If you think more carefully about the maximum possible value of i (it can't be too large since it's the minimum of the digits), and add some appropriate bail-out conditions, then you'll have a very fast solution.


Viewing all articles
Browse latest Browse all 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>