Skip to the content

Grandpa's spoons

Problem

Grandpa Anselmo is about to bake the bread from his mother's recipe, but he lost the measuring cup. He still has a few spoons of different sizes, and he can fill each one as many times as he likes. Before he starts, he wants to know how many ways he has to measure the milk.

Write a function that takes sizes, a list of distinct positive whole numbers (how many milliliters each spoon holds; they come in any order and the list may be empty), and amount, a whole number from 1 to 30: the milliliters the recipe calls for. Return a whole number: how many different ways there are to add up to exactly that amount. Only how many times you use each spoon matters, not the order: pouring 2 and then 1 is the same as pouring 1 and then 2.

With spoons of 1, 2 and 5 and a recipe of 6 there are 5 ways: the 1 six times; four of 1 and one of 2; two of 1 and two of 2; three of 2; one of 1 and one of 5. With spoons of 3 and 4 and a recipe of 10 only 3 + 3 + 4 works, so it returns 1. If there is no way to measure it exactly, return 0.

Examples

  • The first example

    [1, 2, 5], 6 → 5

  • Starting with the biggest one does not work

    [3, 4], 10 → 1

  • No way to do it

    [3, 4], 5 → 0

  • The spoons come out of order

    [5, 1, 2], 6 → 5

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def spoons(sizes, amount):
    pass

JavaScript

function spoons(sizes, amount) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(2ⁿ) challenges

See all challenges →