Data update
This commit is contained in:
parent
5150844a7d
commit
4bb20c9b71
7735 changed files with 38060 additions and 199180 deletions
|
|
@ -1,174 +1,174 @@
|
|||
bdos equ 5
|
||||
putchar equ 2
|
||||
rawio equ 6
|
||||
puts equ 9
|
||||
cstat equ 11
|
||||
reads equ 10
|
||||
bdos equ 5
|
||||
putchar equ 2
|
||||
rawio equ 6
|
||||
puts equ 9
|
||||
cstat equ 11
|
||||
reads equ 10
|
||||
|
||||
org 100h
|
||||
mvi c,puts
|
||||
lxi d,signon ; Print name
|
||||
call bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Initialize the RNG with keyboard input
|
||||
mvi c,puts
|
||||
lxi d,entropy ; Ask for randomness
|
||||
call bdos
|
||||
mvi b,9 ; 9 times,
|
||||
randloop: mvi c,3 ; read 3 keys.
|
||||
lxi h,xabcdat + 1
|
||||
randkey: push b ; Read a key
|
||||
push h
|
||||
randkeywait: mvi c,rawio
|
||||
mvi e,0FFh
|
||||
call bdos
|
||||
ana a
|
||||
jz randkeywait
|
||||
pop h
|
||||
pop b
|
||||
xra m ; XOR it with the random memory
|
||||
mov m,a
|
||||
inx h
|
||||
dcr c
|
||||
jnz randkey ; Go get more characters
|
||||
dcr b
|
||||
jnz randloop
|
||||
mvi c,puts
|
||||
lxi d,done ; Tell the user we're done
|
||||
call bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Generate 4-digit secret code
|
||||
lxi h,secret
|
||||
mvi b,4
|
||||
gencode: push h
|
||||
push b
|
||||
call randcode
|
||||
pop b
|
||||
pop h
|
||||
mov m,a
|
||||
inx h
|
||||
dcr b
|
||||
jnz gencode
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; User makes a guess
|
||||
readguess: mvi c,puts ; Ask for guess
|
||||
lxi d,guess
|
||||
call bdos
|
||||
mvi c,reads ; Read guess
|
||||
lxi d,bufdef
|
||||
call bdos
|
||||
call newline ; Print newline
|
||||
mvi b,4 ; Check input
|
||||
lxi h,buf
|
||||
validate: mov a,m
|
||||
cpi '9' + 1 ; >9?
|
||||
jnc inval ; = invalid
|
||||
cpi '1' ; <1?
|
||||
jc inval ; = invalid
|
||||
sui '0' ; Make ASCII digit into number
|
||||
mov m,a
|
||||
inx h
|
||||
dcr b
|
||||
jnz validate
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Count bulls
|
||||
mvi c,puts
|
||||
lxi d,bulls ; Output "Bulls:"
|
||||
call bdos
|
||||
lxi d,secret
|
||||
lxi h,buf
|
||||
lxi b,4 ; No bulls, counter = 4
|
||||
bullloop: ldax d ; Get secret digit
|
||||
cmp m ; Match to buffer digit
|
||||
cz countmatch
|
||||
inx h
|
||||
inx d
|
||||
dcr c
|
||||
jnz bullloop
|
||||
push b ; Keep bulls for cow count,
|
||||
push b ; and for final check.
|
||||
call printcount
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Count cows
|
||||
mvi c,puts
|
||||
lxi d,cows ; Output ", Cows:"
|
||||
call bdos
|
||||
pop psw ; Retrieve the bulls (into A reg)
|
||||
cma ; Negate amount of bulls
|
||||
inr a
|
||||
mov b,a ; Use it as start of cow count
|
||||
mvi d,4 ; For all 4 secret digits..
|
||||
lxi h,secret
|
||||
cowouter: mov a,m ; Grab secret digit to test
|
||||
push h ; Store secret position
|
||||
mvi e,4 ; For all 4 input digits...
|
||||
lxi h,buf
|
||||
cowinner: cmp m ; Compare to current secret digit
|
||||
cz countmatch
|
||||
inx h
|
||||
dcr e ; While there are more digits in buf
|
||||
jnz cowinner ; Test next digit
|
||||
pop h ; Restore secret position
|
||||
inx h ; Look at next secret digit
|
||||
dcr d ; While there are digits left
|
||||
jnz cowouter
|
||||
push b ; Keep cow count
|
||||
call printcount
|
||||
call newline
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Check win condition
|
||||
pop psw ; Cow count (in A)
|
||||
pop b ; Bull count (in B)
|
||||
ana a ; To win, there must be 0 cows...
|
||||
jnz readguess
|
||||
mvi a,4 ; And 4 bulls.
|
||||
cmp b
|
||||
jnz readguess
|
||||
mvi c,puts
|
||||
lxi d,win
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Increment bull/cow counter
|
||||
countmatch: inr b
|
||||
ret
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Print a newline
|
||||
newline: mvi c,puts
|
||||
lxi d,nl
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Output counter as ASCII
|
||||
printcount: mvi a,'0'
|
||||
add b
|
||||
mvi c,putchar
|
||||
mov e,a
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; User entered invalid input
|
||||
inval: mvi c,puts
|
||||
lxi d,invalid
|
||||
call bdos
|
||||
jmp readguess
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Generate random number 1-9 that isn't in key
|
||||
randcode: call xabcrand
|
||||
ani 0fh ; Low nybble
|
||||
ana a ; 0 = invalid
|
||||
jz randcode
|
||||
cpi 10 ; >9 = invalid
|
||||
jnc randcode
|
||||
;; Check if it is a duplicate
|
||||
mvi b,4
|
||||
lxi h,secret
|
||||
checkdup: cmp m
|
||||
jz randcode
|
||||
inx h
|
||||
dcr b
|
||||
jnz checkdup
|
||||
ret
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; The "X ABC" 8-bit random number generator
|
||||
;; (Google that to find where it came from)
|
||||
org 100h
|
||||
mvi c,puts
|
||||
lxi d,signon ; Print name
|
||||
call bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Initialize the RNG with keyboard input
|
||||
mvi c,puts
|
||||
lxi d,entropy ; Ask for randomness
|
||||
call bdos
|
||||
mvi b,9 ; 9 times,
|
||||
randloop: mvi c,3 ; read 3 keys.
|
||||
lxi h,xabcdat + 1
|
||||
randkey: push b ; Read a key
|
||||
push h
|
||||
randkeywait: mvi c,rawio
|
||||
mvi e,0FFh
|
||||
call bdos
|
||||
ana a
|
||||
jz randkeywait
|
||||
pop h
|
||||
pop b
|
||||
xra m ; XOR it with the random memory
|
||||
mov m,a
|
||||
inx h
|
||||
dcr c
|
||||
jnz randkey ; Go get more characters
|
||||
dcr b
|
||||
jnz randloop
|
||||
mvi c,puts
|
||||
lxi d,done ; Tell the user we're done
|
||||
call bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Generate 4-digit secret code
|
||||
lxi h,secret
|
||||
mvi b,4
|
||||
gencode: push h
|
||||
push b
|
||||
call randcode
|
||||
pop b
|
||||
pop h
|
||||
mov m,a
|
||||
inx h
|
||||
dcr b
|
||||
jnz gencode
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; User makes a guess
|
||||
readguess: mvi c,puts ; Ask for guess
|
||||
lxi d,guess
|
||||
call bdos
|
||||
mvi c,reads ; Read guess
|
||||
lxi d,bufdef
|
||||
call bdos
|
||||
call newline ; Print newline
|
||||
mvi b,4 ; Check input
|
||||
lxi h,buf
|
||||
validate: mov a,m
|
||||
cpi '9' + 1 ; >9?
|
||||
jnc inval ; = invalid
|
||||
cpi '1' ; <1?
|
||||
jc inval ; = invalid
|
||||
sui '0' ; Make ASCII digit into number
|
||||
mov m,a
|
||||
inx h
|
||||
dcr b
|
||||
jnz validate
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Count bulls
|
||||
mvi c,puts
|
||||
lxi d,bulls ; Output "Bulls:"
|
||||
call bdos
|
||||
lxi d,secret
|
||||
lxi h,buf
|
||||
lxi b,4 ; No bulls, counter = 4
|
||||
bullloop: ldax d ; Get secret digit
|
||||
cmp m ; Match to buffer digit
|
||||
cz countmatch
|
||||
inx h
|
||||
inx d
|
||||
dcr c
|
||||
jnz bullloop
|
||||
push b ; Keep bulls for cow count,
|
||||
push b ; and for final check.
|
||||
call printcount
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Count cows
|
||||
mvi c,puts
|
||||
lxi d,cows ; Output ", Cows:"
|
||||
call bdos
|
||||
pop psw ; Retrieve the bulls (into A reg)
|
||||
cma ; Negate amount of bulls
|
||||
inr a
|
||||
mov b,a ; Use it as start of cow count
|
||||
mvi d,4 ; For all 4 secret digits..
|
||||
lxi h,secret
|
||||
cowouter: mov a,m ; Grab secret digit to test
|
||||
push h ; Store secret position
|
||||
mvi e,4 ; For all 4 input digits...
|
||||
lxi h,buf
|
||||
cowinner: cmp m ; Compare to current secret digit
|
||||
cz countmatch
|
||||
inx h
|
||||
dcr e ; While there are more digits in buf
|
||||
jnz cowinner ; Test next digit
|
||||
pop h ; Restore secret position
|
||||
inx h ; Look at next secret digit
|
||||
dcr d ; While there are digits left
|
||||
jnz cowouter
|
||||
push b ; Keep cow count
|
||||
call printcount
|
||||
call newline
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Check win condition
|
||||
pop psw ; Cow count (in A)
|
||||
pop b ; Bull count (in B)
|
||||
ana a ; To win, there must be 0 cows...
|
||||
jnz readguess
|
||||
mvi a,4 ; And 4 bulls.
|
||||
cmp b
|
||||
jnz readguess
|
||||
mvi c,puts
|
||||
lxi d,win
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Increment bull/cow counter
|
||||
countmatch: inr b
|
||||
ret
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Print a newline
|
||||
newline: mvi c,puts
|
||||
lxi d,nl
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Output counter as ASCII
|
||||
printcount: mvi a,'0'
|
||||
add b
|
||||
mvi c,putchar
|
||||
mov e,a
|
||||
jmp bdos
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; User entered invalid input
|
||||
inval: mvi c,puts
|
||||
lxi d,invalid
|
||||
call bdos
|
||||
jmp readguess
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Generate random number 1-9 that isn't in key
|
||||
randcode: call xabcrand
|
||||
ani 0fh ; Low nybble
|
||||
ana a ; 0 = invalid
|
||||
jz randcode
|
||||
cpi 10 ; >9 = invalid
|
||||
jnc randcode
|
||||
;; Check if it is a duplicate
|
||||
mvi b,4
|
||||
lxi h,secret
|
||||
checkdup: cmp m
|
||||
jz randcode
|
||||
inx h
|
||||
dcr b
|
||||
jnz checkdup
|
||||
ret
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; The "X ABC" 8-bit random number generator
|
||||
;; (Google that to find where it came from)
|
||||
xabcrand: lxi h,xabcdat
|
||||
inr m ; X++
|
||||
mov a,m ; X,
|
||||
|
|
@ -187,20 +187,20 @@ xabcrand: lxi h,xabcdat
|
|||
add m ; + C
|
||||
mov m,a ; -> C
|
||||
ret
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Strings
|
||||
signon: db 'Bulls and Cows',13,10,'$'
|
||||
entropy: db 'Please mash the keyboard to generate entropy...$'
|
||||
done: db 'done.',13,10,13,10,'$'
|
||||
bulls: db 'Bulls: $'
|
||||
cows: db ', Cows: $'
|
||||
guess: db 'Guess: $'
|
||||
invalid: db 'Invalid input.',13,10,'$'
|
||||
win: db 'You win!',13,10,'$'
|
||||
nl: db 13,10,'$'
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Variables
|
||||
xabcdat: ds 4 ; RNG state
|
||||
secret: ds 4 ; Holds the secret code
|
||||
bufdef: db 4,0 ; User input buffer
|
||||
buf: ds 4
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Strings
|
||||
signon: db 'Bulls and Cows',13,10,'$'
|
||||
entropy: db 'Please mash the keyboard to generate entropy...$'
|
||||
done: db 'done.',13,10,13,10,'$'
|
||||
bulls: db 'Bulls: $'
|
||||
cows: db ', Cows: $'
|
||||
guess: db 'Guess: $'
|
||||
invalid: db 'Invalid input.',13,10,'$'
|
||||
win: db 'You win!',13,10,'$'
|
||||
nl: db 13,10,'$'
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Variables
|
||||
xabcdat: ds 4 ; RNG state
|
||||
secret: ds 4 ; Holds the secret code
|
||||
bufdef: db 4,0 ; User input buffer
|
||||
buf: ds 4
|
||||
|
|
|
|||
|
|
@ -1,10 +1,4 @@
|
|||
input ← {⍞←'Guess: ' ⋄ 7↓⍞}
|
||||
output ← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
|
||||
isdigits← ∧/⎕D∊⍨⊢
|
||||
valid ← isdigits∧4=≢
|
||||
guess ← ⍎¨input⍣(valid⊣)
|
||||
bulls ← +/=
|
||||
cows ← +/∊∧≠
|
||||
game ← (output ⊣(bulls,cows) guess)⍣(4 0≡⊣)
|
||||
random ← 1+4?9
|
||||
moo ← 'You win!'⊣(random game⊢)
|
||||
output← {⎕←(↑'Bulls: ' 'Cows: '),⍕⍪⍵ ⋄ ⍵}
|
||||
guess ← ⍎¨{⍞←'Guess: ' ⋄ 7↓⍞}⍣((∧/⍤∊∘⎕D ∧ 4=≢)⊣)
|
||||
game ← (output ⊣ (+/⍤= , ∊+/⍤∧≠) guess)⍣(4 0≡⊣)
|
||||
moo ← 'You win!'⊣(1+4?9⍨)game⊢
|
||||
|
|
|
|||
|
|
@ -1,53 +0,0 @@
|
|||
with Ada.Text_IO; use Ada.Text_IO;
|
||||
with Ada.Numerics.Discrete_Random;
|
||||
|
||||
procedure Bulls_And_Cows is
|
||||
package Random_Natural is new Ada.Numerics.Discrete_Random (Natural);
|
||||
Number : String (1..4);
|
||||
begin
|
||||
declare -- Generation of number
|
||||
use Random_Natural;
|
||||
Digit : String := "123456789";
|
||||
Size : Positive := 9;
|
||||
Dice : Generator;
|
||||
Position : Natural;
|
||||
begin
|
||||
Reset (Dice);
|
||||
for I in Number'Range loop
|
||||
Position := Random (Dice) mod Size + 1;
|
||||
Number (I) := Digit (Position);
|
||||
Digit (Position..Size - 1) := Digit (Position + 1..Size);
|
||||
Size := Size - 1;
|
||||
end loop;
|
||||
end;
|
||||
loop -- Guessing loop
|
||||
Put ("Enter four digits:");
|
||||
declare
|
||||
Guess : String := Get_Line;
|
||||
Bulls : Natural := 0;
|
||||
Cows : Natural := 0;
|
||||
begin
|
||||
if Guess'Length /= 4 then
|
||||
raise Data_Error;
|
||||
end if;
|
||||
for I in Guess'Range loop
|
||||
for J in Number'Range loop
|
||||
if Guess (I) not in '1'..'9' or else (I < J and then Guess (I) = Guess (J)) then
|
||||
raise Data_Error;
|
||||
end if;
|
||||
if Number (I) = Guess (J) then
|
||||
if I = J then
|
||||
Bulls := Bulls + 1;
|
||||
else
|
||||
Cows := Cows + 1;
|
||||
end if;
|
||||
end if;
|
||||
end loop;
|
||||
end loop;
|
||||
exit when Bulls = 4;
|
||||
Put_Line (Integer'Image (Bulls) & " bulls," & Integer'Image (Cows) & " cows");
|
||||
exception
|
||||
when Data_Error => Put_Line ("You should enter four different digits 1..9");
|
||||
end;
|
||||
end loop;
|
||||
end Bulls_And_Cows;
|
||||
|
|
@ -1,58 +1,58 @@
|
|||
on pickNumber()
|
||||
set theNumber to ""
|
||||
repeat 4 times
|
||||
set theDigit to (random number from 1 to 9) as string
|
||||
repeat while (offset of theDigit in theNumber) > 0
|
||||
set theDigit to (random number from 1 to 9) as string
|
||||
end repeat
|
||||
set theNumber to theNumber & theDigit
|
||||
end repeat
|
||||
set theNumber to ""
|
||||
repeat 4 times
|
||||
set theDigit to (random number from 1 to 9) as string
|
||||
repeat while (offset of theDigit in theNumber) > 0
|
||||
set theDigit to (random number from 1 to 9) as string
|
||||
end repeat
|
||||
set theNumber to theNumber & theDigit
|
||||
end repeat
|
||||
end pickNumber
|
||||
|
||||
to bulls of theGuess given key:theKey
|
||||
set bullCount to 0
|
||||
repeat with theIndex from 1 to 4
|
||||
if text theIndex of theGuess = text theIndex of theKey then
|
||||
set bullCount to bullCount + 1
|
||||
end if
|
||||
end repeat
|
||||
return bullCount
|
||||
set bullCount to 0
|
||||
repeat with theIndex from 1 to 4
|
||||
if text theIndex of theGuess = text theIndex of theKey then
|
||||
set bullCount to bullCount + 1
|
||||
end if
|
||||
end repeat
|
||||
return bullCount
|
||||
end bulls
|
||||
|
||||
to cows of theGuess given key:theKey, bulls:bullCount
|
||||
set cowCount to -bullCount
|
||||
repeat with theIndex from 1 to 4
|
||||
if (offset of (text theIndex of theKey) in theGuess) > 0 then
|
||||
set cowCount to cowCount + 1
|
||||
end if
|
||||
end repeat
|
||||
|
||||
return cowCount
|
||||
set cowCount to -bullCount
|
||||
repeat with theIndex from 1 to 4
|
||||
if (offset of (text theIndex of theKey) in theGuess) > 0 then
|
||||
set cowCount to cowCount + 1
|
||||
end if
|
||||
end repeat
|
||||
|
||||
return cowCount
|
||||
end cows
|
||||
|
||||
to score of theGuess given key:theKey
|
||||
set bullCount to bulls of theGuess given key:theKey
|
||||
set cowCount to cows of theGuess given key:theKey, bulls:bullCount
|
||||
return {bulls:bullCount, cows:cowCount}
|
||||
set bullCount to bulls of theGuess given key:theKey
|
||||
set cowCount to cows of theGuess given key:theKey, bulls:bullCount
|
||||
return {bulls:bullCount, cows:cowCount}
|
||||
end score
|
||||
|
||||
on run
|
||||
set theNumber to pickNumber()
|
||||
set pastGuesses to {}
|
||||
repeat
|
||||
set theMessage to ""
|
||||
repeat with aGuess in pastGuesses
|
||||
set {theGuess, theResult} to aGuess
|
||||
set theMessage to theMessage & theGuess & ":" & bulls of theResult & "B, " & cows of theResult & "C" & linefeed
|
||||
end repeat
|
||||
set theMessage to theMessage & linefeed & "Enter guess:"
|
||||
set theGuess to text returned of (display dialog theMessage with title "Bulls and Cows" default answer "")
|
||||
set theScore to score of theGuess given key:theNumber
|
||||
if bulls of theScore is 4 then
|
||||
display dialog "Correct! Found the secret in " & ((length of pastGuesses) + 1) & " guesses!"
|
||||
exit repeat
|
||||
else
|
||||
set end of pastGuesses to {theGuess, theScore}
|
||||
end if
|
||||
end repeat
|
||||
set theNumber to pickNumber()
|
||||
set pastGuesses to {}
|
||||
repeat
|
||||
set theMessage to ""
|
||||
repeat with aGuess in pastGuesses
|
||||
set {theGuess, theResult} to aGuess
|
||||
set theMessage to theMessage & theGuess & ":" & bulls of theResult & "B, " & cows of theResult & "C" & linefeed
|
||||
end repeat
|
||||
set theMessage to theMessage & linefeed & "Enter guess:"
|
||||
set theGuess to text returned of (display dialog theMessage with title "Bulls and Cows" default answer "")
|
||||
set theScore to score of theGuess given key:theNumber
|
||||
if bulls of theScore is 4 then
|
||||
display dialog "Correct! Found the secret in " & ((length of pastGuesses) + 1) & " guesses!"
|
||||
exit repeat
|
||||
else
|
||||
set end of pastGuesses to {theGuess, theScore}
|
||||
end if
|
||||
end repeat
|
||||
end run
|
||||
|
|
|
|||
|
|
@ -2,16 +2,16 @@ rand: first.n: 4 unique map 1..10 => [sample 0..9]
|
|||
bulls: 0
|
||||
|
||||
while [bulls <> 4][
|
||||
bulls: new 0
|
||||
cows: new 0
|
||||
bulls: 0
|
||||
cows: 0
|
||||
|
||||
got: strip input "make a guess: "
|
||||
if? or? not? numeric? got
|
||||
switch or? not? numeric? got
|
||||
4 <> size got -> print "Malformed answer. Try again!"
|
||||
else [
|
||||
[
|
||||
loop.with:'i split got 'digit [
|
||||
if? (to :integer digit) = rand\[i] -> inc 'bulls
|
||||
else [
|
||||
switch (to :integer digit) = rand\[i] -> inc 'bulls
|
||||
[
|
||||
if contains? rand to :integer digit -> inc 'cows
|
||||
]
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
length:=4, Code:="" ; settings
|
||||
|
||||
While StrLen(Code) < length {
|
||||
Random, num, 1, 9
|
||||
If !InStr(Code, num)
|
||||
Code .= num
|
||||
Random, num, 1, 9
|
||||
If !InStr(Code, num)
|
||||
Code .= num
|
||||
}
|
||||
Gui, Add, Text, w83 vInfo, I'm thinking of a %length%-digit number with no duplicate digits.
|
||||
Gui, Add, Edit, wp vGuess, Enter a guess...
|
||||
|
|
@ -13,40 +13,40 @@ Gui, Show
|
|||
Return
|
||||
|
||||
ButtonSubmit:
|
||||
If Default = Restart
|
||||
Reload
|
||||
Gui, Submit, NoHide
|
||||
If (StrLen(Guess) != length)
|
||||
GuiControl, , Info, Enter a %length%-digit number.
|
||||
Else If Guess is not digit
|
||||
GuiControl, , Info, Enter a %length%-digit number.
|
||||
Else
|
||||
{
|
||||
GuiControl, , Info
|
||||
GuiControl, , Guess
|
||||
If (Guess = Code)
|
||||
{
|
||||
GuiControl, , Info, Correct!
|
||||
GuiControl, , Default, Restart
|
||||
Default = Restart
|
||||
}
|
||||
response := Response(Guess, Code)
|
||||
Bulls := SubStr(response, 1, InStr(response,",")-1)
|
||||
Cows := SubStr(response, InStr(response,",")+1)
|
||||
GuiControl, , History, % History . Guess ": " Bulls " Bulls " Cows " Cows`n"
|
||||
}
|
||||
If Default = Restart
|
||||
Reload
|
||||
Gui, Submit, NoHide
|
||||
If (StrLen(Guess) != length)
|
||||
GuiControl, , Info, Enter a %length%-digit number.
|
||||
Else If Guess is not digit
|
||||
GuiControl, , Info, Enter a %length%-digit number.
|
||||
Else
|
||||
{
|
||||
GuiControl, , Info
|
||||
GuiControl, , Guess
|
||||
If (Guess = Code)
|
||||
{
|
||||
GuiControl, , Info, Correct!
|
||||
GuiControl, , Default, Restart
|
||||
Default = Restart
|
||||
}
|
||||
response := Response(Guess, Code)
|
||||
Bulls := SubStr(response, 1, InStr(response,",")-1)
|
||||
Cows := SubStr(response, InStr(response,",")+1)
|
||||
GuiControl, , History, % History . Guess ": " Bulls " Bulls " Cows " Cows`n"
|
||||
}
|
||||
Return
|
||||
|
||||
GuiEscape:
|
||||
GuiClose:
|
||||
ExitApp
|
||||
ExitApp
|
||||
|
||||
Response(Guess,Code) {
|
||||
Bulls := 0, Cows := 0
|
||||
Loop, % StrLen(Code)
|
||||
If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1))
|
||||
Bulls++
|
||||
Else If (InStr(Code, SubStr(Guess, A_Index, 1)))
|
||||
Cows++
|
||||
Return Bulls "," Cows
|
||||
Bulls := 0, Cows := 0
|
||||
Loop, % StrLen(Code)
|
||||
If (SubStr(Guess, A_Index, 1) = SubStr(Code, A_Index, 1))
|
||||
Bulls++
|
||||
Else If (InStr(Code, SubStr(Guess, A_Index, 1)))
|
||||
Cows++
|
||||
Return Bulls "," Cows
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ int main()
|
|||
mvaddstrf(20, 0, "You guessed %s correctly in %d attempts!", number, tries);
|
||||
else
|
||||
mvaddstrf(20,0, "Sorry, you had only %d tries...; the number was %s",
|
||||
MAX_NUM_TRIES, number);
|
||||
MAX_NUM_TRIES, number);
|
||||
again = ask_play_again();
|
||||
tries = 0;
|
||||
} while(again);
|
||||
|
|
|
|||
|
|
@ -1,112 +1,112 @@
|
|||
class
|
||||
BULLS_AND_COWS
|
||||
BULLS_AND_COWS
|
||||
|
||||
create
|
||||
execute
|
||||
execute
|
||||
|
||||
feature
|
||||
|
||||
execute
|
||||
-- Initiate game.
|
||||
do
|
||||
io.put_string ("Let's play bulls and cows.%N")
|
||||
create answer.make_empty
|
||||
play
|
||||
end
|
||||
execute
|
||||
-- Initiate game.
|
||||
do
|
||||
io.put_string ("Let's play bulls and cows.%N")
|
||||
create answer.make_empty
|
||||
play
|
||||
end
|
||||
|
||||
feature {NONE}
|
||||
|
||||
play
|
||||
-- Plays bulls ans cows.
|
||||
local
|
||||
count, seed: INTEGER
|
||||
guess: STRING
|
||||
do
|
||||
from
|
||||
until
|
||||
seed > 0
|
||||
loop
|
||||
io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N")
|
||||
io.read_integer
|
||||
seed := io.last_integer
|
||||
end
|
||||
generate_answer (seed)
|
||||
io.put_string ("Your game has been created.%N Try to guess the four digit number.%N")
|
||||
create guess.make_empty
|
||||
from
|
||||
until
|
||||
guess ~ answer
|
||||
loop
|
||||
io.put_string ("Guess: ")
|
||||
io.read_line
|
||||
guess := io.last_string
|
||||
if guess.count = 4 and guess.is_natural and not guess.has ('0') then
|
||||
io.put_string (score (guess) + "%N")
|
||||
count := count + 1
|
||||
else
|
||||
io.put_string ("Your input does not have the correct format.")
|
||||
end
|
||||
end
|
||||
io.put_string ("Congratulations! You won with " + count.out + " guesses.")
|
||||
end
|
||||
play
|
||||
-- Plays bulls ans cows.
|
||||
local
|
||||
count, seed: INTEGER
|
||||
guess: STRING
|
||||
do
|
||||
from
|
||||
until
|
||||
seed > 0
|
||||
loop
|
||||
io.put_string ("Enter a positive integer.%NYour play will be generated from it.%N")
|
||||
io.read_integer
|
||||
seed := io.last_integer
|
||||
end
|
||||
generate_answer (seed)
|
||||
io.put_string ("Your game has been created.%N Try to guess the four digit number.%N")
|
||||
create guess.make_empty
|
||||
from
|
||||
until
|
||||
guess ~ answer
|
||||
loop
|
||||
io.put_string ("Guess: ")
|
||||
io.read_line
|
||||
guess := io.last_string
|
||||
if guess.count = 4 and guess.is_natural and not guess.has ('0') then
|
||||
io.put_string (score (guess) + "%N")
|
||||
count := count + 1
|
||||
else
|
||||
io.put_string ("Your input does not have the correct format.")
|
||||
end
|
||||
end
|
||||
io.put_string ("Congratulations! You won with " + count.out + " guesses.")
|
||||
end
|
||||
|
||||
answer: STRING
|
||||
answer: STRING
|
||||
|
||||
generate_answer (s: INTEGER)
|
||||
-- Answer with 4-digits between 1 and 9 stored in 'answer'.
|
||||
require
|
||||
positive_seed: s > 0
|
||||
local
|
||||
random: RANDOM
|
||||
ran: INTEGER
|
||||
do
|
||||
create random.set_seed (s)
|
||||
from
|
||||
until
|
||||
answer.count = 4
|
||||
loop
|
||||
ran := (random.double_item * 10).floor
|
||||
if ran > 0 and not answer.has_substring (ran.out) then
|
||||
answer.append (ran.out)
|
||||
end
|
||||
random.forth
|
||||
end
|
||||
ensure
|
||||
answer_not_void: answer /= Void
|
||||
correct_length: answer.count = 4
|
||||
end
|
||||
generate_answer (s: INTEGER)
|
||||
-- Answer with 4-digits between 1 and 9 stored in 'answer'.
|
||||
require
|
||||
positive_seed: s > 0
|
||||
local
|
||||
random: RANDOM
|
||||
ran: INTEGER
|
||||
do
|
||||
create random.set_seed (s)
|
||||
from
|
||||
until
|
||||
answer.count = 4
|
||||
loop
|
||||
ran := (random.double_item * 10).floor
|
||||
if ran > 0 and not answer.has_substring (ran.out) then
|
||||
answer.append (ran.out)
|
||||
end
|
||||
random.forth
|
||||
end
|
||||
ensure
|
||||
answer_not_void: answer /= Void
|
||||
correct_length: answer.count = 4
|
||||
end
|
||||
|
||||
score (g: STRING): STRING
|
||||
-- Score for the guess 'g' depending on 'answer'.
|
||||
require
|
||||
same_length: answer.count = g.count
|
||||
local
|
||||
k: INTEGER
|
||||
a, ge: STRING
|
||||
do
|
||||
Result := ""
|
||||
a := answer.twin
|
||||
ge := g.twin
|
||||
across
|
||||
1 |..| a.count as c
|
||||
loop
|
||||
if a [c.item] ~ ge [c.item] then
|
||||
Result := Result + "BULL "
|
||||
a [c.item] := ' '
|
||||
ge [c.item] := ' '
|
||||
end
|
||||
end
|
||||
across
|
||||
1 |..| a.count as c
|
||||
loop
|
||||
if a [c.item] /= ' ' then
|
||||
k := ge.index_of (a [c.item], 1)
|
||||
if k > 0 then
|
||||
Result := Result + "COW "
|
||||
ge [k] := ' '
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
score (g: STRING): STRING
|
||||
-- Score for the guess 'g' depending on 'answer'.
|
||||
require
|
||||
same_length: answer.count = g.count
|
||||
local
|
||||
k: INTEGER
|
||||
a, ge: STRING
|
||||
do
|
||||
Result := ""
|
||||
a := answer.twin
|
||||
ge := g.twin
|
||||
across
|
||||
1 |..| a.count as c
|
||||
loop
|
||||
if a [c.item] ~ ge [c.item] then
|
||||
Result := Result + "BULL "
|
||||
a [c.item] := ' '
|
||||
ge [c.item] := ' '
|
||||
end
|
||||
end
|
||||
across
|
||||
1 |..| a.count as c
|
||||
loop
|
||||
if a [c.item] /= ' ' then
|
||||
k := ge.index_of (a [c.item], 1)
|
||||
if k > 0 then
|
||||
Result := Result + "COW "
|
||||
ge [k] := ' '
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
|
|
|
|||
|
|
@ -80,7 +80,7 @@ class GameMaster
|
|||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
public Program()
|
||||
{
|
||||
var gameMaster := new GameMaster();
|
||||
|
||||
|
|
|
|||
|
|
@ -1,132 +0,0 @@
|
|||
(defun get-list-4-random-digits ()
|
||||
"Generate a list of 4 random non-repeating digits."
|
||||
(let ((list-of-digits '(0 1 2 3 4 5 6 7 8 9))
|
||||
(one-digit)
|
||||
(four-digits))
|
||||
(dotimes (n 4)
|
||||
(setq one-digit (seq-random-elt list-of-digits))
|
||||
(push one-digit four-digits)
|
||||
(setq list-of-digits (delq one-digit (copy-sequence list-of-digits))))
|
||||
four-digits))
|
||||
|
||||
(defun list-digits (guess-string)
|
||||
"List individual digits of GUESS-STRING."
|
||||
(let ((list-of-digits)
|
||||
(one-digit)
|
||||
(total-digits (length guess-string)))
|
||||
(dotimes (n total-digits)
|
||||
(setq one-digit (string-to-number (substring guess-string n (1+ n))))
|
||||
(push one-digit list-of-digits))
|
||||
(reverse list-of-digits)))
|
||||
|
||||
(defun number-list-to-string (numbers)
|
||||
(mapconcat #'number-to-string numbers))
|
||||
|
||||
(defun four-non-repeating-digits-p (guess-string)
|
||||
"Test if GUESS-STRING has 4 one-digit numbers that do not repeat."
|
||||
;; if GUESS-STRING contains non-numeric characters, then
|
||||
;; the non-numeric characters will be converted to 0s
|
||||
(let ((number-list (list-digits guess-string)))
|
||||
|
||||
(and
|
||||
;; GUESS-STRING must consist of exactly 4 digits
|
||||
(string-match-p "^[[:digit:]]\\{4\\}$" guess-string)
|
||||
|
||||
;; the length of the list must still be 4 after
|
||||
;; removing duplicate characters, and
|
||||
(= (length (seq-uniq number-list)) 4))))
|
||||
|
||||
(defun count-bulls (guess answer)
|
||||
"Count number of bulls in GUESS as compared to ANSWER.
|
||||
In this game, a bull is an exact match. Both GUESS and
|
||||
ANSWER are lists of numbers."
|
||||
(let ((bulls 0)
|
||||
(position-in-list -1))
|
||||
(dolist (guess-number guess)
|
||||
(setq position-in-list (1+ position-in-list))
|
||||
(when (= guess-number (nth position-in-list answer))
|
||||
(setq bulls (1+ bulls))))
|
||||
bulls))
|
||||
|
||||
(defun is-cow-p (number-list position answer)
|
||||
"Test if NUMBER-LIST is in ANSWER but not in same POSITION."
|
||||
(and
|
||||
;; NUMBER-LIST is found in ANSWER
|
||||
(seq-position answer number-list)
|
||||
;; NUMBER-LIST is not in same POSITION in ANSWER
|
||||
(not (equal number-list (nth position answer)))))
|
||||
|
||||
(defun count-cows (guess answer)
|
||||
"Count number of cows in GUESS as compared to ANSWER.
|
||||
In this game, a cow is a match, but only in a different position.
|
||||
Both GUESS and ANSWER are lists of numbers."
|
||||
(let ((cows 0)
|
||||
(zero-based-position 0))
|
||||
(dotimes (n 4)
|
||||
(when (is-cow-p (nth zero-based-position guess) zero-based-position answer)
|
||||
(setq cows (1+ cows)))
|
||||
(setq zero-based-position (1+ zero-based-position)))
|
||||
cows))
|
||||
|
||||
(defun count-bulls-and-cows (guess answer count)
|
||||
"Give game feedback for GUESS as compared to ANSWER."
|
||||
(let ((cows (count-cows guess answer))
|
||||
(bulls (count-bulls guess answer)))
|
||||
(goto-char (point-max))
|
||||
(insert (format "\n%3s - %s Bulls = %s Cows = %s" count (number-list-to-string guess) bulls cows))
|
||||
(when (= bulls 4)
|
||||
(insert " You win!")
|
||||
t)))
|
||||
|
||||
(defun get-player-guess ()
|
||||
"Get player guess."
|
||||
(let ((player-guess))
|
||||
(setq player-guess (read-string "Enter a 4 digit number or Q to quit: "))
|
||||
player-guess))
|
||||
|
||||
(defun play-bulls-and-cows ()
|
||||
"Play bulls and cows game."
|
||||
(interactive)
|
||||
(let ((answer (get-list-4-random-digits))
|
||||
(player-guess-string)
|
||||
(player-guess-list-of-numbers)
|
||||
(count 0))
|
||||
(with-current-buffer (pop-to-buffer "bulls and cows game")
|
||||
(erase-buffer)
|
||||
(insert (propertize
|
||||
(concat
|
||||
"Rules: Enter a 4 digit number whose digits do not repeat."
|
||||
"\n For example, 2468 is 4 digit number with non-repeating digits."
|
||||
"\n Digits that match both the number and position will be scored as bulls."
|
||||
"\n Digits that match the number but *not* the position will be scored as cows.") 'face 'shadow))
|
||||
|
||||
;; (insert "Rules: Enter a 4 digit number whose digits do not repeat.")
|
||||
;; (insert "\n For example, 2468 is 4 digit number with non-repeating digits.")
|
||||
;; (insert "\n Digits that match both the number and position will be scored as bulls.")
|
||||
;; (insert "\n Digits that match the number but *not* the position will be scored as cows.")
|
||||
(insert (propertize
|
||||
(concat
|
||||
"\n"
|
||||
"\nTurn Your guess Result"
|
||||
"\n---- ---------- ------")
|
||||
'face 'bold))
|
||||
(catch 'end-game
|
||||
(while t
|
||||
(progn
|
||||
;; get input
|
||||
(setq player-guess-string (get-player-guess))
|
||||
(setq player-guess-list-of-numbers (list-digits player-guess-string))
|
||||
;; evaluate input
|
||||
(cond
|
||||
((string-equal-ignore-case player-guess-string "Q")
|
||||
(insert "\nGame ended because Q was entered")
|
||||
(throw 'end-game t))
|
||||
((four-non-repeating-digits-p player-guess-string)
|
||||
;; increase count of turns played by 1
|
||||
(setq count (1+ count))
|
||||
;; count-bulls-and-cows returns nil if 4 bulls
|
||||
(and (count-bulls-and-cows player-guess-list-of-numbers answer count)
|
||||
(throw 'end-game t)))
|
||||
(t
|
||||
(goto-char (point-max))
|
||||
(insert (propertize (format "\nThe guess entered was %S\nYou must enter a number with 4 non-repeating digits or Q to quit." player-guess-string) 'face 'error))))))))))
|
||||
|
|
@ -1,103 +0,0 @@
|
|||
include std\text.e
|
||||
include std\os.e
|
||||
include std\sequence.e
|
||||
include std\console.e
|
||||
|
||||
sequence bcData = {0,0} --bull,cow score for the player
|
||||
sequence goalNum = { {0,0,0,0}, {0,0,0,0}, 0} --computer's secret number digits (element 1), marked as bull/cow
|
||||
--indexes in element 2, integer value of it in element 3
|
||||
sequence currentGuess = { {0,0,0,0}, {0,0,0,0}, 0} --player's guess, same format as goalNum
|
||||
sequence removeChars = 0 & " 0\r\t\n" --characters to trim (remove) from user's input. \r, \t are single escaped characters,
|
||||
--0 is ascii 0x0 and number zero is ascii 48, or 0x30. The rest are wysiwyg
|
||||
integer tries = 0 --track number of tries to guess the number
|
||||
sequence bcStrings ={"bull", "cow"} --stores singular and/or plural strings depending on score in bcData
|
||||
|
||||
goalNum[1] = rand( {9,9,9,9} ) --rand function works on objects. here it outputs into each sequence element.
|
||||
goalNum[3] = goalNum[1][1] * 1000 + goalNum[1][2] * 100 + goalNum[1][3] * 10 + goalNum[1][4] --convert digits to an integer
|
||||
--and store it
|
||||
|
||||
procedure getInputAndProcess(integer stage = 1) --object = 1 sets default value for the parameter if it isn't specified
|
||||
|
||||
goalNum[2][1..4] = 0 --{0,0,0,0} --set these to unscaned (0) since the scanning will start over.
|
||||
currentGuess[1][1..4] = 0 --{0,0,0,0} --these too, or they will contain old marks
|
||||
currentGuess[2][1..4] = 0
|
||||
tries += 1 --equivalent to tries = tries + 1, but faster and shorter to write
|
||||
bcData[1..2] = 0 -- {0,0}
|
||||
|
||||
if stage <= 1 then --if this process was run for the first time or with no parameters, then..
|
||||
puts(1,"The program has thought of a four digit number using only digits 1 to 9.\nType your guess and press enter.\n")
|
||||
end if
|
||||
|
||||
while 1 label "guesscheck" do --labels can be used to specify a jump point from exit or retry, and help readability
|
||||
currentGuess[1] = trim(gets(0), removeChars) --get user input, trim unwanted characters from it, store it in currentGuess[1]
|
||||
currentGuess[1] = mapping( currentGuess[1], {49,50,51,52,53,54,55,56,57}, {1,2,3,4,5,6,7,8,9} ) --convert ascii codes to
|
||||
-- integer digits they represent
|
||||
integer tempF = find('0',currentGuess[1])
|
||||
if length(currentGuess[1]) != 4 or tempF != 0 then --if the input string is now more than 4 characters/integers,
|
||||
--the input won't be used.
|
||||
puts(1,"You probably typed too many digits or a 0. Try typing a new 4 digit number with only numbers 1 through 9.\n")
|
||||
retry "guesscheck"
|
||||
else
|
||||
exit "guesscheck"
|
||||
end if
|
||||
end while
|
||||
--convert separate digits to the one integer they represent and store it, like with goalNum[3]
|
||||
currentGuess[3] = currentGuess[1][1] * 1000 + currentGuess[1][2] * 100 + currentGuess[1][3] * 10 + currentGuess[1][4]
|
||||
--convert digits to the integer they represent, to print to a string later
|
||||
|
||||
--check for bulls
|
||||
for i = 1 to 4 do
|
||||
if goalNum[1][i] = currentGuess[1][i] then
|
||||
goalNum[2][i] = 1
|
||||
currentGuess[2][i] = 1
|
||||
bcData[1] += 1
|
||||
end if
|
||||
end for
|
||||
|
||||
--check for cows, but not slots marked as bulls or cows already.
|
||||
for i = 1 to 4 label "iGuessElem"do --loop through each guessed digit
|
||||
for j = 1 to 4 label "jGoalElem" do --but first go through each goal digit, comparing the first guessed digit,
|
||||
--and then the other guessed digits 2 through 4
|
||||
|
||||
if currentGuess[2][i] = 1 then --if the guessed digit we're comparing right now has been marked as bull or cow already
|
||||
continue "iGuessElem" --skip to the next guess digit without comparing this guess digit to the other goal digits
|
||||
end if
|
||||
|
||||
if goalNum[2][j] = 1 then --if the goal digit we're comparing to right now has been marked as a bull or cow already
|
||||
continue "jGoalElem" --skip to the next goal digit
|
||||
end if
|
||||
|
||||
if currentGuess[1][i] = goalNum[1][j] then --if the guessed digit is the same as the goal one,
|
||||
--it won't be a bull, so it's a cow
|
||||
bcData[2] += 1 --score one more cow
|
||||
goalNum[2][j] = 1 --mark this digit as a found cow in the subsequence that stores 0's or 1's as flags
|
||||
continue "iGuessElem" --skip to the next guess digit, so that this digit won't try to check for
|
||||
--matches(cow) with other goal digits
|
||||
end if
|
||||
|
||||
end for --this guess digit was compared to one goal digit , try comparing this guess digit with the next goal digit
|
||||
end for --this guess digit was compared with all goal digits, compare the next guess digit to all the goal digits
|
||||
|
||||
if bcData[1] = 1 then --uses singular noun when there is score of 1, else plural
|
||||
bcStrings[1] = "bull"
|
||||
else
|
||||
bcStrings[1] = "bulls"
|
||||
end if
|
||||
|
||||
if bcData[2] = 1 then --the same kind of thing as above block
|
||||
bcStrings[2] = "cow"
|
||||
else
|
||||
bcStrings[2] = "cows"
|
||||
end if
|
||||
|
||||
if bcData[1] < 4 then --if less than 4 bulls were found, the player hasn't won, else they have...
|
||||
printf(1, "Guess #%d : You guessed %d . You found %d %s, %d %s. Type new guess.\n", {tries, currentGuess[3], bcData[1], bcStrings[1], bcData[2], bcStrings[2]} )
|
||||
getInputAndProcess(2)
|
||||
else --else they have won and the procedure ends
|
||||
printf(1, "The number was %d. You guessed %d in %d tries.\n", {goalNum[3], currentGuess[3], tries} )
|
||||
any_key()--wait for keypress before closing console window.
|
||||
end if
|
||||
|
||||
end procedure
|
||||
--run the procedure
|
||||
getInputAndProcess(1)
|
||||
|
|
@ -1,12 +1,11 @@
|
|||
USING: io kernel math math.parser random ranges sequences sets ; IN: bullsncows
|
||||
9 [1..b] 4 sample [ 48 + ] "" map-as
|
||||
[ "guess the 4-digit number: " write flush readln dup
|
||||
[ length 4 = ] [ [ 48 57 [a..b] in? ] all? ] bi and ! [48,57] is the ascii range for 0-9
|
||||
[ 2dup =
|
||||
[ 2drop "yep!" print flush f ]
|
||||
[ "bulls & cows: " write
|
||||
[ 0 [ = 1 0 ? + ] 2reduce ] [ intersect length ] 2bi over -
|
||||
[ number>string ] bi@ " & " glue print flush t ]
|
||||
if ]
|
||||
[ 2drop "bad input" print t ]
|
||||
if ] curry loop
|
||||
USING: io kernel math math.parser math.vectors random ranges sequences sets ; IN: bullsncows
|
||||
: fp ( str -- ) print flush ; inline : fw ( str -- ) write flush ; inline
|
||||
: bac ( -- )
|
||||
CHAR: 0 CHAR: 9 [a..b] dup 4 sample
|
||||
'[ "guess the 4-digit number: " fw readln { } like
|
||||
dup [ length 4 = ] keep [ _ in? ] all? and
|
||||
[ _ [ v= vcount ] 2keep intersect length over - over 4 =
|
||||
[ 2drop "correct!" fp f ]
|
||||
[ "bulls & cows: " fw [ >dec ] bi@ " & " glue fp t ] if
|
||||
] [ drop "bad input" fp t ] if
|
||||
] loop ; MAIN: bac
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
output=. ['Bulls: '&,:@'Cows: 'echo@,.":@,.
|
||||
valid =. *./@e.&Num_j_*.4=#
|
||||
guess =. 0 ".&> $:^:(-.@valid)@(1!:1@1)@echo@'Guess:'{{x u y}}
|
||||
game =. [ $:^:(4 0-.@-:]) [ (+/@:= output@, e. +/@:*. ~:) guess
|
||||
guess =. 0".&>1!:1@1@echo@'Guess:'^:(*./@e.&Num_j_*:4=#)^:_.@]
|
||||
game =. ([:output [ (= ,&(+/) e.*.~:) guess)^:(4 0-.@-:])^:_.
|
||||
moo =. 'You win!'[ (1+4?9:) game ]
|
||||
|
|
|
|||
|
|
@ -1,11 +1,4 @@
|
|||
U =. {{u^:(-.@:v)^:_.}} NB. apply u until v is true
|
||||
input =. 1!:1@1@echo@'Guess: '
|
||||
output =. [ ('Bulls: ',:'Cows: ')echo@,.":@,.
|
||||
isdigits=. *./@e.&Num_j_
|
||||
valid =. isdigits*.4=#
|
||||
guess =. 0".&>input U(valid@])
|
||||
bulls =. +/@:=
|
||||
cows =. [:+/e.*.~:
|
||||
game =. ([:output [(bulls,cows) guess)U(4 0-:])
|
||||
random =. 1+4?9:
|
||||
moo =. 'You win!'[ random game ]
|
||||
output=. ['Bulls: '&,:@'Cows: 'echo@,.":@,.
|
||||
guess =. $:^:(*./@e.&Num_j_*:4=#)@(1!:1@1)@echo@'Guess:'
|
||||
game =. [ $:^:(4 0-.@-:]) [:output [ (= ,&(+/) e.*.~:) 0".&>guess
|
||||
moo =. 'You win!'[ (1+4?9:) game ]
|
||||
|
|
|
|||
|
|
@ -1,24 +1 @@
|
|||
require 'misc'
|
||||
|
||||
plural=: conjunction define
|
||||
(":m),' ',n,'s'#~1~:m
|
||||
)
|
||||
|
||||
bullcow=:monad define
|
||||
number=. 1+4?9
|
||||
whilst. -.guess-:number do.
|
||||
guess=. 0 "."0 prompt 'Guess my number: '
|
||||
if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do.
|
||||
if. 0=#guess do.
|
||||
smoutput 'Giving up.'
|
||||
return.
|
||||
end.
|
||||
smoutput 'Guesses must be four different non-zero digits'
|
||||
continue.
|
||||
end.
|
||||
bulls=. +/guess=number
|
||||
cows=. (+/guess e.number)-bulls
|
||||
smoutput bulls plural 'bull',' and ',cows plural 'cow','.'
|
||||
end.
|
||||
smoutput 'you win'
|
||||
)
|
||||
guess =. 0 ".&> $:^:(*./@e.&Num_j_*:4=#)@(1!:1@1)@echo@'Guess:'{{x u y}}
|
||||
|
|
|
|||
|
|
@ -1,16 +1,24 @@
|
|||
bullcow''
|
||||
Guess my number: 1234
|
||||
0 bulls and 1 cow.
|
||||
Guess my number: 5678
|
||||
3 bulls and 0 cows.
|
||||
Guess my number: 2349
|
||||
0 bulls and 0 cows.
|
||||
Guess my number: 1567
|
||||
0 bulls and 3 cows.
|
||||
Guess my number: 6178
|
||||
3 bulls and 0 cows.
|
||||
Guess my number: 6157
|
||||
1 bull and 2 cows.
|
||||
Guess my number: 5178
|
||||
4 bulls and 0 cows.
|
||||
you win
|
||||
require 'misc'
|
||||
|
||||
plural=: conjunction define
|
||||
(":m),' ',n,'s'#~1~:m
|
||||
)
|
||||
|
||||
bullcow=:monad define
|
||||
number=. 1+4?9
|
||||
whilst. -.guess-:number do.
|
||||
guess=. 0 "."0 prompt 'Guess my number: '
|
||||
if. (4~:#guess)+.(4~:#~.guess)+.0 e.guess e.1+i.9 do.
|
||||
if. 0=#guess do.
|
||||
echo 'Giving up.'
|
||||
return.
|
||||
end.
|
||||
echo 'Guesses must be four different non-zero digits'
|
||||
continue.
|
||||
end.
|
||||
bulls=. +/guess=number
|
||||
cows=. (+/guess e.number)-bulls
|
||||
echo bulls plural 'bull',' and ',cows plural 'cow','.'
|
||||
end.
|
||||
echo 'you win'
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,50 +3,50 @@ import java.util.Random;
|
|||
import java.util.Scanner;
|
||||
|
||||
public class BullsAndCows{
|
||||
public static void main(String[] args){
|
||||
Random gen= new Random();
|
||||
int target;
|
||||
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
|
||||
String targetStr = target +"";
|
||||
boolean guessed = false;
|
||||
Scanner input = new Scanner(System.in);
|
||||
int guesses = 0;
|
||||
do{
|
||||
int bulls = 0;
|
||||
int cows = 0;
|
||||
System.out.print("Guess a 4-digit number with no duplicate digits: ");
|
||||
int guess;
|
||||
try{
|
||||
guess = input.nextInt();
|
||||
if(hasDupes(guess) || guess < 1000) continue;
|
||||
}catch(InputMismatchException e){
|
||||
continue;
|
||||
}
|
||||
guesses++;
|
||||
String guessStr = guess + "";
|
||||
for(int i= 0;i < 4;i++){
|
||||
if(guessStr.charAt(i) == targetStr.charAt(i)){
|
||||
bulls++;
|
||||
}else if(targetStr.contains(guessStr.charAt(i)+"")){
|
||||
cows++;
|
||||
}
|
||||
}
|
||||
if(bulls == 4){
|
||||
guessed = true;
|
||||
}else{
|
||||
System.out.println(cows+" Cows and "+bulls+" Bulls.");
|
||||
}
|
||||
}while(!guessed);
|
||||
System.out.println("You won after "+guesses+" guesses!");
|
||||
}
|
||||
public static void main(String[] args){
|
||||
Random gen= new Random();
|
||||
int target;
|
||||
while(hasDupes(target= (gen.nextInt(9000) + 1000)));
|
||||
String targetStr = target +"";
|
||||
boolean guessed = false;
|
||||
Scanner input = new Scanner(System.in);
|
||||
int guesses = 0;
|
||||
do{
|
||||
int bulls = 0;
|
||||
int cows = 0;
|
||||
System.out.print("Guess a 4-digit number with no duplicate digits: ");
|
||||
int guess;
|
||||
try{
|
||||
guess = input.nextInt();
|
||||
if(hasDupes(guess) || guess < 1000) continue;
|
||||
}catch(InputMismatchException e){
|
||||
continue;
|
||||
}
|
||||
guesses++;
|
||||
String guessStr = guess + "";
|
||||
for(int i= 0;i < 4;i++){
|
||||
if(guessStr.charAt(i) == targetStr.charAt(i)){
|
||||
bulls++;
|
||||
}else if(targetStr.contains(guessStr.charAt(i)+"")){
|
||||
cows++;
|
||||
}
|
||||
}
|
||||
if(bulls == 4){
|
||||
guessed = true;
|
||||
}else{
|
||||
System.out.println(cows+" Cows and "+bulls+" Bulls.");
|
||||
}
|
||||
}while(!guessed);
|
||||
System.out.println("You won after "+guesses+" guesses!");
|
||||
}
|
||||
|
||||
public static boolean hasDupes(int num){
|
||||
boolean[] digs = new boolean[10];
|
||||
while(num > 0){
|
||||
if(digs[num%10]) return true;
|
||||
digs[num%10] = true;
|
||||
num/= 10;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public static boolean hasDupes(int num){
|
||||
boolean[] digs = new boolean[10];
|
||||
while(num > 0){
|
||||
if(digs[num%10]) return true;
|
||||
digs[num%10] = true;
|
||||
num/= 10;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,32 +1,32 @@
|
|||
function cowsbulls()
|
||||
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
|
||||
You get one bull for every right number in the right position.\n
|
||||
You get one cow for every right number, but in the wrong position.\n
|
||||
Enter 'n' to pick a new number and 'q' to quit.\n>")
|
||||
function new_number()
|
||||
s = [1:9]
|
||||
n = ""
|
||||
for i = 9:-1:6
|
||||
n *= string(delete!(s,rand(1:i)))
|
||||
end
|
||||
return n
|
||||
end
|
||||
answer = new_number()
|
||||
while true
|
||||
input = chomp(readline(STDIN))
|
||||
input == "q" && break
|
||||
if input == "n"
|
||||
answer = new_number()
|
||||
print("\nI've picked a new number, go ahead and guess\n>")
|
||||
continue
|
||||
end
|
||||
!ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue)
|
||||
if input == answer
|
||||
print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>")
|
||||
else
|
||||
bulls = sum(answer.data .== input.data)
|
||||
cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])
|
||||
print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>")
|
||||
end
|
||||
end
|
||||
print("Welcome to Cows & Bulls! I've picked a number with unique digits between 1 and 9, go ahead and type your guess.\n
|
||||
You get one bull for every right number in the right position.\n
|
||||
You get one cow for every right number, but in the wrong position.\n
|
||||
Enter 'n' to pick a new number and 'q' to quit.\n>")
|
||||
function new_number()
|
||||
s = [1:9]
|
||||
n = ""
|
||||
for i = 9:-1:6
|
||||
n *= string(delete!(s,rand(1:i)))
|
||||
end
|
||||
return n
|
||||
end
|
||||
answer = new_number()
|
||||
while true
|
||||
input = chomp(readline(STDIN))
|
||||
input == "q" && break
|
||||
if input == "n"
|
||||
answer = new_number()
|
||||
print("\nI've picked a new number, go ahead and guess\n>")
|
||||
continue
|
||||
end
|
||||
!ismatch(r"^[1-9]{4}$",input) && (print("Invalid guess: Please enter a 4-digit number\n>"); continue)
|
||||
if input == answer
|
||||
print("\nYou're right! Good guessing!\nEnter 'n' for a new number or 'q' to quit\n>")
|
||||
else
|
||||
bulls = sum(answer.data .== input.data)
|
||||
cows = sum([answer[x] != input[x] && contains(input.data,answer[x]) for x = 1:4])
|
||||
print("\nNot quite! Your guess is worth:\n$bulls Bulls\n$cows Cows\nPlease guess again\n\n>")
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
|
|
@ -1,7 +0,0 @@
|
|||
n:1+-4?9
|
||||
loop:{
|
||||
`1:"guess: ";g:(`i$-1_1:`)-48 / -48 to convert ascii digit codepoints to corresponding int values
|
||||
$[n~g;[`0:"yup!";`exit 0]
|
||||
(4=#g)&*/(g<10)&~g<0;`0:"bulls & cows: "," & "/$(b;(#g^g^n)-b:+/n=g)
|
||||
`0:"bad input"]}
|
||||
{1}loop/0 / "while true: loop". 0 is a dummy arg
|
||||
|
|
@ -1,27 +1,27 @@
|
|||
[
|
||||
define randomizer() => {
|
||||
local(n = string)
|
||||
while(#n->size < 4) => {
|
||||
local(r = integer_random(1,9)->asString)
|
||||
#n !>> #r ? #n->append(#r)
|
||||
}
|
||||
return #n
|
||||
local(n = string)
|
||||
while(#n->size < 4) => {
|
||||
local(r = integer_random(1,9)->asString)
|
||||
#n !>> #r ? #n->append(#r)
|
||||
}
|
||||
return #n
|
||||
}
|
||||
define cowbullchecker(n::string,a::string) => {
|
||||
integer(#n) == integer(#a) ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
|
||||
local(cowbull = map('cows'=0,'bulls'=0,'choice'=#a),'checked' = array)
|
||||
loop(4) => {
|
||||
if(#checked !>> integer(#a->values->get(loop_count))) => {
|
||||
#checked->insert(integer(#a->values->get(loop_count)))
|
||||
if(integer(#n->values->get(loop_count)) == integer(#a->values->get(loop_count))) => {
|
||||
#cowbull->find('bulls') += 1
|
||||
else(#n->values >> #a->values->get(loop_count))
|
||||
#cowbull->find('cows') += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
#cowbull->find('bulls') == 4 ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
|
||||
return (:true,#cowbull)
|
||||
integer(#n) == integer(#a) ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
|
||||
local(cowbull = map('cows'=0,'bulls'=0,'choice'=#a),'checked' = array)
|
||||
loop(4) => {
|
||||
if(#checked !>> integer(#a->values->get(loop_count))) => {
|
||||
#checked->insert(integer(#a->values->get(loop_count)))
|
||||
if(integer(#n->values->get(loop_count)) == integer(#a->values->get(loop_count))) => {
|
||||
#cowbull->find('bulls') += 1
|
||||
else(#n->values >> #a->values->get(loop_count))
|
||||
#cowbull->find('cows') += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
#cowbull->find('bulls') == 4 ? return (:true,map('cows'=0,'bulls'=4,'choice'=#a))
|
||||
return (:true,#cowbull)
|
||||
}
|
||||
session_start('user')
|
||||
session_addvar('user', 'num')
|
||||
|
|
@ -32,12 +32,12 @@ var(historic_choices)->isNotA(::array) ? var(historic_choices = array)
|
|||
local(success = false)
|
||||
// check answer
|
||||
if(web_request->param('a')->asString->size) => {
|
||||
local(success,result) = cowbullchecker($num,web_request->param('a')->asString)
|
||||
$historic_choices->insert(#result)
|
||||
local(success,result) = cowbullchecker($num,web_request->param('a')->asString)
|
||||
$historic_choices->insert(#result)
|
||||
}
|
||||
if(web_request->params->asStaticArray >> 'restart') => {
|
||||
$num = randomizer
|
||||
$historic_choices = array
|
||||
$num = randomizer
|
||||
$historic_choices = array
|
||||
}
|
||||
]
|
||||
<h1>Bulls and Cows</h1>
|
||||
|
|
@ -49,22 +49,22 @@ if(web_request->params->asStaticArray >> 'restart') => {
|
|||
[
|
||||
local(win = false)
|
||||
if($historic_choices->size) => {
|
||||
with c in $historic_choices do => {^
|
||||
'<p>'+#c->find('choice')+': Bulls: '+#c->find('bulls')+', Cows: '+#c->find('cows')
|
||||
if(#c->find('bulls') == 4) => {^
|
||||
' - YOU WIN!'
|
||||
#win = true
|
||||
^}
|
||||
'</p>'
|
||||
^}
|
||||
with c in $historic_choices do => {^
|
||||
'<p>'+#c->find('choice')+': Bulls: '+#c->find('bulls')+', Cows: '+#c->find('cows')
|
||||
if(#c->find('bulls') == 4) => {^
|
||||
' - YOU WIN!'
|
||||
#win = true
|
||||
^}
|
||||
'</p>'
|
||||
^}
|
||||
}
|
||||
if(not #win) => {^
|
||||
]
|
||||
<form action="?" method="post">
|
||||
<input name="a" value="[web_request->param('a')->asString]" size="5">
|
||||
<input type="submit" name="guess">
|
||||
<a href="?restart">Restart</a>
|
||||
<input name="a" value="[web_request->param('a')->asString]" size="5">
|
||||
<input type="submit" name="guess">
|
||||
<a href="?restart">Restart</a>
|
||||
</form>
|
||||
[else
|
||||
'<a href="?restart">Restart</a>'
|
||||
'<a href="?restart">Restart</a>'
|
||||
^}]
|
||||
|
|
|
|||
|
|
@ -1,63 +1,63 @@
|
|||
function createNewNumber ()
|
||||
math.randomseed(os.time())
|
||||
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
local tNumb = {} -- list of numbers
|
||||
for i = 1, 4 do
|
||||
table.insert(tNumb, math.random(#tNumb+1), table.remove(numbers, math.random(#numbers)))
|
||||
end
|
||||
return tNumb
|
||||
math.randomseed(os.time())
|
||||
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||
local tNumb = {} -- list of numbers
|
||||
for i = 1, 4 do
|
||||
table.insert(tNumb, math.random(#tNumb+1), table.remove(numbers, math.random(#numbers)))
|
||||
end
|
||||
return tNumb
|
||||
end
|
||||
|
||||
TNumber = createNewNumber ()
|
||||
print ('(right number: ' .. table.concat (TNumber) .. ')')
|
||||
|
||||
function isValueInList (value, list)
|
||||
for i, v in ipairs (list) do
|
||||
if v == value then return true end
|
||||
end
|
||||
return false
|
||||
for i, v in ipairs (list) do
|
||||
if v == value then return true end
|
||||
end
|
||||
return false
|
||||
end
|
||||
|
||||
local nGuesses = 0
|
||||
|
||||
while not GameOver do
|
||||
nGuesses = nGuesses + 1
|
||||
print("Enter your guess (or 'q' to quit): ")
|
||||
local input
|
||||
while not input do
|
||||
input = io.read()
|
||||
end
|
||||
if input == "q" then
|
||||
GameOver = true
|
||||
return
|
||||
end
|
||||
local tInput = {}
|
||||
for i=1, string.len(input) do
|
||||
local number = tonumber(string.sub(input,i,i))
|
||||
if number and not isValueInList (number, tInput) then
|
||||
table.insert (tInput, number)
|
||||
end
|
||||
end
|
||||
local malformed = false
|
||||
if not (string.len(input) == 4) or not (#tInput == 4) then
|
||||
print (nGuesses, 'bad input: too short or too long')
|
||||
malformed = true
|
||||
end
|
||||
|
||||
if not malformed then
|
||||
print (nGuesses, 'parsed input:', table.concat(tInput, ', '))
|
||||
local nBulls, nCows = 0, 0
|
||||
for i, number in ipairs (tInput) do
|
||||
if TNumber[i] == number then
|
||||
nBulls = nBulls + 1
|
||||
elseif isValueInList (number, TNumber) then
|
||||
nCows = nCows + 1
|
||||
end
|
||||
end
|
||||
print (nGuesses, 'Bulls: '.. nBulls .. ' Cows: ' .. nCows)
|
||||
if nBulls == 4 then
|
||||
print (nGuesses, 'Win!')
|
||||
GameOver = true
|
||||
end
|
||||
end
|
||||
nGuesses = nGuesses + 1
|
||||
print("Enter your guess (or 'q' to quit): ")
|
||||
local input
|
||||
while not input do
|
||||
input = io.read()
|
||||
end
|
||||
if input == "q" then
|
||||
GameOver = true
|
||||
return
|
||||
end
|
||||
local tInput = {}
|
||||
for i=1, string.len(input) do
|
||||
local number = tonumber(string.sub(input,i,i))
|
||||
if number and not isValueInList (number, tInput) then
|
||||
table.insert (tInput, number)
|
||||
end
|
||||
end
|
||||
local malformed = false
|
||||
if not (string.len(input) == 4) or not (#tInput == 4) then
|
||||
print (nGuesses, 'bad input: too short or too long')
|
||||
malformed = true
|
||||
end
|
||||
|
||||
if not malformed then
|
||||
print (nGuesses, 'parsed input:', table.concat(tInput, ', '))
|
||||
local nBulls, nCows = 0, 0
|
||||
for i, number in ipairs (tInput) do
|
||||
if TNumber[i] == number then
|
||||
nBulls = nBulls + 1
|
||||
elseif isValueInList (number, TNumber) then
|
||||
nCows = nCows + 1
|
||||
end
|
||||
end
|
||||
print (nGuesses, 'Bulls: '.. nBulls .. ' Cows: ' .. nCows)
|
||||
if nBulls == 4 then
|
||||
print (nGuesses, 'Win!')
|
||||
GameOver = true
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
|
|
@ -4,66 +4,66 @@ digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9)
|
|||
num = ""
|
||||
while num.count < numCount and digits.count > 0 do
|
||||
(
|
||||
local r = random 1 digits.count
|
||||
append num (digits[r] as string)
|
||||
deleteitem digits r
|
||||
local r = random 1 digits.count
|
||||
append num (digits[r] as string)
|
||||
deleteitem digits r
|
||||
)
|
||||
digits = undefined
|
||||
numGuesses = 0
|
||||
inf = "Rules: \n1. Choose only % unique digits in any combination"+\
|
||||
" (0 can't be used).\n2. Only positive integers are allowed."+\
|
||||
"\n3. For each digit that is in it's place, you get a bull,\n"+\
|
||||
"\tand for each digit that is not in it's place, you get a cow."+\
|
||||
"\n4. The game is won when your number matches the number I chose."+\
|
||||
"\n\nPress [esc] to quit the game.\n\n"
|
||||
" (0 can't be used).\n2. Only positive integers are allowed."+\
|
||||
"\n3. For each digit that is in it's place, you get a bull,\n"+\
|
||||
"\tand for each digit that is not in it's place, you get a cow."+\
|
||||
"\n4. The game is won when your number matches the number I chose."+\
|
||||
"\n\nPress [esc] to quit the game.\n\n"
|
||||
clearlistener()
|
||||
format inf num.count
|
||||
while not keyboard.escpressed do
|
||||
(
|
||||
local userVal = getkbvalue prompt:"\nEnter your number: "
|
||||
if (userVal as string) == num do
|
||||
(
|
||||
format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses
|
||||
exit with OK
|
||||
)
|
||||
local bulls = 0
|
||||
local cows = 0
|
||||
local badInput = false
|
||||
case of
|
||||
(
|
||||
(classof userVal != integer):
|
||||
(
|
||||
format "\nThe number must be a positive integer.\n"
|
||||
badInput = true
|
||||
)
|
||||
((userVal as string).count != num.count):
|
||||
(
|
||||
format "\nThe number must have % digits.\n" num.count
|
||||
badInput = true
|
||||
)
|
||||
((makeuniquearray (for i in 1 to (userVal as string).count \
|
||||
collect (userVal as string)[i])).count != (userVal as string).count):
|
||||
(
|
||||
format "\nThe number can only have unique digits.\n"
|
||||
badInput = true
|
||||
)
|
||||
)
|
||||
if not badInput do
|
||||
(
|
||||
userVal = userVal as string
|
||||
i = 1
|
||||
while i <= userVal.count do
|
||||
(
|
||||
for j = 1 to num.count do
|
||||
(
|
||||
if userVal[i] == num[j] do
|
||||
(
|
||||
if i == j then bulls += 1 else cows += 1
|
||||
)
|
||||
)
|
||||
i += 1
|
||||
)
|
||||
numGuesses += 1
|
||||
format "\nBulls: % Cows: %\n" bulls cows
|
||||
)
|
||||
local userVal = getkbvalue prompt:"\nEnter your number: "
|
||||
if (userVal as string) == num do
|
||||
(
|
||||
format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses
|
||||
exit with OK
|
||||
)
|
||||
local bulls = 0
|
||||
local cows = 0
|
||||
local badInput = false
|
||||
case of
|
||||
(
|
||||
(classof userVal != integer):
|
||||
(
|
||||
format "\nThe number must be a positive integer.\n"
|
||||
badInput = true
|
||||
)
|
||||
((userVal as string).count != num.count):
|
||||
(
|
||||
format "\nThe number must have % digits.\n" num.count
|
||||
badInput = true
|
||||
)
|
||||
((makeuniquearray (for i in 1 to (userVal as string).count \
|
||||
collect (userVal as string)[i])).count != (userVal as string).count):
|
||||
(
|
||||
format "\nThe number can only have unique digits.\n"
|
||||
badInput = true
|
||||
)
|
||||
)
|
||||
if not badInput do
|
||||
(
|
||||
userVal = userVal as string
|
||||
i = 1
|
||||
while i <= userVal.count do
|
||||
(
|
||||
for j = 1 to num.count do
|
||||
(
|
||||
if userVal[i] == num[j] do
|
||||
(
|
||||
if i == j then bulls += 1 else cows += 1
|
||||
)
|
||||
)
|
||||
i += 1
|
||||
)
|
||||
numGuesses += 1
|
||||
format "\nBulls: % Cows: %\n" bulls cows
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ Rules:
|
|||
1. Choose only 4 unique digits in any combination (0 can't be used).
|
||||
2. Only positive integers are allowed.
|
||||
3. For each digit that is in it's place, you get a bull,
|
||||
and for each digit that is not in it's place, you get a cow.
|
||||
and for each digit that is not in it's place, you get a cow.
|
||||
4. The game is won when your number matches the number I chose.
|
||||
|
||||
Press [esc] to quit the game.
|
||||
|
|
|
|||
|
|
@ -1,34 +1,34 @@
|
|||
BullCow New bull,cow,guess,guessed,ii,number,pos,x
|
||||
Set number="",x=1234567890
|
||||
For ii=1:1:4 Do
|
||||
. Set pos=$Random($Length(x))+1
|
||||
. Set number=number_$Extract(x,pos)
|
||||
. Set $Extract(x,pos)=""
|
||||
. Quit
|
||||
Write !,"The computer has selected a number that consists"
|
||||
Write !,"of four different digits."
|
||||
Write !!,"As you are guessing the number, ""bulls"" and ""cows"""
|
||||
Write !,"will be awarded: a ""bull"" for each digit that is"
|
||||
Write !,"placed in the correct position, and a ""cow"" for each"
|
||||
Write !,"digit that occurs in the number, but in a different place.",!
|
||||
Write !,"For a guess, enter 4 digits."
|
||||
Write !,"Any other input is interpreted as ""I give up"".",!
|
||||
Set guessed=0 For Do Quit:guessed
|
||||
. Write !,"Your guess: " Read guess If guess'?4n Set guessed=-1 Quit
|
||||
. Set (bull,cow)=0,x=guess
|
||||
. For ii=4:-1:1 If $Extract(x,ii)=$Extract(number,ii) Do
|
||||
. . Set bull=bull+1,$Extract(x,ii)=""
|
||||
. . Quit
|
||||
. For ii=1:1:$Length(x) Set:number[$Extract(x,ii) cow=cow+1
|
||||
. Write !,"You guessed ",guess,". That earns you "
|
||||
. If 'bull,'cow Write "neither bulls nor cows..." Quit
|
||||
. If bull Write bull," bull" Write:bull>1 "s"
|
||||
. If cow Write:bull " and " Write cow," cow" Write:cow>1 "s"
|
||||
. Write "."
|
||||
. If bull=4 Set guessed=1 Write !,"That's a perfect score."
|
||||
. Quit
|
||||
If guessed<0 Write !!,"The number was ",number,".",!
|
||||
Quit
|
||||
BullCow New bull,cow,guess,guessed,ii,number,pos,x
|
||||
Set number="",x=1234567890
|
||||
For ii=1:1:4 Do
|
||||
. Set pos=$Random($Length(x))+1
|
||||
. Set number=number_$Extract(x,pos)
|
||||
. Set $Extract(x,pos)=""
|
||||
. Quit
|
||||
Write !,"The computer has selected a number that consists"
|
||||
Write !,"of four different digits."
|
||||
Write !!,"As you are guessing the number, ""bulls"" and ""cows"""
|
||||
Write !,"will be awarded: a ""bull"" for each digit that is"
|
||||
Write !,"placed in the correct position, and a ""cow"" for each"
|
||||
Write !,"digit that occurs in the number, but in a different place.",!
|
||||
Write !,"For a guess, enter 4 digits."
|
||||
Write !,"Any other input is interpreted as ""I give up"".",!
|
||||
Set guessed=0 For Do Quit:guessed
|
||||
. Write !,"Your guess: " Read guess If guess'?4n Set guessed=-1 Quit
|
||||
. Set (bull,cow)=0,x=guess
|
||||
. For ii=4:-1:1 If $Extract(x,ii)=$Extract(number,ii) Do
|
||||
. . Set bull=bull+1,$Extract(x,ii)=""
|
||||
. . Quit
|
||||
. For ii=1:1:$Length(x) Set:number[$Extract(x,ii) cow=cow+1
|
||||
. Write !,"You guessed ",guess,". That earns you "
|
||||
. If 'bull,'cow Write "neither bulls nor cows..." Quit
|
||||
. If bull Write bull," bull" Write:bull>1 "s"
|
||||
. If cow Write:bull " and " Write cow," cow" Write:cow>1 "s"
|
||||
. Write "."
|
||||
. If bull=4 Set guessed=1 Write !,"That's a perfect score."
|
||||
. Quit
|
||||
If guessed<0 Write !!,"The number was ",number,".",!
|
||||
Quit
|
||||
Do BullCow
|
||||
|
||||
The computer has selected a number that consists
|
||||
|
|
|
|||
|
|
@ -1,55 +1,55 @@
|
|||
BC := proc(n) #where n is the number of turns the user wishes to play before they quit
|
||||
local target, win, numGuesses, guess, bulls, cows, i, err;
|
||||
target := [0, 0, 0, 0]:
|
||||
randomize(); #This is a command that makes sure that the numbers are truly randomized each time, otherwise your first time will always give the same result.
|
||||
while member(0, target) or numelems({op(target)}) < 4 do #loop continues to generate random numbers until you get one with no repeating digits or 0s
|
||||
target := [seq(parse(i), i in convert(rand(1234..9876)(), string))]: #a list of random numbers
|
||||
end do:
|
||||
local target, win, numGuesses, guess, bulls, cows, i, err;
|
||||
target := [0, 0, 0, 0]:
|
||||
randomize(); #This is a command that makes sure that the numbers are truly randomized each time, otherwise your first time will always give the same result.
|
||||
while member(0, target) or numelems({op(target)}) < 4 do #loop continues to generate random numbers until you get one with no repeating digits or 0s
|
||||
target := [seq(parse(i), i in convert(rand(1234..9876)(), string))]: #a list of random numbers
|
||||
end do:
|
||||
|
||||
win := false:
|
||||
numGuesses := 0:
|
||||
while win = false and numGuesses < n do #loop allows the user to play until they win or until a set amount of turns have passed
|
||||
err := true;
|
||||
while err do #loop asks for values until user enters a valid number
|
||||
printf("Please enter a 4 digit integer with no repeating digits\n");
|
||||
try#catches any errors in user input
|
||||
guess := [seq(parse(i), i in readline())];
|
||||
if hastype(guess, 'Not(numeric)', 'exclude_container') then
|
||||
printf("Postive integers only! Please guess again.\n\n");
|
||||
elif numelems(guess) <> 4 then
|
||||
printf("4 digit numbers only! Please guess again.\n\n");
|
||||
elif numelems({op(guess)}) < 4 then
|
||||
printf("No repeating digits! Please guess again.\n\n");
|
||||
elif member(0, guess) then
|
||||
printf("No 0s! Please guess again.\n\n");
|
||||
else
|
||||
err := false;
|
||||
end if;
|
||||
catch:
|
||||
printf("Invalid input. Please guess again.\n\n");
|
||||
end try;
|
||||
end do:
|
||||
numGuesses := numGuesses + 1;
|
||||
printf("Guess %a: %a\n", numGuesses, guess);
|
||||
bulls := 0;
|
||||
cows := 0;
|
||||
for i to 4 do #loop checks for bulls and cows in the user's guess
|
||||
if target[i] = guess[i] then
|
||||
bulls := bulls + 1;
|
||||
elif member(target[i], guess) then
|
||||
cows := cows + 1;
|
||||
end if;
|
||||
end do;
|
||||
if bulls = 4 then
|
||||
win := true;
|
||||
printf("The number was %a.\n", target);
|
||||
printf(StringTools[FormatMessage]("You won with %1 %{1|guesses|guess|guesses}.", numGuesses));
|
||||
else
|
||||
printf(StringTools[FormatMessage]("%1 %{1|Cows|Cow|Cows}, %2 %{2|Bulls|Bull|Bulls}.\n\n", cows, bulls));
|
||||
end if;
|
||||
end do:
|
||||
if win = false and numGuesses >= n then
|
||||
win := false:
|
||||
numGuesses := 0:
|
||||
while win = false and numGuesses < n do #loop allows the user to play until they win or until a set amount of turns have passed
|
||||
err := true;
|
||||
while err do #loop asks for values until user enters a valid number
|
||||
printf("Please enter a 4 digit integer with no repeating digits\n");
|
||||
try#catches any errors in user input
|
||||
guess := [seq(parse(i), i in readline())];
|
||||
if hastype(guess, 'Not(numeric)', 'exclude_container') then
|
||||
printf("Postive integers only! Please guess again.\n\n");
|
||||
elif numelems(guess) <> 4 then
|
||||
printf("4 digit numbers only! Please guess again.\n\n");
|
||||
elif numelems({op(guess)}) < 4 then
|
||||
printf("No repeating digits! Please guess again.\n\n");
|
||||
elif member(0, guess) then
|
||||
printf("No 0s! Please guess again.\n\n");
|
||||
else
|
||||
err := false;
|
||||
end if;
|
||||
catch:
|
||||
printf("Invalid input. Please guess again.\n\n");
|
||||
end try;
|
||||
end do:
|
||||
numGuesses := numGuesses + 1;
|
||||
printf("Guess %a: %a\n", numGuesses, guess);
|
||||
bulls := 0;
|
||||
cows := 0;
|
||||
for i to 4 do #loop checks for bulls and cows in the user's guess
|
||||
if target[i] = guess[i] then
|
||||
bulls := bulls + 1;
|
||||
elif member(target[i], guess) then
|
||||
cows := cows + 1;
|
||||
end if;
|
||||
end do;
|
||||
if bulls = 4 then
|
||||
win := true;
|
||||
printf("The number was %a.\n", target);
|
||||
printf(StringTools[FormatMessage]("You won with %1 %{1|guesses|guess|guesses}.", numGuesses));
|
||||
else
|
||||
printf(StringTools[FormatMessage]("%1 %{1|Cows|Cow|Cows}, %2 %{2|Bulls|Bull|Bulls}.\n\n", cows, bulls));
|
||||
end if;
|
||||
end do:
|
||||
if win = false and numGuesses >= n then
|
||||
printf("You lost! The number was %a.\n", target);
|
||||
end if;
|
||||
return NULL;
|
||||
return NULL;
|
||||
end proc:
|
||||
|
|
|
|||
|
|
@ -1,12 +1,12 @@
|
|||
digits=Last@FixedPointList[If[Length@Union@#==4,#,Table[Random[Integer,{1,9}],{4}]]&,{}]
|
||||
codes=ToCharacterCode[StringJoin[ToString/@digits]];
|
||||
Module[{r,bulls,cows},
|
||||
While[True,
|
||||
r=InputString[];
|
||||
If[r===$Canceled,Break[],
|
||||
With[{userCodes=ToCharacterCode@r},
|
||||
If[userCodes===codes,Print[r<>": You got it!"];Break[],
|
||||
If[Length@userCodes==Length@codes,
|
||||
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
|
||||
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
|
||||
Print["Guess four digits."]]]]]]]
|
||||
While[True,
|
||||
r=InputString[];
|
||||
If[r===$Canceled,Break[],
|
||||
With[{userCodes=ToCharacterCode@r},
|
||||
If[userCodes===codes,Print[r<>": You got it!"];Break[],
|
||||
If[Length@userCodes==Length@codes,
|
||||
bulls=Count[userCodes-codes,0];cows=Length@Intersection[codes,userCodes]-bulls;
|
||||
Print[r<>": "<>ToString[bulls]<>"bull(s), "<>ToString@cows<>"cow(s)."],
|
||||
Print["Guess four digits."]]]]]]]
|
||||
|
|
|
|||
|
|
@ -2,34 +2,34 @@ import Nanoquery.Util; random = new(Random)
|
|||
|
||||
// a function to verify the user's input
|
||||
def verify_digits(input)
|
||||
global size
|
||||
seen = ""
|
||||
global size
|
||||
seen = ""
|
||||
|
||||
if len(input) != size
|
||||
return false
|
||||
else
|
||||
for char in input
|
||||
if not char in "0123456789"
|
||||
return false
|
||||
else if char in seen
|
||||
return false
|
||||
end
|
||||
if len(input) != size
|
||||
return false
|
||||
else
|
||||
for char in input
|
||||
if not char in "0123456789"
|
||||
return false
|
||||
else if char in seen
|
||||
return false
|
||||
end
|
||||
|
||||
seen += char
|
||||
end
|
||||
end
|
||||
seen += char
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
return true
|
||||
end
|
||||
|
||||
size = 4
|
||||
chosen = ""
|
||||
while len(chosen) < size
|
||||
digit = random.getInt(8) + 1
|
||||
digit = random.getInt(8) + 1
|
||||
|
||||
if not str(digit) in chosen
|
||||
chosen += str(digit)
|
||||
end
|
||||
if not str(digit) in chosen
|
||||
chosen += str(digit)
|
||||
end
|
||||
end
|
||||
|
||||
println "I have chosen a number from 4 unique digits from 1 to 9 arranged in a random order."
|
||||
|
|
@ -38,29 +38,29 @@ println "You need to input a 4 digit, unique digit number as a guess at what I h
|
|||
guesses = 1
|
||||
won = false
|
||||
while !won
|
||||
print "\nNext guess [" + str(guesses) + "]: "
|
||||
guess = input()
|
||||
print "\nNext guess [" + str(guesses) + "]: "
|
||||
guess = input()
|
||||
|
||||
if !verify_digits(guess)
|
||||
println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
|
||||
else
|
||||
if guess = chosen
|
||||
won = true
|
||||
else
|
||||
bulls = 0
|
||||
cows = 0
|
||||
for i in range(0, size - 1)
|
||||
if guess[i] = chosen[i]
|
||||
bulls += 1
|
||||
else if guess[i] in chosen
|
||||
cows += 1
|
||||
end
|
||||
end
|
||||
if !verify_digits(guess)
|
||||
println "Problem, try again. You need to enter 4 unique digits from 1 to 9"
|
||||
else
|
||||
if guess = chosen
|
||||
won = true
|
||||
else
|
||||
bulls = 0
|
||||
cows = 0
|
||||
for i in range(0, size - 1)
|
||||
if guess[i] = chosen[i]
|
||||
bulls += 1
|
||||
else if guess[i] in chosen
|
||||
cows += 1
|
||||
end
|
||||
end
|
||||
|
||||
println format(" %d Bulls\n %d Cows", bulls, cows)
|
||||
guesses += 1
|
||||
end
|
||||
end
|
||||
println format(" %d Bulls\n %d Cows", bulls, cows)
|
||||
guesses += 1
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
println "\nCongratulations you guess correctly in " + guesses + " attempts"
|
||||
|
|
|
|||
|
|
@ -1,47 +0,0 @@
|
|||
[int]$guesses = $bulls = $cows = 0
|
||||
[string]$guess = "none"
|
||||
[string]$digits = ""
|
||||
|
||||
while ($digits.Length -lt 4)
|
||||
{
|
||||
$character = [char](49..57 | Get-Random)
|
||||
|
||||
if ($digits.IndexOf($character) -eq -1) {$digits += $character}
|
||||
}
|
||||
|
||||
Write-Host "`nGuess four digits (1-9) using no digit twice.`n" -ForegroundColor Cyan
|
||||
|
||||
while ($bulls -lt 4)
|
||||
{
|
||||
do
|
||||
{
|
||||
$prompt = "Guesses={0:0#}, Last='{1,4}', Bulls={2}, Cows={3}; Enter your guess" -f $guesses, $guess, $bulls, $cows
|
||||
$guess = Read-Host $prompt
|
||||
|
||||
if ($guess.Length -ne 4) {Write-Host "`nMust be a four-digit number`n" -ForegroundColor Red}
|
||||
if ($guess -notmatch "[1-9][1-9][1-9][1-9]") {Write-Host "`nMust be numbers 1-9`n" -ForegroundColor Red}
|
||||
}
|
||||
until ($guess.Length -eq 4)
|
||||
|
||||
$guesses += 1
|
||||
$bulls = $cows = 0
|
||||
|
||||
for ($i = 0; $i -lt 4; $i++)
|
||||
{
|
||||
$character = $digits.Substring($i,1)
|
||||
|
||||
if ($guess.Substring($i,1) -eq $character)
|
||||
{
|
||||
$bulls += 1
|
||||
}
|
||||
else
|
||||
{
|
||||
if ($guess.IndexOf($character) -ge 0)
|
||||
{
|
||||
$cows += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "`nYou won after $($guesses - 1) guesses." -ForegroundColor Cyan
|
||||
|
|
@ -12,45 +12,45 @@ digits(8).
|
|||
|
||||
|
||||
bulls_and_cows_server :-
|
||||
proposition(LenGuess),
|
||||
length(Solution, LenGuess),
|
||||
choose(Solution),
|
||||
repeat,
|
||||
write('Your guess : '),
|
||||
read(Guess),
|
||||
( study(Solution, Guess, Bulls, Cows)
|
||||
-> format('Bulls : ~w Cows : ~w~n', [Bulls, Cows]),
|
||||
Bulls = LenGuess
|
||||
; digits(Digits), Max is Digits + 1,
|
||||
format('Guess must be of ~w digits between 1 and ~w~n',
|
||||
[LenGuess, Max]),
|
||||
fail).
|
||||
proposition(LenGuess),
|
||||
length(Solution, LenGuess),
|
||||
choose(Solution),
|
||||
repeat,
|
||||
write('Your guess : '),
|
||||
read(Guess),
|
||||
( study(Solution, Guess, Bulls, Cows)
|
||||
-> format('Bulls : ~w Cows : ~w~n', [Bulls, Cows]),
|
||||
Bulls = LenGuess
|
||||
; digits(Digits), Max is Digits + 1,
|
||||
format('Guess must be of ~w digits between 1 and ~w~n',
|
||||
[LenGuess, Max]),
|
||||
fail).
|
||||
|
||||
choose(Solution) :-
|
||||
digits(Digits),
|
||||
Max is Digits + 1,
|
||||
repeat,
|
||||
maplist(\X^(X is random(Max) + 1), Solution),
|
||||
all_distinct(Solution),
|
||||
!.
|
||||
digits(Digits),
|
||||
Max is Digits + 1,
|
||||
repeat,
|
||||
maplist(\X^(X is random(Max) + 1), Solution),
|
||||
all_distinct(Solution),
|
||||
!.
|
||||
|
||||
study(Solution, Guess, Bulls, Cows) :-
|
||||
proposition(LenGuess),
|
||||
digits(Digits),
|
||||
|
||||
% compute the transformation 1234 => [1,2,3,4]
|
||||
atom_chars(Guess, Chars),
|
||||
maplist(\X^Y^(atom_number(X, Y)), Chars, Ms),
|
||||
|
||||
% check that the guess is well formed
|
||||
length(Ms, LenGuess),
|
||||
maplist(\X^(X > 0, X =< Digits+1), Ms),
|
||||
proposition(LenGuess),
|
||||
digits(Digits),
|
||||
|
||||
% compute the digit in good place
|
||||
foldl(\X^Y^V0^V1^((X = Y->V1 is V0+1; V1 = V0)),Solution, Ms, 0, Bulls),
|
||||
|
||||
% compute the digits in bad place
|
||||
foldl(\Y1^V2^V3^(foldl(\X2^Z2^Z3^(X2 = Y1 -> Z3 is Z2+1; Z3 = Z2), Ms, 0, TT1),
|
||||
V3 is V2+ TT1),
|
||||
Solution, 0, TT),
|
||||
Cows is TT - Bulls.
|
||||
% compute the transformation 1234 => [1,2,3,4]
|
||||
atom_chars(Guess, Chars),
|
||||
maplist(\X^Y^(atom_number(X, Y)), Chars, Ms),
|
||||
|
||||
% check that the guess is well formed
|
||||
length(Ms, LenGuess),
|
||||
maplist(\X^(X > 0, X =< Digits+1), Ms),
|
||||
|
||||
% compute the digit in good place
|
||||
foldl(\X^Y^V0^V1^((X = Y->V1 is V0+1; V1 = V0)),Solution, Ms, 0, Bulls),
|
||||
|
||||
% compute the digits in bad place
|
||||
foldl(\Y1^V2^V3^(foldl(\X2^Z2^Z3^(X2 = Y1 -> Z3 is Z2+1; Z3 = Z2), Ms, 0, TT1),
|
||||
V3 is V2+ TT1),
|
||||
Solution, 0, TT),
|
||||
Cows is TT - Bulls.
|
||||
|
|
|
|||
|
|
@ -4,13 +4,13 @@ bulls: 0
|
|||
random/seed now/time
|
||||
number: copy/part random a 4
|
||||
while [bulls <> 4] [
|
||||
bulls: 0
|
||||
cows: 0
|
||||
guess: ask "make a guess: "
|
||||
repeat i 4 [
|
||||
if (pick guess i) = (pick number i) [bulls: bulls + 1]
|
||||
]
|
||||
cows: (length? intersect guess number) - bulls
|
||||
print ["bulls: " bulls " cows: " cows]
|
||||
bulls: 0
|
||||
cows: 0
|
||||
guess: ask "make a guess: "
|
||||
repeat i 4 [
|
||||
if (pick guess i) = (pick number i) [bulls: bulls + 1]
|
||||
]
|
||||
cows: (length? intersect guess number) - bulls
|
||||
print ["bulls: " bulls " cows: " cows]
|
||||
]
|
||||
print "You won!"
|
||||
|
|
|
|||
|
|
@ -1,77 +1,77 @@
|
|||
repeat forever
|
||||
repeat forever
|
||||
put random(1111,9999) into num
|
||||
if character 1 of num is not equal to character 2 of num
|
||||
if character 1 of num is not equal to character 3 of num
|
||||
if character 1 of num is not equal to character 4 of num
|
||||
if character 2 of num is not equal to character 3 of num
|
||||
if character 2 of num is not equal to character 4 of num
|
||||
if character 3 of num is not equal to character 4 of num
|
||||
if num does not contain 0
|
||||
exit repeat
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set description to "Guess the 4 digit number" & newline & "- zero's excluded" & newline & "- each digit is unique" & newline & newline & "Receive 1 Bull for each digit that equals the corresponding digit in the random number." & newline & newline & "Receive 1 Cow for each digit that appears in the wrong position." & newline
|
||||
repeat forever
|
||||
repeat forever
|
||||
Ask "Guess the number" title "Bulls & Cows" message description
|
||||
put it into guess
|
||||
if number of characters in guess is equal to 4
|
||||
exit repeat
|
||||
else if guess is ""
|
||||
Answer "" with "Play" or "Quit" title "Quit Bulls & Cows?"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set score to {
|
||||
bulls: {
|
||||
qty: 0,
|
||||
values: []
|
||||
},
|
||||
cows: {
|
||||
qty: 0,
|
||||
values: []
|
||||
}
|
||||
}
|
||||
repeat the number of characters in num times
|
||||
if character the counter of guess is equal to character the counter of num
|
||||
add 1 to score.bulls.qty
|
||||
insert character the counter of guess into score.bulls.values
|
||||
else
|
||||
if num contains character the counter of guess
|
||||
if character the counter of guess is not equal to character the counter of num
|
||||
if score.bulls.values does not contain character the counter of guess and score.cows.values does not contain character the counter of guess
|
||||
add 1 to score.cows.qty
|
||||
insert character the counter of guess into score.cows.values
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set showScores to "Your score is:" & newline & newline & "Bulls:" && score.bulls.qty & newline & newline & "Cows:" && score.cows.qty
|
||||
if guess is not equal to num
|
||||
Answer showScores with "Guess Again" or "Quit" title "Score"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
else
|
||||
set winShowScores to showScores & newline & newline & "Your Guess:" && guess & newline & "Random Number:" && num & newline
|
||||
Answer winShowScores with "Play Again" or "Quit" title "You Win!"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
exit repeat
|
||||
end if
|
||||
end repeat
|
||||
repeat forever
|
||||
put random(1111,9999) into num
|
||||
if character 1 of num is not equal to character 2 of num
|
||||
if character 1 of num is not equal to character 3 of num
|
||||
if character 1 of num is not equal to character 4 of num
|
||||
if character 2 of num is not equal to character 3 of num
|
||||
if character 2 of num is not equal to character 4 of num
|
||||
if character 3 of num is not equal to character 4 of num
|
||||
if num does not contain 0
|
||||
exit repeat
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set description to "Guess the 4 digit number" & newline & "- zero's excluded" & newline & "- each digit is unique" & newline & newline & "Receive 1 Bull for each digit that equals the corresponding digit in the random number." & newline & newline & "Receive 1 Cow for each digit that appears in the wrong position." & newline
|
||||
repeat forever
|
||||
repeat forever
|
||||
Ask "Guess the number" title "Bulls & Cows" message description
|
||||
put it into guess
|
||||
if number of characters in guess is equal to 4
|
||||
exit repeat
|
||||
else if guess is ""
|
||||
Answer "" with "Play" or "Quit" title "Quit Bulls & Cows?"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set score to {
|
||||
bulls: {
|
||||
qty: 0,
|
||||
values: []
|
||||
},
|
||||
cows: {
|
||||
qty: 0,
|
||||
values: []
|
||||
}
|
||||
}
|
||||
repeat the number of characters in num times
|
||||
if character the counter of guess is equal to character the counter of num
|
||||
add 1 to score.bulls.qty
|
||||
insert character the counter of guess into score.bulls.values
|
||||
else
|
||||
if num contains character the counter of guess
|
||||
if character the counter of guess is not equal to character the counter of num
|
||||
if score.bulls.values does not contain character the counter of guess and score.cows.values does not contain character the counter of guess
|
||||
add 1 to score.cows.qty
|
||||
insert character the counter of guess into score.cows.values
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end if
|
||||
end repeat
|
||||
set showScores to "Your score is:" & newline & newline & "Bulls:" && score.bulls.qty & newline & newline & "Cows:" && score.cows.qty
|
||||
if guess is not equal to num
|
||||
Answer showScores with "Guess Again" or "Quit" title "Score"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
else
|
||||
set winShowScores to showScores & newline & newline & "Your Guess:" && guess & newline & "Random Number:" && num & newline
|
||||
Answer winShowScores with "Play Again" or "Quit" title "You Win!"
|
||||
put it into myAnswer
|
||||
if myAnswer is "Quit"
|
||||
exit all
|
||||
end if
|
||||
exit repeat
|
||||
end if
|
||||
end repeat
|
||||
end repeat
|
||||
|
|
|
|||
|
|
@ -1,57 +1,57 @@
|
|||
func generateRandomNumArray(numDigits: Int = 4) -> [Character]
|
||||
{
|
||||
guard (1 ... 9).contains(numDigits) else { fatalError("number out of range") }
|
||||
guard (1 ... 9).contains(numDigits) else { fatalError("number out of range") }
|
||||
|
||||
return Array("123456789".shuffled()[0 ..< numDigits])
|
||||
return Array("123456789".shuffled()[0 ..< numDigits])
|
||||
}
|
||||
|
||||
func parseGuess(_ guess: String, numDigits: Int = 4) -> String?
|
||||
{
|
||||
guard guess.count == numDigits else { return nil }
|
||||
guard guess.count == numDigits else { return nil }
|
||||
// Only digits 0 to 9 allowed, no Unicode fractions or numbers from other languages
|
||||
let guessArray = guess.filter{ $0.isASCII && $0.isWholeNumber }
|
||||
let guessArray = guess.filter{ $0.isASCII && $0.isWholeNumber }
|
||||
|
||||
guard Set(guessArray).count == numDigits else { return nil }
|
||||
guard Set(guessArray).count == numDigits else { return nil }
|
||||
|
||||
return guessArray
|
||||
return guessArray
|
||||
}
|
||||
|
||||
func pluralIfNeeded(_ count: Int, _ units: String) -> String
|
||||
{
|
||||
return "\(count) " + units + (count == 1 ? "" : "s")
|
||||
return "\(count) " + units + (count == 1 ? "" : "s")
|
||||
}
|
||||
|
||||
var guessAgain = "y"
|
||||
while guessAgain == "y"
|
||||
{
|
||||
let num = generateRandomNumArray()
|
||||
var bulls = 0
|
||||
var cows = 0
|
||||
let num = generateRandomNumArray()
|
||||
var bulls = 0
|
||||
var cows = 0
|
||||
|
||||
print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")
|
||||
print("Please enter a 4 digit number with digits between 1-9, no repetitions: ")
|
||||
|
||||
if let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr)
|
||||
{
|
||||
for (guess, actual) in zip(guess, num)
|
||||
{
|
||||
if guess == actual
|
||||
{
|
||||
bulls += 1
|
||||
}
|
||||
else if num.contains(guess)
|
||||
{
|
||||
cows += 1
|
||||
}
|
||||
}
|
||||
if let guessStr = readLine(strippingNewline: true), let guess = parseGuess(guessStr)
|
||||
{
|
||||
for (guess, actual) in zip(guess, num)
|
||||
{
|
||||
if guess == actual
|
||||
{
|
||||
bulls += 1
|
||||
}
|
||||
else if num.contains(guess)
|
||||
{
|
||||
cows += 1
|
||||
}
|
||||
}
|
||||
|
||||
print("Actual number: " + num)
|
||||
print("Your score: \(pluralIfNeeded(bulls, "bull")) and \(pluralIfNeeded(cows, "cow"))\n")
|
||||
print("Would you like to play again? (y): ")
|
||||
print("Actual number: " + num)
|
||||
print("Your score: \(pluralIfNeeded(bulls, "bull")) and \(pluralIfNeeded(cows, "cow"))\n")
|
||||
print("Would you like to play again? (y): ")
|
||||
|
||||
guessAgain = readLine(strippingNewline: true)?.lowercased() ?? "n"
|
||||
}
|
||||
else
|
||||
{
|
||||
print("Invalid input")
|
||||
}
|
||||
guessAgain = readLine(strippingNewline: true)?.lowercased() ?? "n"
|
||||
}
|
||||
else
|
||||
{
|
||||
print("Invalid input")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,52 +2,52 @@ import rand
|
|||
import os
|
||||
|
||||
fn main() {
|
||||
valid := ['1','2','3','4','5','6','7','8','9']
|
||||
mut value := []string{}
|
||||
mut guess, mut elem := '', ''
|
||||
mut cows, mut bulls := 0, 0
|
||||
println('Cows and Bulls')
|
||||
println('Guess four digit numbers of unique digits in the range 1 to 9.')
|
||||
println('A correct digit, but not in the correct place is a cow.')
|
||||
println('A correct digit, and in the correct place is a bull.')
|
||||
// generate pattern
|
||||
for value.len < 4 {
|
||||
elem = rand.string_from_set('123456789', 1)
|
||||
if value.any(it == elem) == false {
|
||||
value << elem
|
||||
}
|
||||
}
|
||||
// start game
|
||||
input: for _ in 0..3 {
|
||||
guess = os.input('Guess: ').str()
|
||||
// deal with malformed guesses
|
||||
if guess.len != 4 {println('Please input a four digit number.') continue input}
|
||||
for val in guess {
|
||||
if valid.contains(val.ascii_str()) == false {
|
||||
{println('Please input a number between 1 to 9.') continue input}
|
||||
}
|
||||
if guess.count(val.ascii_str()) > 1 {
|
||||
{println('Please do not repeat the same digit.') continue input}
|
||||
}
|
||||
}
|
||||
// score guesses
|
||||
for idx, gval in guess {
|
||||
match true {
|
||||
gval.ascii_str() == value[idx] {
|
||||
bulls++
|
||||
println('${gval.ascii_str()} was correctly guessed, and in the correct location! ')
|
||||
valid := ['1','2','3','4','5','6','7','8','9']
|
||||
mut value := []string{}
|
||||
mut guess, mut elem := '', ''
|
||||
mut cows, mut bulls := 0, 0
|
||||
println('Cows and Bulls')
|
||||
println('Guess four digit numbers of unique digits in the range 1 to 9.')
|
||||
println('A correct digit, but not in the correct place is a cow.')
|
||||
println('A correct digit, and in the correct place is a bull.')
|
||||
// generate pattern
|
||||
for value.len < 4 {
|
||||
elem = rand.string_from_set('123456789', 1)
|
||||
if value.any(it == elem) == false {
|
||||
value << elem
|
||||
}
|
||||
}
|
||||
// start game
|
||||
input: for _ in 0..3 {
|
||||
guess = os.input('Guess: ').str()
|
||||
// deal with malformed guesses
|
||||
if guess.len != 4 {println('Please input a four digit number.') continue input}
|
||||
for val in guess {
|
||||
if valid.contains(val.ascii_str()) == false {
|
||||
{println('Please input a number between 1 to 9.') continue input}
|
||||
}
|
||||
if guess.count(val.ascii_str()) > 1 {
|
||||
{println('Please do not repeat the same digit.') continue input}
|
||||
}
|
||||
}
|
||||
// score guesses
|
||||
for idx, gval in guess {
|
||||
match true {
|
||||
gval.ascii_str() == value[idx] {
|
||||
bulls++
|
||||
println('${gval.ascii_str()} was correctly guessed, and in the correct location! ')
|
||||
|
||||
}
|
||||
gval.ascii_str() in value {
|
||||
cows++
|
||||
println('${gval.ascii_str()} was correctly quessed, but not in the exact location! ')
|
||||
}
|
||||
else {}
|
||||
}
|
||||
if bulls == 4 {println('You are correct and have won!!! Congratulations!!!') exit(0)}
|
||||
}
|
||||
println('score: bulls: $bulls cows: $cows')
|
||||
}
|
||||
println('Only 3 guesses allowed. The correct value was: $value')
|
||||
println('Sorry, you lost this time, try again.')
|
||||
}
|
||||
gval.ascii_str() in value {
|
||||
cows++
|
||||
println('${gval.ascii_str()} was correctly quessed, but not in the exact location! ')
|
||||
}
|
||||
else {}
|
||||
}
|
||||
if bulls == 4 {println('You are correct and have won!!! Congratulations!!!') exit(0)}
|
||||
}
|
||||
println('score: bulls: $bulls cows: $cows')
|
||||
}
|
||||
println('Only 3 guesses allowed. The correct value was: $value')
|
||||
println('Sorry, you lost this time, try again.')
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,43 +0,0 @@
|
|||
randomize timer
|
||||
fail=array("Wrong number of chars","Only figures 0 to 9 allowed","Two or more figures are the same")
|
||||
p=dopuzzle()
|
||||
wscript.echo "Bulls and Cows. Guess my 4 figure number!"
|
||||
do
|
||||
do
|
||||
wscript.stdout.write vbcrlf & "your move ": s=trim(wscript.stdin.readline)
|
||||
c=checkinput(s)
|
||||
if not isarray (c) then wscript.stdout.write fail(c) :exit do
|
||||
bu=c(0)
|
||||
wscript.stdout.write "bulls: " & c(0) & " | cows: " & c(1)
|
||||
loop while 0
|
||||
loop until bu=4
|
||||
wscript.stdout.write vbcrlf & "You won! "
|
||||
|
||||
|
||||
function dopuzzle()
|
||||
dim b(10)
|
||||
for i=1 to 4
|
||||
do
|
||||
r=fix(rnd*10)
|
||||
loop until b(r)=0
|
||||
b(r)=1:dopuzzle=dopuzzle+chr(r+48)
|
||||
next
|
||||
end function
|
||||
|
||||
function checkinput(s)
|
||||
dim c(10)
|
||||
bu=0:co=0
|
||||
if len(s)<>4 then checkinput=0:exit function
|
||||
for i=1 to 4
|
||||
b=mid(s,i,1)
|
||||
if instr("0123456789",b)=0 then checkinput=1 :exit function
|
||||
if c(asc(b)-48)<>0 then checkinput=2 :exit function
|
||||
c(asc(b)-48)=1
|
||||
for j=1 to 4
|
||||
if asc(b)=asc(mid(p,j,1)) then
|
||||
if i=j then bu=bu+1 else co=co+1
|
||||
end if
|
||||
next
|
||||
next
|
||||
checkinput=array(bu,co)
|
||||
end function
|
||||
Loading…
Add table
Add a link
Reference in a new issue