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 artlung 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
function sumOfDigits($num) {    $str = "{$num}";    $sum = 0;    for ($i=0;$i<strlen($str);$i++) {        $sum += (int)substr($str, $i, 1);    }    return $sum;}function hasDuplicateDigits($num) {    $str = "{$num}";    $pieces = array();    for ($i=0;$i<strlen($str);$i++) {        $pieces[] = substr($str, $i, 1);    }    return (count(array_unique($pieces)) != strlen($str));}// if you prefer the opposite functionfunction hasAllUniqueDigits($num) {    return (!hasDuplicateDigits($num));}$numbers = range(10000, 99999);foreach ($numbers as $num) {    if ( !hasDuplicateDigits($num) && (sumOfDigits($num) == 30)) {        print $num . "\n";    }}

Viewing all articles
Browse latest Browse all 9

Trending Articles



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