Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- There are two tasks. Both are about and ask for a (tail-) recursive and side-effect free solution. You can use any language to do this, and I would hope that at least one person from each of the three language teams will find a bit time to solve this :-)
- You have a tree which either contains ints or subtrees of ints, which themselves can contain the same. One example to represent such a tree in JavaScript could be this: [10, 20, [[30, 40], 50], 60]
- Now the first task is: write a function getNthElement which takes a zero-based index and a tree. It may call a (possibly tail-recursive) helper function, but there should be no state mutation. Here a list of correct/expected return values:
- getNthElement(0, [10, 20, [[30, 40], 50], 60]) => 10
- getNthElement(1, [10, 20, [[30, 40], 50], 60]) => 20
- getNthElement(2, [10, 20, [[30, 40], 50], 60]) => [[30, 40], 50]
- getNthElement(3, [10, 20, [[30, 40], 50], 60]) => [30, 40]
- getNthElement(4, [10, 20, [[30, 40], 50], 60]) => 30
- getNthElement(5, [10, 20, [[30, 40], 50], 60]) => 40
- getNthElement(6, [10, 20, [[30, 40], 50], 60]) => 50
- getNthElement(7, [10, 20, [[30, 40], 50], 60]) => 60
- If you think that this is too easy then go directly to task 2. That is: changeNthElement.
- It takes the index, the tree and a new element (which could be a number or an arbitrary tree).
- Same rules: no side effects, but instead pure functions. Examples:
- changeNthElement(0, [10, 20, [[30, 40], 50], 60], 0) => [0, 20, [[30, 40], 50], 60]
- changeNthElement(2, [10, 20, [[30, 40], 50], 60], 0) => [10, 20, 0, 50], 60]
- changeNthElement(5, [10, 20, [[30, 40], 50], 60], 0) => [10, 20, [[30, 0], 50], 60]
- changeNthElement(7, [10, 20, [[30, 40], 50], 60], [[0]]) => [10, 20, [[30, 40], 50], [[0]]]
Advertisement
Add Comment
Please, Sign In to add comment