3
$\begingroup$

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?

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

2 Answers 2

5
$\begingroup$
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 *)
$\endgroup$
2
  • $\begingroup$ Why use the Reap and Sow functions? incomprehension? $\endgroup$ Apr 14 at 10:35
  • $\begingroup$ @我心永恒 What do you mean by "incomprehension?"? $\endgroup$
    – xzczd
    Apr 14 at 11:02
9
$\begingroup$

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}
$\endgroup$
2
  • $\begingroup$ There is no need for Floor. Why did you add it? $\endgroup$
    – mattiav27
    Apr 14 at 12:14
  • 1
    $\begingroup$ @mattiav27 In this special case not but in general yes. For example if it was three empty bottles for one soda instead of two. $\endgroup$ Apr 14 at 12:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.