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

Published on 12 May 2024 09:40 PM

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

Source code in the wren programming language

import "random" for Random
import "./ioutil" for Input
import "./seq" for Stack

var R = Random.new()

class Game24 {
    static run() {
        var digits = List.filled(4, 0)
        for (i in 0..3) digits[i] = R.int(1, 10)
        System.print("Make 24 using these digits: %(digits)")
        var cin = Input.text("> ")
        var s = Stack.new()
        var total = 0
        for (c in cin) {
            var d = c.bytes[0]
            if (d >= 48 && d <= 57) {
                d = d - 48
                total = total + (1 << (d*5))
                s.push(d)
            } else if ("+-*/".indexOf(c) != -1) s.push(applyOperator_(s.pop(), s.pop(), c))
        }
        if (tallyDigits_(digits) != total) {
            System.write("Not the same digits.")
        } else if ((24 - s.peek()).abs < 0.001) {
            System.print("Correct!")
        } else {
            System.write("Not correct.")
        }
    }

    static applyOperator_(a, b, c) {
        if (c == "+") return a + b
        if (c == "-") return b - a
        if (c == "*") return a * b
        if (c == "/") return b / a
        return 0/0
    }

    static tallyDigits_(a) {
        var total = 0
        for (i in 0...a.count) total = total + (1 << (a[i]*5))
        return total
    }
}

Game24.run()


  

You may also check:How to resolve the algorithm Knapsack problem/Continuous step by step in the Go programming language
You may also check:How to resolve the algorithm Loops/Nested step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Associative array/Creation step by step in the SQL PL programming language
You may also check:How to resolve the algorithm Draw a cuboid step by step in the Delphi programming language
You may also check:How to resolve the algorithm Poker hand analyser step by step in the Wren programming language