How to resolve the algorithm Bulls and cows step by step in the Seed7 programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Bulls and cows step by step in the Seed7 programming language

Table of Contents

Problem Statement

Bulls and Cows   is an old game played with pencil and paper that was later implemented using computers.

Create a four digit random number from the digits   1   to   9,   without duplication. The program should:

The score is computed as:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Bulls and cows step by step in the Seed7 programming language

Source code in the seed7 programming language

$ include "seed7_05.s7i";

const proc: main is func
  local
    const integer: size is 4;
    var set of char: digits is {'1' .. '9'};
    var string: chosen is " " mult size;
    var integer: guesses is 0;
    var string: guess is "";
    var integer: pos is 0;
    var integer: bulls is 0;
    var integer: cows is 0;
    var boolean: okay is FALSE;
  begin
    for pos range 1 to 4 do
      chosen @:= [pos] rand(digits);
      excl(digits, chosen[pos]);
    end for;
    writeln("I have chosen a number from " <& size <& " unique digits from 1 to 9 arranged in a random order.");
    writeln("You need to input a " <& size <& " digit, unique digit number as a guess at what I have chosen");
    repeat
      incr(guesses);
      repeat
        write("Next guess [" <& guesses <& "]: ");
        readln(guess);
        okay := length(guess) = size;
        for key pos range guess do
          okay := okay and guess[pos] in {'1' .. '9'} and pos(guess[succ(pos) ..], guess[pos]) = 0;
        end for;
        if not okay then
          writeln("Problem, try again. You need to enter " <& size <& " unique digits from 1 to 9");
        end if;
      until okay;
      if guess <> chosen then
        bulls := 0;
        cows := 0;
        for key pos range chosen do
          if guess[pos] = chosen[pos] then
            incr(bulls);
          elsif pos(chosen, guess[pos]) <> 0 then
            incr(cows);
          end if;
        end for;
        writeln("  " <& bulls <& " Bulls");
        writeln("  " <& cows <& " Cows");
      end if;
    until guess = chosen;
    writeln("Congratulations you guessed correctly in " <& guesses <& " attempts");
  end func;

  

You may also check:How to resolve the algorithm XML/Input step by step in the ARM Assembly programming language
You may also check:How to resolve the algorithm Bin given limits step by step in the Lua programming language
You may also check:How to resolve the algorithm Increment a numerical string step by step in the EGL programming language
You may also check:How to resolve the algorithm Reverse a string step by step in the 0815 programming language
You may also check:How to resolve the algorithm URL decoding step by step in the Scala programming language