xkcd287.frink

View or download xkcd287.frink in plain text format


/** This solves the problem posed in the xkcd cartoon #287:

    https://xkcd.com/287/
*/

items = [["Mixed fruit",       2.15],
         ["French fries",      2.75],
         ["Side salad",        3.35],
         ["Hot wings",         3.55],
         ["Mozzarella sticks", 4.20],
         ["Sampler plate",     5.80]]

target = 15.05

r = new array
for [item, price] = items
   r.push[new range[0, target div price]]

COMBINATIONS:
multifor c = r
{
   sum = 0
   for i = rangeOf[c]
   {
      sum = sum + c@i * items@i@1
      if sum > target
         next COMBINATIONS i   // Note the fast bailout to the specified level
   }

   // Found a solution?  Print it legibly for human consumption!
   if sum == target
   {
      for i = rangeOf[c]
         if c@i != 0
            println[c@i + " " + items@i@0]
      println[]  
   }
}


View or download xkcd287.frink in plain text format


This is a program written in the programming language Frink.
For more information, view the Frink Documentation or see More Sample Frink Programs.

Alan Eliasen was born 17592 days, 6 hours, 29 minutes ago.