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

Published on 12 May 2024 09:40 PM

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

Table of Contents

Problem Statement

Given a jumbled list of the numbers   1   to   9   that are definitely   not   in ascending order. Show the list,   and then ask the player how many digits from the left to reverse. Reverse those digits,   then ask again,   until all the digits end up in ascending order.

The score is the count of the reversals needed to attain the ascending order.

Note: Assume the player's input does not need extra validation.

Let's start with the solution:

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

Source code in the nim programming language

import random, rdstdin, strutils, algorithm
randomize()

proc isSorted[T](s: openarray[T]): bool =
  var last = low(T)
  for c in s:
    if c < last:
      return false
    last = c
  return true

proc toString[T](s: openarray[T]): string =
  result = ""
  for i, x in s:
    if i > 0:
      result.add " "
    result.add($x)

echo """number reversal game
    Given a jumbled list of the numbers 1 to 9
    Show the list.
    Ask the player how many digits from the left to reverse.
    Reverse those digits then ask again.
    until all the digits end up in ascending order."""

var data = @[1,2,3,4,5,6,7,8,9]
var trials = 0
while isSorted data:
  shuffle data
while not isSorted data:
  inc trials
  var flip = parseInt readLineFromStdin(
    "#" & $trials & ": List: '" & toString(data) & "' Flip how many?: ")
  reverse(data, 0, flip - 1)

echo "You took ", trials, " attempts to put the digits in order!"


  

You may also check:How to resolve the algorithm Amicable pairs step by step in the PL/M programming language
You may also check:How to resolve the algorithm Interactive programming (repl) step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Atomic updates step by step in the Tcl programming language
You may also check:How to resolve the algorithm The Twelve Days of Christmas step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Leonardo numbers step by step in the Ada programming language