there is a question：

" If a bottle of soda costs \$1 and you can exchange two empty bottles for one soda, how many sodas can you drink with \$20 "

calculateTotalDrinks[initialMoney_] :=
Module[{drink = initialMoney, empty = initialMoney, newDrinks},
NestWhile[(newDrinks = Quotient[#[[2]], 2];
drink += newDrinks;
empty = newDrinks + Mod[#[[2]], 2];
{drink, empty}) &, {drink, empty}, #[[2]] >= 2 &][[1]]];

calculateTotalDrinks@20


out: 39

What better way?

• What do you mean by "after drinking two empty bottles for a bottle of soda"? Apr 14 at 10:17
• @xzczd The translation is not quite accurate, I have revised it Apr 14 at 10:19

exchange[{money_, emptybottle_, soda_}] :=
drink@{0, Mod[emptybottle, 2], money + Quotient[emptybottle, 2]}

drink[{money_, emptybottle_, soda_}] /; soda > 0 :=
exchange@{money, emptybottle + Sow@soda, 0}

Reap[exchange@{20, 0, 0}][[-1, 1]] // Total
(* 39 *)


A slightly different implementation:

exchange[money_, emptybottle_, soda_, {record___}] :=
drink[0, Mod[emptybottle, 2], money + Quotient[emptybottle, 2], {record}]

drink[money_, emptybottle_, soda_?Positive, {record___}] :=
exchange[money, emptybottle + soda, 0, {record, soda}]

exchange[20, 0, 0, {}]
(* drink[0, 1, 0, {20, 10, 5, 2, 1, 1}] *)

Total@Last@%
(* 39 *)

• Why use the Reap and Sow functions? incomprehension? Apr 14 at 10:35
• @我心永恒 What do you mean by "incomprehension?"? Apr 14 at 11:02

s price of soda without bottle, b price of empty bottle, k number of drunk sodas.

SolveValues[{s + b == 1, 2 b == s + b, k s + b == 20}, k, {s, b}] // Floor


{39}

• There is no need for Floor. Why did you add it? Apr 14 at 12:14
• @mattiav27 In this special case not but in general yes. For example if it was three empty bottles for one soda instead of two. Apr 14 at 12:30