Bulls and cows: Difference between revisions

m (Added Sidef)
Line 884:
 
=={{header|Elena}}==
<lang elena>#define std'dictionary'*system.
#define stdsystem'basic'*routines.
#define std'collections'*extensions.
#define std'patterns'*.
#define ext'utils'*.
#define std'routines'arrays'*.
 
#class EDigitProp
{
#method get
[
^ self numeric - 30h.
]
}
#symbol Digits : aLiteral
= Summing &&var:List &prop:EDigitProp start:Scan::aLiteral.
 
#class GameMaster
Line 905 ⟶ 892:
#field theNumbers.
 
#initializerconstructor new
[
// generate secret number
#var aRandomNumbers := RandomizedrandomControl randomize:9 &&basearray:(1,2,3,4,5,6,7,8,9) &count:9.
theNumbers := arrayControl copy:aRandomNumbers~earrayop read &from:0 &to:3 &length:esubarray4.
]
 
#method getask
[
#var aRow := consoleEx write:"Your Guess ?" readLine.
^ stringControl toArray:aRow.
theNumbers := aRandomNumbers~earrayop read &from:0 &to:3 &:esubarray.
]
 
#method proceed : aGuess
[
#ifvar (aGuessaCows count !:= 4)?Integer new:0.
[#var aBulls := Integer new:0.
'program'output << "Not a valid guess.%n".
^ $self.
].
 
#var(aGuess aCowsCount :!= Integer::0.4)
#var ? [ aBulls :=<< Integer::0-1. ]
! [
#if It control from:0 &to:aGuess3 run&do: aNumber =&&:i
[
// check range #var ch := aGuess@i.
Control if:( #var aNumber >:= 0)convertControl iftoInt:(aNumber <ch 10Literal).
// check duplicatesrange
#if (aNumber indexer'clone> index'append:10)~EIt findand:(aNumber < 10)
! [ #throw InvalidArgumentException new. ].
[
control fail.
// check duplicates
#var duplicate := arrayControl seek:aGuess &for: &&:x [ (x == ch)and:[ x equal &type'object:ch not ] ].
nil != duplicate ?
[
#throw InvalidArgumentException new.
].
].
#if Control if: (aNumber == (theNumbers@aNumber indexi))
? [ aBulls += 1. ]
! [
arrayControl ifExist:aNumber &in:theNumbers
? [ aCows += 1. ].
].
]
| ifFailed:
^ $self. [
#if ( aBulls ==<< 4)?-1.
^ self numeric - 30h ].
].
 
^ aBulls =>
#if Control if:(aNumber == theNumbers@aNumber index)
'program'output-1 <<? [ consoleEx writeLine:"Not a valid guess.%n". ^ true. ]
[
4 ? [ aBullsconsoleEx +=writeLine:"Congratulations! 1You have won!". ^ false. ]
] ! [
'program'output << consoleEx writeLine:"%nYourYour Score is " <<: aBulls <<: " bulls and " <<: aCows <<: " cows%n".
| if:(Scan::theNumbers == aNumber)
[
aCows +=^ 1true.
].
]
| [
'program'output << "Not a valid guess.%n".
^ $self.
].
#if (aBulls == 4)?
[
'program'output << "%nCongratulations! You have won!".
$self fail.
]
| [
'program'output << "%nYour Score is " << aBulls << " bulls and " << aCows << " cows%n".
].
]
}
 
#symbol Programprogram =
[
#var aGameMaster := GameMaster new.
 
#control while:[ aGameMaster proceed:Digits::(ext'io'consoleaGameMaster <<ask). "Your Guess ?" >> String)].
].</lang>
 
Anonymous user