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.

Revisions

  1. littledian created this gist Nov 14, 2018.
    51 changes: 51 additions & 0 deletions calculate24.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    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)