Skip to content

Instantly share code, notes, and snippets.

@wulab
Created September 6, 2015 06:45
Show Gist options
  • Select an option

  • Save wulab/96e400f68169db9dc8d1 to your computer and use it in GitHub Desktop.

Select an option

Save wulab/96e400f68169db9dc8d1 to your computer and use it in GitHub Desktop.
function findSolution(target) {
function find(start, history) {
if (start == target)
return history;
else if (start > target)
return null;
else
return find(start + 5, "(" + history + " + 5)") ||
find(start * 3, "(" + history + " * 3)");
}
return find(1, "1");
}
console.log(findSolution(24));
// → (((1 * 3) + 5) * 3)
@wulab
Copy link
Copy Markdown
Author

wulab commented Sep 6, 2015

find(1, "1")
  find(6, "(1 + 5)")
    find(11, "((1 + 5) + 5)")
      find(16, "(((1 + 5) + 5) + 5)")
        too big
      find(33, "(((1 + 5) + 5) * 3)")
        too big
    find(18, "((1 + 5) * 3)")
      too big
  find(3, "(1 * 3)")
    find(8, "((1 * 3) + 5)")
      find(13, "(((1 * 3) + 5) + 5)")
        found!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment