How to resolve the algorithm Bulls and cows step by step in the Smalltalk programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Bulls and cows step by step in the Smalltalk 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 Smalltalk programming language
Source code in the smalltalk programming language
Object subclass: BullsCows [
|number|
BullsCows class >> new: secretNum [ |i|
i := self basicNew.
(self isValid: secretNum)
ifFalse: [ SystemExceptions.InvalidArgument
signalOn: secretNum
reason: 'You need 4 unique digits from 1 to 9' ].
i setNumber: secretNum.
^ i
]
BullsCows class >> new [ |b| b := Set new.
[ b size < 4 ]
whileTrue: [ b add: ((Random between: 1 and: 9) displayString first) ].
^ self new: (b asString)
]
BullsCows class >> isValid: num [
^ (num asSet size = 4) & ((num asSet includes: $0) not)
]
setNumber: num [ number := num ]
check: guess [ |bc| bc := Bag new.
1 to: 4 do: [ :i |
(number at: i) = (guess at: i)
ifTrue: [ bc add: 'bulls' ]
ifFalse: [
(number includes: (guess at: i))
ifTrue: [ bc add: 'cows' ]
]
].
^ bc
]
].
'Guess the 4-digits number (digits from 1 to 9, no repetition)' displayNl.
|guessMe d r tries|
[
tries := 0.
guessMe := BullsCows new.
[
[
'Write 4 digits: ' display.
d := stdin nextLine.
(BullsCows isValid: d)
] whileFalse: [
'Insert 4 digits, no repetition, exclude the digit 0' displayNl
].
r := guessMe check: d.
tries := tries + 1.
(r occurrencesOf: 'bulls') = 4
] whileFalse: [
('%1 cows, %2 bulls' % { r occurrencesOf: 'cows'. r occurrencesOf: 'bulls' })
displayNl.
].
('Good, you guessed it in %1 tries!' % { tries }) displayNl.
'Do you want to play again? [y/n]' display.
( (stdin nextLine) = 'y' )
] whileTrue: [ Character nl displayNl ].
You may also check:How to resolve the algorithm Damm algorithm step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Variable-length quantity step by step in the J programming language
You may also check:How to resolve the algorithm Binary search step by step in the K programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Ring programming language
You may also check:How to resolve the algorithm Factors of a Mersenne number step by step in the Python programming language