Last active
August 29, 2015 14:14
-
-
Save nbdd0121/adae33f73e123fa4f36e to your computer and use it in GitHub Desktop.
24-points javascript calculator unoptimized / no parenthesis removal / only single answer is shown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function wrap(num) { | |
return ' ' + num + ' '; | |
} | |
function singleStep(ans, a, b, arr, i, target, sym) { | |
arr[i] = ans; | |
return (target = calc24(arr, target)) && | |
target.replace(wrap(ans), '(' + wrap(a) + sym + wrap(b) + ')'); | |
} | |
function reduction(a, b, arr, i, target) { | |
return singleStep(a + b, a, b, arr, i, target, '+') || | |
singleStep(a - b, a, b, arr, i, target, '-') || | |
singleStep(b - a, b, a, arr, i, target, '-') || | |
singleStep(a * b, a, b, arr, i, target, '*') || | |
singleStep(a / b, a, b, arr, i, target, '/') || | |
singleStep(b / a, b, a, arr, i, target, '/'); | |
} | |
function calc24(arr, target) { | |
if (arr.length == 1) { | |
if (arr[0] == target) | |
return wrap(arr[0]); | |
else | |
return null; | |
} | |
for (var i = 0; i < arr.length; i++) { | |
var clone = arr.slice(); | |
clone.splice(i, 1); | |
for (var j = i; j < clone.length; j++) { | |
var result = reduction(arr[i], arr[j + 1], clone, j, target); | |
clone[j] = arr[j+1]; | |
if (result) return result; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment