Last active
April 22, 2022 23:46
-
-
Save mallardduck/349ee1412d2e487a09c14103db6d757f to your computer and use it in GitHub Desktop.
Apply the "Work It" transformation to an Integer with PHP
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 | |
function missyElliott(int $id): int { | |
if ($id > 4294967295) { | |
throw new \RuntimeException('Maximum integer size is 4_294_967_295'); | |
} | |
// Int to Binary - ensure at least 32 char long binary string | |
$binaryInt = str_pad(decbin($id), 32, '0', STR_PAD_LEFT); | |
// Split into workIt array | |
$workIt = str_split($binaryInt, 1); | |
// put my thing down function | |
$putMyThingDown = static function($thing) use (&$workIt) { | |
array_unshift($workIt, $thing); | |
}; | |
// Pop the last item off and unshift (prepend) it...by reference | |
$putMyThingDown(array_pop($workIt)); | |
// flipIt function to invert the binary's 1's and 0's | |
$flipIt = static function(&$it) { | |
return array_map(static function($n) { | |
$bool = filter_var($n, FILTER_VALIDATE_BOOLEAN); | |
$invertBool = match ($bool) { | |
true => false, | |
false => true, | |
}; | |
// convert to int and then string to ensure we get string 1's and 0's out | |
return (string) (int) $invertBool; | |
}, $it); | |
}; | |
// Actually flip it now | |
$workIt = $flipIt($workIt); | |
// Now we reverse it | |
$workIt = array_reverse($workIt); | |
// Implode the array back to a string and then back to a Decimal integer | |
return bindec(implode('', $workIt)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment