I want a hint on a efficient algorithm of solving the following:
(Okay, The question was not that, I just made this for simplicity).
Example: Out of N Advert boards there should be M advert of a company in K consecutive boards. and the Adverts will be used such a way that only MINIMUM number of Adverts will be used
if N=3,K=2,M=1. The answer will be one 010;
if N=6, K=3, M=2 the answer will be 6.
011011,
011101,
011110,
101101,
101110,
110110.
I took the approach of Creating all the combinations(with binary approach) with iterative and recursive method.After that I filtered it. It is working well except if N is big it will crash.(as expected). So Is there any efficient method of solving these?
I just took another approach but it is not going to well .. :(
Second approach
if($n%$k == 0){
$perm = $m*($n/$k);
}else{
$perm = $m*ceil($n/$k);
}
Then I will do the nCr... and now I'm lost
First Approach
<?php
$n = $input1;$k = $input2;$l=$input3; $total = 0;
$flag = false;$arrays = array();$z=0;$min=$n;$x=0;
$total_permutations = pow(2,$n);
for($i=0;$i<$total_permutations;$i++){
$binary = base_convert($i, 10, 2);
$binary = str_pad($binary, $n,"0", STR_PAD_LEFT);
for($j=0;$j<=($n-$k);$j++){
$flag = false;$x=0;
for($m=0;$m<$k;$m++){
$x += intval($binary{$j+$m});
}
if($x<$l){
$flag = true;
break;
}
}
if(!$flag){
$arrays[$z]=str_split($binary);
$arrays[$z] = array_map('intval', $arrays[$z]);
$z++;
echo $binary."<br />";
}
unset($binary);
}
$min = min(array_map('array_sum',$arrays));
echo "------------<br />";
foreach($arrays as $val){
$sum = array_sum($val);
if($sum == $min){
echo implode("",$val);echo "<br>";
$total++;
}
}
return $total;
}
?>