Suppose a number is given which is of positive integer type, e.g: 312. Please help me to write a program in PHP which convert that given number to a new number having same number of digits and all the digits of the new number must be equal to any of the digits of the given number (e.g: 333, 111, 222 by either decrementing or incrementing each digit by 1 at a time only). But print only that sequence of digits which takes lesser number of steps to generate the sequence and also print the number of steps taken to generate that sequence.
Explanation: Input: A positive integer N (e.g: 312)
converting the number(312) to the sequence of 3
3 2 2
3 3 2
3 3 3
here number of steps = 3
Now, converting the number(312) to the sequence of 1
2 1 2
1 1 2
1 1 1
here number of steps = 3
and finally converting the number(312) to the sequence of 2
2 1 2
2 2 2
here number of steps = 2
So, Output: 222
Number of steps: 2
Here's what I tried but lost
<?php
$num = 312;
$arr_num = array_map('intval', str_split($num));
//steps taken for each sequence will be stored in this array
$steps = array();
//printing number
for($i = 0; $i < count($arr_num); $i++)
echo $arr_num[$i];
//calculation
for($i = 0; $i < count($arr_num); $i++) {
$count = 0;
for($j = 0; $j < count($arr_num); $j++) {
if($arr_num[$i] == $arr_num[$j])
++$j;
elseif($arr_num[$i] > $arr_num[$j]) {
while($arr_num[$j] != $arr[$i]) {
$arr_num[$j] += 1;
$count++;
}
}
else {
while($arr_num[$j] != $arr_num[$i]) {
$arr_num[$j] -= 1;
$count++;
}
}
}
//pushing the count to steps array for each sequence
array_push($steps, $count);
}
//I am stuck here...can't find the further solution
?>