|
<?php |
|
/** |
|
* Desafio Lojacorr - How Many Houses Buy With My Budget |
|
* https://gist.github.com/leohmoraes/fa5a60f5087f8ee5f0328b909b67e029 |
|
* @TODO: Adicionar verificações e validações para os parâmetros de entrada |
|
* @TODO: Tratar e testar valores em reais/dolar. |
|
* @TODO: Separar o código em tarefas específicas |
|
* Para rodar o código: php solve.php ou ... |
|
* teste online em: https://onecompiler.com/php/3xtjsrb4a |
|
* teste online em: https://app.codingrooms.com/w/44qCvaibXnBI |
|
*/ |
|
|
|
//array house_sales with prices; |
|
$house_prices = [100.5, 600, 200, 800, 400, 500, 100, 800, 900, 1000]; |
|
|
|
function buy_max_houses($house_prices, $budget_init = 400) |
|
{ |
|
$budget = $budget_init; |
|
|
|
//order prices from lowest to highest; |
|
sort($house_prices); |
|
$houses_bought = 0; //qty |
|
$houses_bought_total = 0; //$ |
|
$houses = []; //price item |
|
|
|
foreach ($house_prices as $house_price) { |
|
if ($house_price <= $budget) { |
|
$houses_bought++; |
|
$budget -= $house_price; |
|
$houses_bought_total += $house_price; |
|
$houses[] = $house_price; |
|
} |
|
} |
|
$houses = "\$" . implode(", $", $houses); |
|
|
|
// saída mais detalhada |
|
/* |
|
echo "O orçamento de \${$budget_init} " . |
|
"\nfoi possível comprar {$houses_bought} casa(s), " . |
|
"\ngastando um total de \${$houses_bought_total}. " . |
|
"\nSaldo do orçamento de \${$budget}. " . |
|
"\nTendo os seguintes valores investidos: {$houses}\n"; |
|
*/ |
|
$results = [ |
|
'qte_casas' => $houses_bought, |
|
'total_gasto' => $houses_bought_total, |
|
"orcamento" => $budget_init, |
|
'saldo' => $budget, |
|
'valores_individuais' => $houses, |
|
]; |
|
// resultado solicitado: |
|
// qtd de casas, valor investido |
|
echo "\nQuantidade de casas: {$results['qte_casas']}\nValor investido: \${$results['total_gasto']}\n"; |
|
} |
|
|
|
//input the budget initial |
|
echo "Digite o orçamento inicial: "; |
|
fscanf(STDIN, "%s\n", $budget_init); |
|
|
|
|
|
buy_max_houses($house_prices, $budget_init); |