The satellite's counterweights
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- lists
- operations
Problem
Yuki Tanaka is adjusting a satellite's ballast before launch. On the table she has loose pieces of different masses, and she needs to put together an exact mass. Before choosing, she wants to know how many options she has.
Write a function that takes masses, a list of positive whole numbers with the mass of each piece (it may be empty and masses may repeat), and target, a whole number of 1 or more. Return a whole number: in how many ways you can pick some pieces, each one at most once, so that their masses add up to exactly target. The order you pick them in does not matter. Each piece counts on its own, even if it weighs the same as another: if there are two 5s, picking one or the other gives two different ways.
With [2, 3, 5, 5, 8] and target 10 there are 4 ways: 2 + 8, the two 5s together, 2 + 3 with the first 5, and 2 + 3 with the second 5. With [4, 6, 1, 3] and target 7 there are 2: 4 + 3 and 6 + 1. If no combination hits the target exactly, return 0.
Examples
The example
[2, 3, 5, 5, 8], 10 → 4
Two ways
[4, 6, 1, 3], 7 → 2
No combination gets there
[4, 6], 5 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def ways(masses, target):
passJavaScript
function ways(masses, target) {
}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.