group php array on strlen closed to the $limit variable

Viewed 47

Need some help. I want to group my array based on strlen that is closed to the $limit and sort on total length

My array looks likes this:

(
    [0] => Isofix
    [1] => Parkinghelp
    [2] => Rainsensor
    [3] => Led light
    [4] => Hill Start Assist
    [5] => Dynamic brake light
    [6] => Cornering Brake Control
)

so for example i want to sum the best option that is close to 29.

So ideally this is the combinations that i want to find

Cornering Brake Control(23) + Isofix(6) = length 29

Dynamic brake light(19) + Rainsensor(10) = 29

Hill Start Assist(17) + Parkinghelp(11) = 28

Led light = 90

My final array should look something like this:

Array
(
    [0] => Cornering Brake * Control Isofix
    [1] => Dynamic brake light * Rainsensor
    [2] => Hill Start Assist * Parkinghelp
    [3] => Led light
)


// code  

$limit = 29;

$arr = array('Isofix', 'Parkinghelp', 'Rainsensor', 'Led light', 'Hill Start Assist', 'Dynamic brake light', 'Cornering Brake Control');

foreach ($arr as $key => $value) {
  echo $value . ' - ' . strlen($value);
  echo "\n";
}

// this is what i have so far. But it's not checking every possibility

$limit = 29;
$result9009 = array(''); 
$cur_key = 0;
foreach ($arr as $word) {
  if (strlen($result9009[$cur_key]) + strlen($word) <= $limit) {
        $result9009[$cur_key] .= ' * ' . $word;
     } else {
        $result9009[] = $word;
        $cur_key++;
     }
  }

1 Answers

Hope this helps, you should add the last case and try to improve complexity

<?php
function cmp($a, $b)
{
    return $a["key"] >= $b["key"];
}

$limit = 29;

$arr = array('Isofix', 'Parkinghelp', 'Rainsensor', 'Led light', 'Hill Start Assist', 'Dynamic brake light', 'Cornering Brake Control');
$result=[];
$arrayToCheckin=[];
for ($i=0; $i < count($arr); $i++) {
    for ($j=$i+1; $j < count($arr); $j++) {
        $key = abs(strlen($arr[$i]) + strlen($arr[$j]) - $limit);
            $arrayToCheckin[] = [
                'key'=>$key,
                'elem1'=>$arr[$i],
                'elem2'=>$arr[$j]
                ];
    }
}
usort($arrayToCheckin, "cmp");
$control = [];
foreach ($arrayToCheckin as $val) {
    if(!in_array($val['elem1'], $control) && !in_array($val['elem2'], $control)) {
        $result[] =  $val['elem1'].'*'.$val['elem2'];   
        $control[] = $val['elem1'];
        $control[] = $val['elem2'];
    }
}
var_export($result);

output

array (
  0 => 'Isofix*Cornering Brake Control',
  1 => 'Rainsensor*Dynamic brake light',
  2 => 'Parkinghelp*Hill Start Assist',
)
    
Related