Lilavati's sums
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- strings
- indexes
Problem
In twelfth-century India, the mathematician Bhaskara wrote a book of problems and named it after his daughter, Lilavati. At home they played this game: Lilavati wrote down a row of digits and a total, and you had to split the row into numbers that added up to that total.
You get digits, a string of 1 to 10 digits, all from 1 to 9 (there are no zeros), and target, a whole number from 1 up. Splitting the row means choosing between which digits to cut: each piece is read as a number, the digits keep their order and every one of them is used. You can cut in as many places as you like, and not cutting at all, keeping the whole number, also counts.
Return, as a whole number, how many ways there are to split the row so that the pieces add up to target.
With "1111" and 13 three ways work: 11 + 1 + 1, 1 + 11 + 1 and 1 + 1 + 11, so you return 3. With "2125" and 28 two work: 21 + 2 + 5 and 2 + 1 + 25. If no way works, return 0.
Examples
The first example
"1111", 13 → 3
The second example
"2125", 28 → 2
Single digits only
"123", 6 → 1
Leaving digits unused is not allowed
"919", 9 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def splits(digits, target):
passJavaScript
function splits(digits, 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.
More O(2ⁿ) challenges
- Mansa Musa's bags of goldrecursion · lists · indexes
- Modules on rocketsrecursion · lists · booleans · division
- Monday's operating roomsrecursion · lists · comparisons
- Spelling with elementsrecursion · strings · indexes
- Splitting the honeyrecursion · lists · comparisons
- The block partyrecursion · lists · loops