<?php
function gray_code($bits) {
if ($bits == 1) {
return array('0', '1');
}
else {
$codes = gray_code($bits - 1);
return array_merge(array_map(function ($v) { return '0' . $v; }, $codes),
array_map(function ($v) { return '1' . $v; }, array_reverse($codes))
);
}
}
$value = 115;
$bin = decbin($value);
// get sufficient gray codes to cover the input
$gray_codes = gray_code(strlen($bin));
$codes = array_flip($gray_codes);
echo "$bin takes {$codes[$bin]} steps to reduce to 0\n";
// echo the steps
for ($i = $codes[$bin]; $i >= 0; $i--) {
echo $gray_codes[$i] . PHP_EOL;
}
- Output for 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.29, 8.2.0 - 8.2.23, 8.3.0 - 8.3.11
- 1110011 takes 93 steps to reduce to 0
1110011
1110010
1110110
1110111
1110101
1110100
1111100
1111101
1111111
1111110
1111010
1111011
1111001
1111000
1101000
1101001
1101011
1101010
1101110
1101111
1101101
1101100
1100100
1100101
1100111
1100110
1100010
1100011
1100001
1100000
0100000
0100001
0100011
0100010
0100110
0100111
0100101
0100100
0101100
0101101
0101111
0101110
0101010
0101011
0101001
0101000
0111000
0111001
0111011
0111010
0111110
0111111
0111101
0111100
0110100
0110101
0110111
0110110
0110010
0110011
0110001
0110000
0010000
0010001
0010011
0010010
0010110
0010111
0010101
0010100
0011100
0011101
0011111
0011110
0011010
0011011
0011001
0011000
0001000
0001001
0001011
0001010
0001110
0001111
0001101
0001100
0000100
0000101
0000111
0000110
0000010
0000011
0000001
0000000
preferences:
50.79 ms | 409 KiB | 5 Q