Skip to content

Instantly share code, notes, and snippets.

@jslegers
Last active January 8, 2016 04:19
Show Gist options
  • Save jslegers/202634f71f4814ca550c to your computer and use it in GitHub Desktop.
Save jslegers/202634f71f4814ca550c to your computer and use it in GitHub Desktop.
self descriptive number
<?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