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

Published on 12 May 2024 09:40 PM
#Jq

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

Table of Contents

Problem Statement

Nim is a simple game where the second player─if they know the trick─will always win.

The game has only 3 rules:

To win every time,   the second player simply takes 4 minus the number the first player took.   So if the first player takes 1,   the second takes 3; if the first player takes 2,   the second should take 2; and if the first player takes 3,   the second player will take 1. Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Nim game step by step in the jq programming language

Source code in the jq programming language

def play($tokens):
  label $out
  | "There are \($tokens) tokens.  Take at most \([$tokens,3]|min) or enter q to quit.",
     ( foreach inputs as $in ( {$tokens};
         if $in == "q" then break $out
         else .in = $in
         | if $in | test("^[0-9]+$") then .in |= tonumber else .in = null end
         | if .in and .in > 0 and .in < 4
           then  (4 - .in) as $ct
           | (if $ct == 1 then "" else "s" end) as $s
           | .emit = "  Computer takes \($ct) token\($s);"
           | .tokens += -4
           else .emit = "Please enter a number from 1 to \([3, .tokens]|min) inclusive."
           end
	 end;
	   
     .emit,
	 if .tokens == 0
     then "\nComputer wins!", break $out
     elif .tokens < 0 then "\nCongratulations!", break $out
	 else "\(.tokens) tokens remain. How many tokens will you take?"
     end )) ;

play(12)

  

You may also check:How to resolve the algorithm Logical operations step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm Bifid cipher step by step in the Lua programming language
You may also check:How to resolve the algorithm Zig-zag matrix step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Rep-string step by step in the BQN programming language
You may also check:How to resolve the algorithm Random number generator (device) step by step in the EchoLisp programming language