June 2018 Update

This commit is contained in:
Ingy döt Net 2018-06-22 20:57:24 +00:00
parent ba8067c3b7
commit 22f33d4004
5278 changed files with 84726 additions and 14379 deletions

View file

@ -0,0 +1,88 @@
USING: arrays ascii io kernel math prettyprint random sequences
strings ;
IN: rosetta-code.penneys-game
! Generate a random boolean.
: t|f ( -- t/f )
1 random-bits 0 = ;
! Checks whether the sequence chosen by the human is valid.
: valid-input? ( seq -- ? )
[ [ CHAR: H = ] [ CHAR: T = ] bi or ] filter length 3 = ;
! Prompt the human player for a sequence.
: input-seq ( -- seq )
"Please input a 3-long sequence of H or T (heads or tails)."
print "Example: HTH" print "> " write readln >upper >array ;
! Get the human player's input sequence with error checking.
: get-input ( -- seq )
t [ drop input-seq dup valid-input? not ] loop ;
! Add a random coin flip to a vector.
: flip-coin ( vector -- vector' )
t|f CHAR: H CHAR: T ? over push ;
! Generate a random 3-long sequence of coin flips.
: rand-seq ( -- seq )
V{ } clone 3 [ flip-coin ] times ;
! Generate the optimal sequence response to a given sequence.
: optimal ( seq1 -- seq2 )
[ second dup CHAR: H = [ CHAR: T ] [ CHAR: H ] if ]
[ first ] [ second ] tri 3array nip dup
"The computer chose " write >string write "." print ;
! Choose a random sequence for the computer and report what
! was chosen.
: computer-first ( -- seq )
"The computer picks a sequence first and chooses " write
rand-seq dup >string write "." print >array ;
! The human is prompted to choose any sequence with no
! restrictions.
: human-first ( -- seq )
"You get to go first." print get-input ;
! Forbid the player from choosing the same sequence as the
! computer.
: human-second ( cseq -- cseq hseq )
get-input [ 2dup = not ]
[ drop
"You may not choose the same sequence as the computer."
print get-input
] until ;
! Display a message introducing the game.
: welcome ( -- )
"Welcome to Penney's Game. The computer or the player" print
"will be randomly selected to choose a sequence of" print
"three coin tosses. The sequence will be shown to the" print
"opponent, and then he will choose a sequence." print nl
"Then, a coin will be flipped until the sequence" print
"matches the last three coin flips, and a winner" print
"announced." print nl ;
! Check for human victory.
: human-won? ( cseq hseq coin-flips -- ? )
3 tail* >array = nip ;
! Check for computer victory.
: computer-won? ( cseq hseq coin-flips -- ? )
3 tail* >array pick = 2nip ;
! Flip a coin until a victory is detected. Then, inform the
! player who won.
: flip-coins ( cseq hseq -- )
"Flipping coins..." print
rand-seq [ 3dup [ human-won? ] [ computer-won? ] 3bi or ]
[ flip-coin ] until dup >string print human-won?
[ "You won!" print ] [ "The computer won." print ] if ;
! Randomly choose a player to choose their sequence first.
! Then play a full round of Penney's Game.
: start-game ( -- )
welcome t|f [ human-first dup optimal swap ]
[ computer-first human-second ] if flip-coins ;
start-game

View file

@ -0,0 +1,69 @@
// version 1.2.10
import java.util.Random
val rand = Random()
val optimum = mapOf(
"HHH" to "THH", "HHT" to "THH", "HTH" to "HHT", "HTT" to "HHT",
"THH" to "TTH", "THT" to "TTH", "TTH" to "HTT", "TTT" to "HTT"
)
fun getUserSequence(): String {
println("A sequence of three H or T should be entered")
var userSeq: String
do {
print("Enter your sequence: ")
userSeq = readLine()!!.toUpperCase()
}
while (userSeq.length != 3 || userSeq.any { it != 'H' && it != 'T' })
return userSeq
}
fun getComputerSequence(userSeq: String = ""): String {
val compSeq = if(userSeq == "")
String(CharArray(3) { if (rand.nextInt(2) == 0) 'T' else 'H' })
else
optimum[userSeq]!!
println("Computer's sequence: $compSeq")
return compSeq
}
fun main(args: Array<String>) {
var userSeq: String
var compSeq: String
val r = rand.nextInt(2)
if (r == 0) {
println("You go first")
userSeq = getUserSequence()
println()
compSeq = getComputerSequence(userSeq)
}
else {
println("Computer goes first")
compSeq = getComputerSequence()
println()
userSeq = getUserSequence()
}
println()
val coins = StringBuilder()
while (true) {
val coin = if (rand.nextInt(2) == 0) 'H' else 'T'
coins.append(coin)
println("Coins flipped: $coins")
val len = coins.length
if (len >= 3) {
val seq = coins.substring(len - 3, len)
if (seq == userSeq) {
println("\nYou win!")
return
}
else if (seq == compSeq) {
println("\nComputer wins!")
return
}
}
Thread.sleep(2000) // wait two seconds for next flip
}
}

View file

@ -32,7 +32,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ {
my @mine;
if $flip == $mefirst {
print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = Coin.roll(3);
print "{Yay.pick}! I get to choose first, and I choose: "; sleep 2; say @mine = |Coin.roll(3);
@yours = your-choice("Now you gotta choose: ");
while @yours eqv @mine {
say "{Bozo.pick}! We'd both win at the same time if you pick that!";
@ -43,7 +43,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ {
else {
@yours = your-choice("{Boo.pick}! First you choose: ");
say "OK, you'll win if we see: ", @yours;
print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), @yours[0,1];
print "In that case, I'll just randomly choose: "; sleep 2; say @mine = Coin(+!@yours[1]), |@yours[0,1];
}
sub check($a,$b,$c) {
@ -65,7 +65,7 @@ repeat until prompt("Wanna play again? ").lc ~~ /^n/ {
"Can I borrow that coin again?").pick;
sleep 1;
print "Here we go!\n\t";
for Coin.roll(3), &check ...^ :!defined {
for |Coin.roll(3), &check ...^ :!defined {
flipping;
print "$_ ";
}

View file

@ -0,0 +1,45 @@
(seed (in "/dev/urandom" (rd 8)))
(setq *S (list 0 0))
(de toss (N)
(make
(do N
(link (if (rand T) "T" "H")) ) ) )
(de comp (A Lst)
(or
(for ((I . L) Lst (cddr L) (cdr L))
(T (fully = A L) I) )
T ) )
(de score NIL
(prinl)
(prinl "Total score:")
(prinl "^Iuser: " (car *S))
(prinl "^Icomp: " (cadr *S)) )
(de play NIL
(let (C (toss 3) Lst (toss (rand 5 12)) U)
(prinl)
(prin "Select toss: ")
(setq U (in NIL (skip) (line)))
(prinl "Comp toss: " C)
(prinl "Toss: " Lst)
(setq @ (comp U Lst) @@ (comp C Lst) )
(cond
((< @ @@) (prinl "User win.") (inc *S))
((> @ @@) (prinl "Comp win.") (inc (cdr *S)))
(T (prinl "Draw, lets play again.")) )
(score) ) )
(de go NIL
(loop
(play)
(T
(prog
(prinl)
(prin "Want play again? Y/N: ")
(= "N" (uppc (in NIL (char)))) ) ) ) )
(go)

View file

@ -0,0 +1,81 @@
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const HT As String = "H T"
Public Sub PenneysGame()
Dim S$, YourSeq$, ComputeSeq$, i&, Seq$, WhoWin$, flag As Boolean
Do
S = WhoWillBeFirst(Choice("Who will be first"))
If S = "ABORT" Then Exit Do
Debug.Print S; " start"
YourSeq = Choice("Your sequence", 3)
If YourSeq Like "*ABORT*" Then Exit Do
Debug.Print "Your sequence : " & YourSeq
ComputeSeq = vbNullString
For i = 1 To 3
ComputeSeq = ComputeSeq & Random
Next i
Debug.Print "Computer sequence : " & ComputeSeq
Seq = vbNullString
Do
Seq = Seq & Random
Debug.Print Seq
Sleep 1000
Loop While Not Winner(ComputeSeq, YourSeq, Seq, WhoWin)
Debug.Print WhoWin; " win"
If MsgBox(WhoWin & " win" & vbCrLf & "Play again?", vbYesNo) = vbNo Then flag = True
Debug.Print ""
Loop While Not flag
Debug.Print "Game over"
End Sub
Private Function WhoWillBeFirst(YourChoice As String) As String
Dim S$
S = Random
Select Case YourChoice
Case "ABORT": WhoWillBeFirst = YourChoice
Case Else:
WhoWillBeFirst = IIf(S = YourChoice, "You", "Computer")
End Select
End Function
Private Function Choice(Title As String, Optional Seq As Integer) As String
Dim S$, i&, t$
If Seq = 0 Then Seq = 1
t = Title
For i = 1 To Seq
S = vbNullString
Do
S = InputBox("Choose between H or T : ", t)
If StrPtr(S) = 0 Then S = "Abort"
S = UCase(S)
Loop While S <> "H" And S <> "T" And S <> "ABORT"
Choice = Choice & S
t = Title & " " & Choice
If Choice Like "*ABORT*" Then Exit For
Next i
End Function
Private Function Random() As String
Randomize Timer
Random = Split(HT, " ")(CInt(Rnd))
End Function
Private Function Winner(Cs$, Ys$, S$, W$) As Boolean
If Len(S) < 3 Then
Winner = False
Else
If Right(S, 3) = Cs And Right(S, 3) = Ys Then
Winner = True
W = "Computer & you"
ElseIf Right(S, 3) = Cs And Right(S, 3) <> Ys Then
Winner = True
W = "Computer"
ElseIf Right(S, 3) = Ys And Right(S, 3) <> Cs Then
Winner = True
W = "You"
End If
End If
End Function