xkcd287.frink

Download or view 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[]  
   }
}


Download or view 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 19971 days, 7 hours, 37 minutes ago.