-1

This seems trivial but I'm baffled that I haven't been able to come to a solution on this. What I'm trying to do is:

Input ->  14025
Output -> 10245

Input ->  171
Output -> 117

And so on...

asprin
  • 9,579
  • 12
  • 66
  • 119
  • Calculate all the permutations, add in an array and sort? – DarkBee Dec 11 '17 at 12:42
  • @DarkBee Good idea...let me see how that goes – asprin Dec 11 '17 at 12:45
  • 1
    @Kaddath Yes, but a number starting with 0 doesn't really work in the real world. I have to maintain the number of digits and so 01245 != 1245 – asprin Dec 11 '17 at 12:45
  • This is a perfect example to start with [TDD](https://stackoverflow.com/questions/4303/why-should-i-practice-test-driven-development-and-how-should-i-start) – Nico Haase Dec 11 '17 at 12:51

2 Answers2

5
$input = 140205;

$temp = str_split($input);
sort($temp);
// find the 1st non-zero digit
$f = current(array_filter($temp));
// remove it from the array
unset($temp[array_search($f, $temp)]);
echo $output = $f . join($temp);  // 100245

demo

splash58
  • 26,043
  • 3
  • 22
  • 34
  • That's a nice approach – iainn Dec 11 '17 at 12:50
  • I found a way myself from the suggestions posted in the comment section. But I'll go ahead and mark this as the accepted answer because this is definitely a better solution than mine. I'll post mine too just for sake of information of others. – asprin Dec 11 '17 at 12:56
  • Glad to help. Good luck! – splash58 Dec 11 '17 at 12:57
0

A bit more verbose, but similar to previous answer

function smallestNumberFromDigits($string) {
    //split string to digits
    $array = str_split($string);
    //sort the digits
    sort($array);

    //find the first digit larger than 0 and place it to the begining of array
    foreach($array as $i => $digit) {
        if($digit > 0) {
            $tmp = $array[0];
            $array[0] = $digit;
            $array[$i] = $tmp;
            break;
        }
    }

    //return the imploded string back
    return implode("", $array);
}
flynorc
  • 829
  • 6
  • 13