Skip to content

Instantly share code, notes, and snippets.

@0racle
Last active April 9, 2018 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0racle/03cc5bf4584520dc1bee03b5de4592b6 to your computer and use it in GitHub Desktop.
Save 0racle/03cc5bf4584520dc1bee03b5de4592b6 to your computer and use it in GitHub Desktop.
Possible Number of Pies

/r/dailyprogrammer - [2018-03-28] Challenge #355 [Intermediate] - Link

This is not my solution... Just a modification I made of /u/ruincreep's solution while playing around.

my %recipes =
  'Pumpkin pie' => (:1Pumpkin, :3Eggs, :4Milk, :3Sugar).Bag,
  'Apple pie'   => (:1Apple,   :4Eggs, :3Milk, :2Sugar).Bag;

sub solve-pies($items) {
    %recipes.kv.map(-> $name, $recipe {
        $items  $recipe === $recipe
          ?? solve-pies($items  $recipe).map(*  $name)
          !! Empty.Bag
    }).flat
}

sub format-pies($pies) {
    $pies.map({ "{.value} {.key}{'s' if .value != 1}" }).join(' and ')
}

for $*ARGFILES.lines -> $line {
    my $items = (<Pumpkin Apple Eggs Milk Sugar> Z=> $line.split: ',').Bag;
    say format-pies(solve-pies($items).max(*.total));
}

INPUT:

10,14,10,42,24
12,4,40,30,40
12,14,20,42,24

OUTPUT:

2 Pumpkin pies and 1 Apple pie
4 Pumpkin pies and 4 Apple pies
4 Pumpkin pies and 2 Apple pies

Alternatively...

for $*ARGFILES.lines -> $line {
    my $items = (<Pumpkin Apple Eggs Milk Sugar> Z=> $line.split: ',').Bag;
    my @best = solve-pies($items).classify(*.total).max.values.map(|*.unique);
    say @best.map(&format-pies).join("\n -OR- ") ~ "\n";
}

OUTPUT:

2 Pumpkin pies and 1 Apple pie
 -OR- 3 Pumpkin pies

4 Pumpkin pies and 4 Apple pies
 -OR- 5 Pumpkin pies and 3 Apple pies
 -OR- 6 Pumpkin pies and 2 Apple pies

4 Pumpkin pies and 2 Apple pies
 -OR- 5 Pumpkin pies and 1 Apple pie
 -OR- 6 Pumpkin pies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment