Clash-free rhythms
- O(2ⁿ) · Legendary
- Full plan
- Python
- JavaScript
- recursion
- strings
- lists
Problem
Nico is learning the drums and wants to try every rhythm that fits in a bar of n beats. On each beat he either hits or rests, but his teacher gave him a rule: never two hits in a row, because his hands are not that fast yet.
Write a function that takes n, a whole number from 0 up, and returns a list of every rhythm that follows the rule, with no repeats. Each rhythm is a string of n characters: "x" is a hit and "." is a rest. The list goes in alphabetical order, where the dot comes before the x. The bar does not wrap around: a rhythm can start and end with a hit.
With n equal to 3 it returns ["...", "..x", ".x.", "x..", "x.x"]: "xx.", ".xx" and "xxx" are left out because they have two hits in a row. With n equal to 1 it returns [".", "x"]. With n equal to 0 there is a single rhythm, the one with no beats: it returns [""].
Examples
The three-beat example
3 → ["...", "..x", ".x.", "x..", "x.x"]
One beat
1 → [".", "x"]
Four beats
4 → ["....", "...x", "..x.", ".x..", ".x.x", "x...", "x..x", "x.x."]
No beats
0 → [""]
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def rhythms(n):
passJavaScript
function rhythms(n) {
}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.