Dubfx Posted December 31, 2014 Report Share Posted December 31, 2014 Se da un magazin online pe care se vand sa spunem ... cutite de bucatarie.Toate cutitele AU ACELASI PRET 99 RON.La adaugarea in cos se aplica un discount astfel:- la 2 produse comandate pretul total o sa fie de 149 lei- la 3 produse comandate pretul total o sa fie de 199 lei - la 4 produse comandate pretul total o sa fie de 199 (grupul de 3 produse reduse) + 99 lei (al patrulea produs la pret intreg) = 298 lei- la 5 produse comandate pretul total o sa fie de 199 (grupul de 3 produse reduse) + 149 lei (grupul de 2 produse cu discount) = 348 lei.... so on.Care este algoritmul?HINT: repet, toate produsele au acelasi pret.P.S. Un an nou fericit! Quote Link to comment Share on other sites More sharing options...
GarryOne Posted December 31, 2014 Report Share Posted December 31, 2014 Ceva facut rapid.<?php$pret1 = 99;$pret2 = 149;$pret3 = 199;$cant = 9;$pret_final = 0;while($cant > 0) { if($cant - 3 >= 0) { $cant -= 3; $pret_final += $pret3; } else if($cant - 2 >= 0) { $cant -= 2; $pret_final += $pret2; } else { $cant -= 1; $pret_final += $pret1; }}echo $pret_final?> Quote Link to comment Share on other sites More sharing options...
Dubfx Posted December 31, 2014 Author Report Share Posted December 31, 2014 E ok, dar se rezolva si altfel. Quote Link to comment Share on other sites More sharing options...
GarryOne Posted December 31, 2014 Report Share Posted December 31, 2014 (edited) Sau, alta varianta mai optimizata un pic<?php$preturi = array(1 => 99, 2 => 149, 3 => 199);$cant = 5;$pret_final = 0;for($i=3; $i >= 1;$i--) { while($cant >= $i) { $cant = $cant - $i; $pret_final += $preturi[$i]; }}echo $pret_final?>Inspirat din algoritmul descompunerii in factori primi. Edited December 31, 2014 by GarryOne Quote Link to comment Share on other sites More sharing options...
Dubfx Posted December 31, 2014 Author Report Share Posted December 31, 2014 Bun si asa.Varianta mea e : $primprod = 99; //lei $x=6; //cantitate $a=floor(($x-1)/3); $b=($x-1)%3; $total = ($primprod+(199*$a)+(50*$); $discount = ($primprod*$x)-($primprod+(199*$a)+(50*$); Quote Link to comment Share on other sites More sharing options...
Byte-ul Posted December 31, 2014 Report Share Posted December 31, 2014 Varianta mea: (probabil cea mai simpla)int n = 5;int i = n/3*199 + (n%3)/2*149 + (n%3)%2*99; Quote Link to comment Share on other sites More sharing options...
Dubfx Posted December 31, 2014 Author Report Share Posted December 31, 2014 Practic si util Quote Link to comment Share on other sites More sharing options...