How to resolve the algorithm Number reversal game step by step in the V (Vlang) programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Number reversal game step by step in the V (Vlang) 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 V (Vlang) programming language

Source code in the v programming language

import rand
import os

fn main() {
	mut score, mut rnum := 0, 0
	mut mix, mut unmix := []int{}, []int{}
	for mix.len < 9 {
		rnum = rand.int_in_range(1, 10) or {println('Error: invalid number') exit(1)}
		if mix.contains(rnum) == false {
			mix << rnum
		}
	}
	unmix = mix.clone()
	unmix.sort()
	println("Select how many digits from the left to reverse.")
	for {
		print("The list is: ${mix} ==> How many digits to reverse? ")
		input := os.input('').str().trim_space().int()
		score++
		if input == 0 || input < 2 || input > 9 {
			println("\n(Enter a number from 2 to 9)")
			continue
		}
		for idx, rdx := 0, input - 1; idx < rdx; idx, rdx = idx + 1, rdx - 1 {
			mix[idx], mix[rdx] = mix[rdx], mix[idx]
		}
		if mix == unmix {
			println("The list is: ${mix}.")
			println("Your score: ${score}.  Good job.")
			break
		}
	}
}

  

You may also check:How to resolve the algorithm Sort an integer array step by step in the AWK programming language
You may also check:How to resolve the algorithm FASTA format step by step in the M2000 Interpreter programming language
You may also check:How to resolve the algorithm Terminal control/Preserve screen step by step in the Go programming language
You may also check:How to resolve the algorithm Discordian date step by step in the D programming language
You may also check:How to resolve the algorithm 2048 step by step in the Raku programming language