How to resolve the algorithm 24 game step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm 24 game step by step in the JavaScript programming language

Table of Contents

Problem Statement

The 24 Game tests one's mental arithmetic.

Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 24 game step by step in the JavaScript programming language

This JavaScript code implements a game where the user is given four numbers and has to input an expression using those numbers and the operators +, -, *, /, and parentheses to evaluate to 24. The code initializes four random numbers between 1 and 8 and asks the user to input an expression. It checks if the input is valid (contains only numbers, operators, and parentheses) and evaluates the expression using the eval() function. If the evaluation is not a number or does not equal 24, the code returns an error message. If the evaluation equals 24, the code returns a congratulatory message. The game continues until the user enters 'x' to exit.

Here is a breakdown of the code:

  • The twentyfour function takes two parameters: numbers and input. numbers is an array of four random numbers, and input is the expression entered by the user.
  • The invalidChars variable is a regular expression that matches any character that is not a digit, +, -, *, /, a space, or a parenthesis.
  • The validNums function checks if the input contains the same numbers as the given numbers array. It sorts both the input numbers and the given numbers and compares them element by element. If they are not the same, the function returns false.
  • The validEval function evaluates the input using the eval() function and returns the result. If the evaluation results in an error, the function returns an error object.
  • The code first checks if the input is empty. If it is, it returns an error message.
  • Then, it checks if the input contains any invalid characters. If it does, it returns an error message.
  • Next, it checks if the input contains the same numbers as the given numbers array. If it does not, it returns an error message.
  • Then, it evaluates the input using the validEval function. If the evaluation results in an error, it returns an error message.
  • Finally, it checks if the evaluation equals 24. If it does, it returns a congratulatory message. Otherwise, it returns an error message.
  • The code then runs a loop that continues until the user enters 'x' to exit. In each iteration of the loop, it generates four random numbers and asks the user to input an expression. It then checks if the input is valid and evaluates it. If the evaluation is valid and equals 24, it displays a congratulatory message. Otherwise, it displays an error message.

Source code in the javascript programming language

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));
}


  

You may also check:How to resolve the algorithm Conway's Game of Life step by step in the ooRexx programming language
You may also check:How to resolve the algorithm Empty string step by step in the zkl programming language
You may also check:How to resolve the algorithm Farey sequence step by step in the C# programming language
You may also check:How to resolve the algorithm Align columns step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Combinations step by step in the Action! programming language