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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Bulls and cows step by step in the PureBasic 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 PureBasic programming language

Source code in the purebasic programming language

Define.s secret, guess, c
Define.i bulls, cows, guesses, i

If OpenConsole()

  While Len(secret) < 4
    c = Chr(Random(8) + 49)
    If FindString(secret, c, 1) = 0
      secret + c
    EndIf 
  Wend

  Repeat
    Print("Guess a 4-digit number with no duplicate digits: ")
    guess = Input()
    If Len(guess) = 0 
      Break   ;break from loop
    EndIf 
  
    isMalformedGuess = #False
    If Len(guess) <> 4
      ;guess is too short
      isMalformedGuess = #True 
    Else
      For i = 1 To 4
        c = Mid(guess, i, 1)
        If Not FindString("123456789", c, 1) Or CountString(guess, c) <> 1
          ;guess contains either non-digits or duplicate digits
          isMalformedGuess = #True
          Break ;break from For/Next loop
        EndIf 
      Next
    EndIf
  
    If isMalformedGuess
      PrintN("** You should enter 4 different numeric digits that are each from 1 to 9!")
      Continue ;continue loop
    EndIf 
    
    bulls = 0: cows = 0: guesses = guesses + 1
    For i = 1 To 4
      c = Mid(secret, i, 1)
      If Mid(guess, i, 1) = c
        bulls + 1
      ElseIf FindString(guess, c, 1)
        cows + 1
      EndIf 
    Next
  
    Print( Str(bulls) + " bull")
    If bulls <> 1
      Print( "s")
    EndIf 
    Print( ", " + Str(cows) + " cow")
    If cows <> 1
      PrintN( "s")
    Else
      PrintN("")
    EndIf
  
    If guess = secret
      PrintN("You won after " + Str(guesses) + " guesses!")
      Break    ;break from loop
    EndIf
  ForEver

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf

  

You may also check:How to resolve the algorithm Topological sort step by step in the zkl programming language
You may also check:How to resolve the algorithm String case step by step in the Powerbuilder programming language
You may also check:How to resolve the algorithm Loops/Break step by step in the Amazing Hopper programming language
You may also check:How to resolve the algorithm String prepend step by step in the Asymptote programming language
You may also check:How to resolve the algorithm Compare a list of strings step by step in the Klong programming language