Guest User

Little RP puzzle

a guest
Apr 5th, 2017
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. 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 :-)
  2.  
  3.  
  4. 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]
  5.  
  6. 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:
  7. getNthElement(0, [10, 20, [[30, 40], 50], 60]) => 10
  8. getNthElement(1, [10, 20, [[30, 40], 50], 60]) => 20
  9. getNthElement(2, [10, 20, [[30, 40], 50], 60]) => [[30, 40], 50]
  10. getNthElement(3, [10, 20, [[30, 40], 50], 60]) => [30, 40]
  11. getNthElement(4, [10, 20, [[30, 40], 50], 60]) => 30
  12. getNthElement(5, [10, 20, [[30, 40], 50], 60]) => 40
  13. getNthElement(6, [10, 20, [[30, 40], 50], 60]) => 50
  14. getNthElement(7, [10, 20, [[30, 40], 50], 60]) => 60
  15.  
  16.  
  17. If you think that this is too easy then go directly to task 2. That is: changeNthElement.
  18. It takes the index, the tree and a new element (which could be a number or an arbitrary tree).
  19. Same rules: no side effects, but instead pure functions. Examples:
  20.  
  21. changeNthElement(0, [10, 20, [[30, 40], 50], 60], 0) => [0, 20, [[30, 40], 50], 60]
  22. changeNthElement(2, [10, 20, [[30, 40], 50], 60], 0) => [10, 20, 0, 50], 60]
  23. changeNthElement(5, [10, 20, [[30, 40], 50], 60], 0) => [10, 20, [[30, 0], 50], 60]
  24. changeNthElement(7, [10, 20, [[30, 40], 50], 60], [[0]]) => [10, 20, [[30, 40], 50], [[0]]]
Advertisement
Add Comment
Please, Sign In to add comment