Skip to content

Instantly share code, notes, and snippets.

@looping84
Forked from bradoyler/24.md
Created February 24, 2017 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save looping84/eccd2d831600411f1ed9e3e4ca2c463d to your computer and use it in GitHub Desktop.
Save looping84/eccd2d831600411f1ed9e3e4ca2c463d to your computer and use it in GitHub Desktop.
The 24 game in javascript

The 24 Game

  • tests one's mental arithmetic.

How it works:

  • You are randomly given four digits, each from one to nine, with repetitions allowed.
  • The goal is to enter an expression that evaluates to 24
Tips:
  • Only multiplication, division, addition, and subtraction operators/functions are allowed.
  • Division should use floating point or rational arithmetic, etc, to preserve remainders.
  • Brackets are allowed, if using an infix expression evaluator.
  • Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).
  • The order of the digits when given does not have to be preserved.

The code:

  • you can copy this into your browser console.
function twentyfour(numbers, input) {
    var invalidChars = /[^\d\+\*\/\s-\(\)]/;
 
    var validNums = function(str) {
        // Create a duplicate of our input numbers, so that
        // both lists will be sorted.
        var mnums = numbers.slice();
        mnums.sort();
 
        // Sort after mapping to numbers, to make comparisons valid.
        return str.replace(/[^\d\s]/g, " ")
            .trim()
            .split(/\s+/)
            .map(function(n) { return parseInt(n, 10); })
            .sort()
            .every(function(v, i) { return v === mnums[i]; });
    };
 
    var validEval = function(input) {
        try {
            return eval(input);
        } catch (e) {
            return {error: e.toString()};
        }
    };
 
    if (input.trim() === "") return "You must enter a value.";
    if (input.match(invalidChars)) return "Invalid chars used, try again. Use only:\n + - * / ( )";
    if (!validNums(input)) return "Wrong numbers used, try again.";
    var calc = validEval(input);
    if (typeof calc !== 'number') return "That is not a valid input; please try again.";
    if (calc !== 24) return "Wrong answer: " + String(calc) + "; please try again.";
    return input + " == 24.  Congratulations!";
};
 
// I/O below.
 
while (true) {
    var numbers = [1, 2, 3, 4].map(function() {
        return Math.floor(Math.random() * 8 + 1);
    });
 
    var input = prompt(
        "Your numbers are:\n" + numbers.join(" ") +
        "\nEnter expression. (use only + - * / and parens).\n", +"'x' to exit.", "");
 
    if (input === 'x') {
        break;
    }
    alert(twentyfour(numbers, input));
}

source: http://rosettacode.org/wiki/24_game

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