This code takes a number like 2017 and returns the NEXT highest (not total highest, like 7021) number, so in this case 2071
I understand every bit of except the if (($key = array_search($currentNumber, $tmpArray, true)) !== false) { unset($tmpArray[$key]);
— what exactly is happening here? Please help and I will accept immediately 🙂
I get that $key
is either true or false if the current number is found in the tmpArray variable, but why is it set to !==
false? Instead of ===
true? And what does unsetting do in this case?
<?php function nextBigger(int $n): int { $numbers = str_split((string)$n); $start = $n+ 1; rsort($numbers); $end = (int)implode('', $numbers); for ($i = $start; $i <= $end; $i++) { $tmpArray = $numbers; $currentNumbers = str_split((string)$i); foreach ($currentNumbers as $currentNumber) { if (($key = array_search($currentNumber, $tmpArray, true)) !== false) { unset($tmpArray[$key]); # What is the effect of this?? } else { break; } } if (empty($tmpArray)) { return $i; } } return -1; }
Advertisement
Answer
The function takes the input (2017), and first finds the largest number than can be made with those digits, by ordering them in descending order (7210).
It then loops over every number between those two bounds*, and for each digit in that number, it sees if that digit is “available” in the input. Annotated below:
# Assign a temporary copy of the digits we have available $tmpArray = $numbers; // ... # If the digit is still available in our temp copy, array_search will return the key if (($key = array_search($currentNumber, $tmpArray, true)) !== false) { # If we matched a key, we have to remove it from the temporary copy, # so that we don't use it twice unset($tmpArray[$key]); } else { # Otherwise, if it's not available to use then we know this number # isn't a viable candidate, and we can break the loop break; } # If we've reached this point and the temporary array is empty, # we know we've used all the digits. # Because we're returning from the function this can only happen once, # at the next highest number after the input if (empty($tmpArray)) { return $i; }
* As an aside, this is probably not the most efficient way of performing this task