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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm 24 game step by step in the CoffeeScript 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 CoffeeScript programming language

Source code in the coffeescript programming language

tty = require 'tty'
tty.setRawMode true

buffer  = ""
numbers = []

for n in [0...4]
    numbers.push Math.max 1, Math.floor(Math.random() * 9)
    
console.log "You can use the numbers: #{numbers.join ' '}"

process.stdin.on 'keypress', (char, key) ->

    # accept operator
    if char and isNaN(char) and /[()*\/+-]/.test(char) and buffer.substr(-1) isnt char
        buffer += char
        process.stdout.write char
    # accept number
    else if !isNaN(+char) and (buffer == '' or isNaN(buffer.substr -1))
        buffer += char
        process.stdout.write char
    
    # check then evaluate expression
    if key?.name is 'enter'
        result = calculate()
        process.stdout.write '\n'
        if result and result is 24
            console.log " = 24! congratulations."
        else
            console.log "#{result}. nope."
        process.exit 0
    
    # quit
    if key?.name is 'escape' or (key?.name == 'c' and key.ctrl)
        process.exit 0

calculate = () ->

    if /[^\d\s()+*\/-]/.test buffer
        console.log "invalid characters"
        process.exit 1
    
    used = buffer.match(/\d/g)
    if used?.length != 4 or used.sort().join() != numbers.sort().join()
        console.log "you must use the 4 numbers provided"
        process.exit 1
    
    res = try eval buffer catch e
    return res or 'invalid expression'

    
# begin taking input
process.stdin.resume()


  

You may also check:How to resolve the algorithm Naming conventions step by step in the C programming language
You may also check:How to resolve the algorithm Substring/Top and tail step by step in the Action! programming language
You may also check:How to resolve the algorithm Möbius function step by step in the REXX programming language
You may also check:How to resolve the algorithm Knapsack problem/0-1 step by step in the Visual Basic programming language
You may also check:How to resolve the algorithm Bell numbers step by step in the F# programming language