Skip to content

Instantly share code, notes, and snippets.

@leohmoraes
Last active February 16, 2022 16:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leohmoraes/fa5a60f5087f8ee5f0328b909b67e029 to your computer and use it in GitHub Desktop.
Save leohmoraes/fa5a60f5087f8ee5f0328b909b67e029 to your computer and use it in GitHub Desktop.
Desafio Lojacorr

Problema

Existem X casas à venda. Juntas essas casas valem I reais. Você tem um orçamento de B reais para gastar.

Qual o maior número de casas que você pode comprar com o orçamento?

OBS: Quantidade de casas e valor podem ser definidos da maneira que desejar, é possivel também efetuar pesquisas durante o desenvolvimento

Output

Ao final do processamento, exiba a quantidade de casas que puderam ser compradas, bem como o valor total gasto.

<?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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment