self descriptive number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// PHP implementation of my solution for James Grimes's puzzle @ https://www.youtube.com/watch?v=K6Qc4oK_HqY | |
// The following function calculates the (only) self descriptive number for any number of digits | |
// | |
// With "self descriptive number", I mean : | |
// ------------------- | |
// The first digit tells me how many zeros are in the number | |
// The second digit tells me how many ones are in the number | |
// The third digit tells me how many twos are in the number | |
// You continue this pattern until the last digit | |
// | |
// The function returns the boolean value "false" when no self descriptive number exists | |
function selfreferential($digits) { | |
$c = [array_fill(0, $digits, 0), []]; | |
$c[0][0] = $digits - 1; | |
while (!empty(array_diff_assoc($c[0], $c[1]))) { | |
if ($digits < 7 || $digits > 13) | |
return false; | |
for ($i = $digits - 1; $i >= 0; $i--) { | |
$v = isset($c[1][$i]) ? $c[1][$i] : 0; | |
if ($c[0][$i] !== $v) { | |
$c[0][$i] = $v; | |
$c[1] = array_count_values($c[0]); | |
for ($i = 0; $i <= $digits - 1; $i++) { | |
$c[1][$i] = isset($c[1][$i]) ? $c[1][$i] : 0; | |
} | |
ksort($c[1]); | |
break; | |
} | |
} | |
} | |
return implode('', $c[0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment