Skip to content

Instantly share code, notes, and snippets.

@a1ip
Created July 11, 2014 14:15
Show Gist options
  • Select an option

  • Save a1ip/a2cc553237eeb9adac20 to your computer and use it in GitHub Desktop.

Select an option

Save a1ip/a2cc553237eeb9adac20 to your computer and use it in GitHub Desktop.
Filename with two dots

http://eloquentjavascript.net/2nd_edition/preview/03_functions.html
Consider this puzzle: by starting from the number 1 and repeatedly either adding 5 or multiplying by 3, an infinite amount of new numbers can be produced. How would you write a function that, given a number, tries to find a sequence of such additions and multiplications that produce that number? For example, the number 13 could be reached by first multiplying by 3 and then adding 5 twice, whereas the number 15 cannot be reached at all.

Here is a recursive CoffeeScript solution:

findSolution = (target) ->
  find = (start, history) ->
    if start is target
      history
    else if start > target
      null
    else
      find(start + 5, "(#{history} + 5)") or find(start * 3, "(#{history} * 3)")
  find 1, "1"
console.log findSolution(24)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment