Skip to content

Instantly share code, notes, and snippets.

@cjgratacos
Created November 1, 2017 18:39
Show Gist options
  • Save cjgratacos/f1dd0fa39cac9baae7eb4abbe200b1c6 to your computer and use it in GitHub Desktop.
Save cjgratacos/f1dd0fa39cac9baae7eb4abbe200b1c6 to your computer and use it in GitHub Desktop.
Simple Algorigthm: Closest biggest adjacent number
<?php
// By Carlos Gratacos
// Input: 1 interger number
// Output: false-> if not possible, else return return the smaller or greater input by switching adjacent digit
// Biggest closest to the original one
// 123 -> 132
//
// 254 -> 524
//
// 1653 -> (1635, 1653) -> 6135
//
// 71132 -> 71312
//
// 9876543210 -> false
//
function biggest(int $x) {
$str_num = (string)$x;
$biggest = rotation($str_num);
return $biggest > $x ? $biggest: false;
}
// Rotate
function rotation(string $num) {
$arr = str_split($num);
$stop = null;
for($i = strlen($num)-1; $i > 0; $i-- ) {
if ($arr[$i] > $arr[$i-1]) {
$last = $arr[$i];
$arr[$i] = $arr[$i-1];
$arr[$i-1] = $last;
$stop = $i;
break;
}
}
if(isset($stop)){
for($i = $stop; $i < strlen($num)-1; $i++ ) {
if ($arr[$i] > $arr[$i+1]) {
$last = $arr[$i];
$arr[$i] = $arr[$i+1];
$arr[$i+1] = $last;
}
}
}
return (int)implode('', $arr);
}
function test(){
$arr = [123,254, 1653, 0, 71132,45325, 9876543210];
foreach($arr as $val) {
$x =biggest($val);
echo $val." biggest number is " . ($x?:"None") . "<br>";
}
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment