Skip to content

Instantly share code, notes, and snippets.

@littledian
Created November 14, 2018 11:53
Show Gist options
  • Save littledian/2e6b1affbe9db1c40a025246a2818d4e to your computer and use it in GitHub Desktop.
Save littledian/2e6b1affbe9db1c40a025246a2818d4e to your computer and use it in GitHub Desktop.
function canCalculate24 (...args) {
const length = args.length
if (length === 2) {
const [ a, b ] = args
let result = (a + b === 24) || (a * b === 24) || (Math.abs(a - b) === 24) || (a > b ? a / b === 24 : b / a === 24)
return result
} else {
for (let i = 0; i < length; i++) {
for (let j = i + 1; j < length; j++) {
const sub = []
for (let p = 0; p < i; p++) {
sub.push(args[p])
}
for (let p = i + 1; p < j; p++) {
sub.push(args[p])
}
for (let p = j + 1; p < length; p++) {
sub.push(args[p])
}
const a = args[i]
const b = args[j]
let temp = a + b
if (canCalculate24(temp, ...sub)) return true
temp = Math.abs(a - b)
if (canCalculate24(temp, ...sub)) return true
temp = a * b
if (canCalculate24(temp, ...sub)) return true
temp = a / b
if (canCalculate24(temp, ...sub)) return true
temp = b / a
if (canCalculate24(temp, ...sub)) return true
}
}
return false
}
}
const result = []
for (let i = 1; i < 14; i++) {
for (let j = i; j < 14; j++) {
for (let p = j; p < 14; p++) {
for (let q = p; q < 14; q++) {
if (!canCalculate24(i, j, p, q)) {
result.push([i, j, p, q])
}
}
}
}
}
console.log(result.length)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment