N
N
Nikolay2016-08-27 19:50:38
PHP
Nikolay, 2016-08-27 19:50:38

How to write the function of the largest number in php?

For example, from the numbers [3, 24, 4] we can compose the following: 3244, 3424, 2434, 2443, 4324, 4243 and the largest of them is 4324

$arrNum = [3, 24, 4];
$sizeArr = count($arrNum);
$fact = factorial($sizeArr);

while ((boolean)$sizeArr) {
    for ($j = (count($arrNum) - 1); $j; $j--) {
        list($arrNum[$j], $arrNum[$j - 1]) = [$arrNum[$j - 1], $arrNum[$j]];
        $arrSum[] = implode("",$arrNum);
    }
    $sizeArr--;
}

echo max($arrSum);

function factorial($n)
{
    $result = 1;
    for ($i=2; $i<=$n; $i++)
        $result *= $i;
    return $result;
}

This solution of mine only works with a small size ... but it is necessary to process [1, 34, 3, 98, 9, 76, 45, 4]
Help with the algorithm

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Muhammad, 2016-08-27
@zzzmaikzzz

<?php

$numbers = [1, 15, 3, 9800, 9, 76, 45, 9];
$arr = [];

$maxLength = max(array_map('strlen', $numbers));

foreach ($numbers as $number) {
    $key = str_pad((string) $number, $maxLength, $number);

  $arr[$key] = array_key_exists($key, $arr) ? $arr[$key].$number : $number;
}

ksort($arr);

$arr = array_reverse($arr);

var_dump(implode('', $arr));

Compare the numbers in the number one by one. At the first mismatch, the number with the larger digit is placed to the left:
45 36 => 4534

4 > 6  // первое число ставится влево 

928 998 => 998928

9 = 9
2 < 9 // второе число ставится влево

This is if their lengths are equal. If not, then just start the comparison from the beginning:
456 4

4 = 4
5 > 4 // начинаем сравнивать с начала, первое число ставится влево 

928 92

9 = 9
2 = 2
8 < 9 // начинаем сравнивать с начала, второе число ставится влево

I think I didn't explain well, but what can I do?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question