D
D
Denis2018-06-19 16:02:04
PHP
Denis, 2018-06-19 16:02:04

Algorithm for selecting the 5 closest amounts when buying a product?

Somehow I got confused in the heat .... The
question is there are denominations in currency, for example , and you need to display, for example, the 5 nearest amounts that the user can give for the purchase of goods, for example, if the goods cost
$nominals = [1,2,5,10,20,50,100];

$productCost = 30;
// вывести 30, 40, 50, 100;
$productCost = 312;
// вывести 312,315,320,350

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2018-06-19
@sidni

In python like this:

coins = [1, 2, 5, 10, 20, 50, 100]

def roundup(cost):
    return sorted(set((cost + c - 1) // c * c for c in coins))

print(roundup(30))   # [30, 40, 50, 100]
print(roundup(312))  # [312, 315, 320, 350, 400]

and the specifics of arithmetic and php data structures - that's it yourself)
PS and more, where does 325 come from?

V
Vasya, 2018-06-19
@haramba

$key = array_search($sum, $nominals);
$sum5 = array_slice($nominals, $key, 5);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question