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

Published on 12 May 2024 09:40 PM

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

Source code in the nim programming language

from random import randomize, rand
from strutils import Whitespace
from algorithm import sort
from sequtils import newSeqWith

randomize()
 
var
  problem = newSeqWith(4, rand(1..9))
  stack: seq[float]
  digits: seq[int]
 
echo "Make 24 with the digits: ", problem
 
template op(c: untyped) =
  let a = stack.pop
  stack.add c(stack.pop, a)
 
for c in stdin.readLine:
  case c
  of '1'..'9':
    digits.add c.ord - '0'.ord
    stack.add float(c.ord - '0'.ord)
  of '+': op `+`
  of '*': op `*`
  of '-': op `-`
  of '/': op `/`
  of Whitespace: discard
  else: raise newException(ValueError, "Wrong char: " & c)
 
sort digits
sort problem
if digits != problem:
  raise newException(ValueError, "Not using the given digits.")
if stack.len != 1:
  raise newException(ValueError, "Wrong expression.")
echo "Result: ", stack[0]
echo if abs(stack[0] - 24) < 0.001: "Good job!" else: "Try again."


  

You may also check:How to resolve the algorithm Matrix digital rain step by step in the Racket programming language
You may also check:How to resolve the algorithm MD5 step by step in the NewLISP programming language
You may also check:How to resolve the algorithm Knapsack problem/0-1 step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Find the intersection of two lines step by step in the Common Lisp programming language
You may also check:How to resolve the algorithm Water collected between towers step by step in the Cowgol programming language