2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,18 +1,31 @@
[[wp:Penney's_game|Penneys game]] is a game where two players bet on being the first to see a particular sequence of Heads and Tails in consecutive tosses of a fair coin.
[[wp:Penney's_game|Penney's game]]   is a game where two players bet on being the first to see a particular sequence of   [[wp:Coin_flipping|heads or tails]]   in consecutive tosses of a   [[wp:Fair_coin|fair coin]].
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example Heads, Tails, Heads, or HTH for short; then the other player on seeing the first players choice will choose his sequence. The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
It is common to agree on a sequence length of three then one player will openly choose a sequence, for example:
Heads, Tails, Heads, or
'''HTH''' for short.
The other player on seeing the first players choice will choose his sequence.
For example: One player might choose the sequence HHT and the other THT. Successive coin tosses of HTTHT gives the win to the second player as the last three coin tosses are his sequence.
The coin is tossed and the first player to see his sequence in the sequence of coin tosses wins.
;The Task:
;Example:
One player might choose the sequence   '''HHT'''   and the other   '''THT'''.  
Successive coin tosses of   '''HTTHT'''   gives the win to the second player as the last three coin tosses are his sequence.
;Task:
Create a program that tosses the coin, keeps score and plays Penney's game against a human opponent.
* Who chooses and shows their sequence of three should be chosen randomly.
* If going first, the computer should choose its sequence of three randomly.
* If going second, the computer should automatically play [[wp:Penney's_game#Analysis_of_the_three-bit_game|the optimum sequence]].
* Successive coin tosses should be shown.
:*   Who chooses and shows their sequence of three should be chosen randomly.
:*   If going first, the computer should randomly choose its sequence of three.
:*   If going second, the computer should automatically play [[wp:Penney's_game#Analysis_of_the_three-bit_game|the optimum sequence]].
:*   Successive coin tosses should be shown.
Show output of a game where the computer choses first and a game where the user goes first here on this page.
<br>
Show output of a game where the computer chooses first and a game where the user goes first here on this page.
;Refs:
* [https://www.youtube.com/watch?v=OcYnlSenF04 The Penney Ante Part 1] (Video).
* [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video).
;See also:
* &nbsp; [https://www.youtube.com/watch?v=OcYnlSenF04 The Penney Ante Part 1] (Video).
* &nbsp; [https://www.youtube.com/watch?v=U9wak7g5yQA The Penney Ante Part 2] (Video).
<br><br>

View file

@ -0,0 +1,81 @@
REM >penney
PRINT "*** Penney's Game ***"
REPEAT
PRINT ' "Heads you pick first, tails I pick first."
PRINT "And it is... ";
WAIT 100
ht% = RND(0 - TIME) AND 1
IF ht% THEN
PRINT "heads!"
PROC_player_chooses(player$)
computer$ = FN_optimal(player$)
PRINT "I choose "; computer$; "."
ELSE
PRINT "tails!"
computer$ = FN_random
PRINT "I choose "; computer$; "."
PROC_player_chooses(player$)
ENDIF
PRINT "Starting the game..." ' SPC 5;
sequence$ = ""
winner% = FALSE
REPEAT
WAIT 100
roll% = RND AND 1
IF roll% THEN
sequence$ += "H"
PRINT "H ";
ELSE
PRINT "T ";
sequence$ += "T"
ENDIF
IF RIGHT$(sequence$, 3) = computer$ THEN
PRINT ' "I won!"
winner% = TRUE
ELSE
IF RIGHT$(sequence$, 3) = player$ THEN
PRINT ' "Congratulations! You won."
winner% = TRUE
ENDIF
ENDIF
UNTIL winner%
REPEAT
valid% = FALSE
INPUT "Another game? (Y/N) " another$
IF INSTR("YN", another$) THEN valid% = TRUE
UNTIL valid%
UNTIL another$ = "N"
PRINT "Thank you for playing!"
END
:
DEF PROC_player_chooses(RETURN sequence$)
LOCAL choice$, valid%, i%
REPEAT
valid% = TRUE
PRINT "Enter a sequence of three choices, each of them either H or T:"
INPUT "> " sequence$
IF LEN sequence$ <> 3 THEN valid% = FALSE
IF valid% THEN
FOR i% = 1 TO 3
choice$ = MID$(sequence$, i%, 1)
IF choice$ <> "H" AND choice$ <> "T" THEN valid% = FALSE
NEXT
ENDIF
UNTIL valid%
ENDPROC
:
DEF FN_random
LOCAL sequence$, choice%, i%
sequence$ = ""
FOR i% = 1 TO 3
choice% = RND AND 1
IF choice% THEN sequence$ += "H" ELSE sequence$ += "T"
NEXT
= sequence$
:
DEF FN_optimal(sequence$)
IF MID$(sequence$, 2, 1) = "H" THEN
= "T" + LEFT$(sequence$, 2)
ELSE
= "H" + LEFT$(sequence$, 2)
ENDIF

View file

@ -0,0 +1,57 @@
defmodule Penney do
@toss [:Heads, :Tails]
def game(score \\ {0,0})
def game({iwin, ywin}=score) do
IO.puts "Penney game score I : #{iwin}, You : #{ywin}"
[i, you] = @toss
coin = Enum.random(@toss)
IO.puts "#{i} I start, #{you} you start ..... #{coin}"
{myC, yC} = setup(coin)
seq = for _ <- 1..3, do: Enum.random(@toss)
IO.write Enum.join(seq, " ")
{winner, score} = loop(seq, myC, yC, score)
IO.puts "\n #{winner} win!\n"
game(score)
end
defp setup(:Heads) do
myC = Enum.shuffle(@toss) ++ [Enum.random(@toss)]
joined = Enum.join(myC, " ")
IO.puts "I chose : #{joined}"
{myC, yourChoice}
end
defp setup(:Tails) do
yC = yourChoice
myC = (@toss -- [Enum.at(yC,1)]) ++ Enum.take(yC,2)
joined = Enum.join(myC, " ")
IO.puts "I chose : #{joined}"
{myC, yC}
end
defp yourChoice do
IO.write "Enter your choice (H/T) "
choice = read([])
IO.puts "You chose: #{Enum.join(choice, " ")}"
choice
end
defp read([_,_,_]=choice), do: choice
defp read(choice) do
case IO.getn("") |> String.upcase do
"H" -> read(choice ++ [:Heads])
"T" -> read(choice ++ [:Tails])
_ -> read(choice)
end
end
defp loop(myC, myC, _, {iwin, ywin}), do: {"I", {iwin+1, ywin}}
defp loop(yC, _, yC, {iwin, ywin}), do: {"You", {iwin, ywin+1}}
defp loop(seq, myC, yC, score) do
append = Enum.random(@toss)
IO.write " #{append}"
loop(tl(seq)++[append], myC, yC, score)
end
end
Penney.game

View file

@ -0,0 +1,63 @@
#===============================================================
# Penney's Game Task from Rosetta Code Wiki
# R implementation
#===============================================================
penneysgame <- function() {
#---------------------------------------------------------------
# Who goes first?
#---------------------------------------------------------------
first <- sample(c("PC", "Human"), 1)
#---------------------------------------------------------------
# Determine the sequences
#---------------------------------------------------------------
if (first == "PC") { # PC goes first
pc.seq <- sample(c("H", "T"), 3, replace = TRUE)
cat(paste("\nI choose first and will win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, ""))
} else if (first == "Human") { # Player goest first
cat(paste("\nYou can choose your winning sequence first.\n\n"))
human.seq <- readline("What sequence of three Heads/Tails will you win with: ")
human.seq <- unlist(strsplit(human.seq, "")) # Split the string into characters
pc.seq <- c(human.seq[2], human.seq[1:2]) # Append second element at the start
pc.seq[1] <- ifelse(pc.seq[1] == "H", "T", "H") # Switch first element to get the optimal guess
cat(paste("\nI win on first seeing", paste(pc.seq, collapse = ""), "in the list of tosses.\n"))
}
#---------------------------------------------------------------
# Start throwing the coin
#---------------------------------------------------------------
cat("\nThrowing:\n")
ran.seq <- NULL
while(TRUE) {
ran.seq <- c(ran.seq, sample(c("H", "T"), 1)) # Add a new coin throw to the vector of throws
cat("\n", paste(ran.seq, sep = "", collapse = "")) # Print the sequence thrown so far
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == pc.seq)) {
cat("\n\nI win!\n")
break
}
if (length(ran.seq) >= 3 && all(tail(ran.seq, 3) == human.seq)) {
cat("\n\nYou win!\n")
break
}
Sys.sleep(0.5) # Pause for 0.5 seconds
}
}

View file

@ -1,67 +1,67 @@
/*REXX program plays Penney's Game, a 2-player coin toss sequence game.*/
__=copies('',9) /*literal for eyecatching fence. */
signal on halt /*a clean way out if CLBF quits. */
parse arg # ? . /*get optional args from the C.L.*/
if #=='' | #=="," then #=3 /*default coin sequence length. */
if ?\=='' & ?\==',' then call random ,,? /*use seed for RANDOM #s ?*/
wins=0; do games=1 /*play a number of Penney's games*/
call game /*play a single inning of a game.*/
end /*games*/ /*keep at it 'til QUIT or halt.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────one-line subroutines────────────────*/
halt: say; say __ "Penney's Game was halted."; say; exit 13
r: arg ,$; do arg(1); $=$||random(0,1); end; return $
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/
/*──────────────────────────────────GAME subroutine─────────────────────*/
game: @.=; tosses=@. /*the coin toss sequence so far. */
toss1=r(1) /*result: 0=computer, 1=CBLF.*/
if \toss1 then call randComp /*maybe let the computer go first*/
if toss1 then say __ "You win the first toss, so you pick your sequence first."
else say __ "The computer won first toss, the pick was: " @.comp
call prompter /*get the human's guess from C.L.*/
call randComp /*get computer's guess if needed.*/
/*CBLF: carbon-based life form. */
say __ " your pick:" @.CBLF /*echo human's pick to terminal. */
say __ "computer's pick:" @.comp /* " comp.'s " " " */
say /* [↓] flip the coin 'til a win.*/
do flips=1 until pos(@.CBLF,tosses)\==0 | pos(@.comp,tosses)\==0
tosses=tosses || translate(r(1),'HT',10)
end /*flips*/ /* [↑] this is a flipping coin,*/
/* [↓] series of tosses*/
say __ "The tossed coin series was: " tosses /*show the coin tosses.*/
say
@@@="won this toss with " flips ' coin tosses.' /*handy literal.*/
if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end
else say __ "The computer" @@@
_=wins; if _==0 then _='no' /*use gooder English.*/
say __ "You've won" _ "game"s(wins) 'out of ' games"."
say; say copies('',79%2)''; say /*show eyeball fence.*/
return
/*──────────────────────────────────PROMPTER subroutine─────────────────*/
prompter: oops=__ 'Oops! '; a= /*define some handy REXX literals*/
@a_z='ABCDEFG-IJKLMNOPQRS+UVWXYZ' /*the extraneous alphabetic chars*/
p=__ 'Pick a sequence of' # "coin tosses of H or T (Heads or Tails) or Quit:"
do until ok; say; say p; pull a /*uppercase the answer.*/
if abbrev('QUIT',a,1) then exit 1 /*human wants to quit. */
a=space(translate(a,,@a_z',./\;:_'),0) /*elide extraneous chrs*/
b=translate(a,10,'HT'); L=length(a) /*tran───►bin; get len.*/
ok=0 /*response is OK so far*/
select /*verify user response.*/
when \datatype(b,'B') then say oops "Illegal response."
when \datatype(a,'M') then say oops "Illegal characters in response."
when L==0 then say oops "No choice was given."
when L<# then say oops "Not enough coin choices."
when L># then say oops "Too many coin choices."
when a==@.comp then say oops "You can't choose the computer's choice: " @.comp
otherwise ok=1
end /*select*/
end /*until ok*/
@.CBLF=a; @.CBLF!=b /*we have the human's guess now. */
return
/*──────────────────────────────────RANDCOMP subroutine─────────────────*/
randComp: if @.comp\=='' then return /*the computer already has a pick*/
_=@.CBLF! /* [↓] use best-choice algorithm.*/
if _\=='' then g=left((\substr(_,min(2,#),1))left(_,1)substr(_,3),#)
do until g\==@.CBLF!; g=r(#); end /*otherwise, generate a choice. */
@.comp=translate(g,'HT',10)
return
/*REXX program plays/simulates Penney's Game, a two-player coin toss sequence game. */
__=copies('',9) /*literal for eyecatching fence. */
signal on halt /*a clean way out if CLBF quits. */
parse arg # seed . /*obtain optional arguments from the CL*/
if #=='' | #=="," then #=3 /*Not specified? Then use the default.*/
if datatype(seed,'W') then call random ,,seed /*use seed for RANDOM #s repeatability.*/
wins=0; do games=1 /*simulate a number of Penney's games. */
call game /*simulate a single inning of a game. */
end /*games*/ /*keep at it until QUIT or halt. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
halt: say; say __ "Penney's Game was halted."; say; exit 13
r: arg ,$; do arg(1); $=$ || random(0,1); end; return $
s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
game: @.=; tosses=@. /*the coin toss sequence so far. */
toss1=r(1) /*result: 0=computer, 1=CBLF.*/
if \toss1 then call randComp /*maybe let the computer go first*/
if toss1 then say __ "You win the first toss, so you pick your sequence first."
else say __ "The computer won first toss, the pick was: " @.comp
call prompter /*get the human's guess from C.L.*/
call randComp /*get computer's guess if needed.*/
/*CBLF: carbon-based life form. */
say __ " your pick:" @.CBLF /*echo human's pick to terminal. */
say __ "computer's pick:" @.comp /* " comp.'s " " " */
say /* [↓] flip the coin 'til a win.*/
do flips=1 until pos(@.CBLF,tosses)\==0 | pos(@.comp,tosses)\==0
tosses=tosses || translate(r(1),'HT',10)
end /*flips*/ /* [↑] this is a flipping coin,*/
/* [↓] series of tosses*/
say __ "The tossed coin series was: " tosses
say
@@@="won this toss with " flips ' coin tosses.'
if pos(@.CBLF,tosses)\==0 then do; say __ "You" @@@; wins=wins+1; end
else say __ "The computer" @@@
_=wins; if _==0 then _='no'
say __ "You've won" _ "game"s(wins) 'out of ' games"."
say; say copies('',79%2)''; say
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
prompter: oops=__ 'Oops! '; a= /*define some handy REXX literals*/
@a_z='ABCDEFG-IJKLMNOPQRS+UVWXYZ' /*the extraneous alphabetic chars*/
p=__ 'Pick a sequence of' # "coin tosses of H or T (Heads or Tails) or Quit:"
do until ok; say; say p; pull a /*uppercase the answer. */
if abbrev('QUIT',a,1) then exit 1 /*the human wants to quit. */
a=space(translate(a,,@a_z',./\;:_'),0) /*elide extraneous characters. */
b=translate(a,10,'HT'); L=length(a) /*translate ───► bin; get length.*/
ok=0 /*the response is OK (so far). */
select /*verify the user response. */
when \datatype(b,'B') then say oops "Illegal response."
when \datatype(a,'M') then say oops "Illegal characters in response."
when L==0 then say oops "No choice was given."
when L<# then say oops "Not enough coin choices."
when L># then say oops "Too many coin choices."
when a==@.comp then say oops "You can't choose the computer's choice: " @.comp
otherwise ok=1
end /*select*/
end /*until ok*/
@.CBLF=a; @.CBLF!=b /*we have the human's guess now. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
randComp: if @.comp\=='' then return /*the computer already has a pick*/
_=@.CBLF! /* [↓] use best-choice algorithm.*/
if _\=='' then g=left((\substr(_, min(2, #), 1))left(_, 1)substr(_, 3), #)
do until g\==@.CBLF!; g=r(#); end /*otherwise, generate a choice. */
@.comp=translate(g, 'HT', 10)
return

View file

@ -1,5 +1,3 @@
# Penney's Game
Toss = [:Heads, :Tails]
def yourChoice
@ -14,22 +12,24 @@ def yourChoice
choice
end
puts "%s I start, %s you start ..... #{coin = Toss.sample}" % Toss
if coin == Toss[0]
myC = Array.new(3){Toss.sample}
puts "I chose #{myC.join(' ')}"
yC = yourChoice
else
yC = yourChoice
myC = Toss - [yC[1]] + yC.first(2)
puts "I chose #{myC.join(' ')}"
end
seq = Array.new(3){Toss.sample}
print seq.join(' ')
loop do
puts "\n I win!" or break if seq == myC
puts "\n You win!" or break if seq == yC
seq.push(Toss.sample).shift
print " #{seq[-1]}"
puts "\n%s I start, %s you start ..... %s" % [*Toss, coin = Toss.sample]
if coin == Toss[0]
myC = Toss.shuffle << Toss.sample
puts "I chose #{myC.join(' ')}"
yC = yourChoice
else
yC = yourChoice
myC = Toss - [yC[1]] + yC.first(2)
puts "I chose #{myC.join(' ')}"
end
seq = Array.new(3){Toss.sample}
print seq.join(' ')
loop do
puts "\n I win!" or break if seq == myC
puts "\n You win!" or break if seq == yC
seq.push(Toss.sample).shift
print " #{seq[-1]}"
end
end