Penney's game is a game where two players bet on being the first to see a particular sequence of heads or tails in consecutive tosses of a 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.

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.



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 randomly choose its sequence of three.
 If going second, the computer should automatically play the optimum sequence.
 Successive coin tosses should be shown.


Show output of a game where the computer chooses first and a game where the user goes first here on this page.



See also
 The Penney Ante Part 1 (Video).
 The Penney Ante Part 2 (Video).


require 'format/printf numeric'
 
randomize ''                               NB. randomize seed for new session
 
Vals=: 'HT'                                NB. valid values
input=: 1!:1@<&1:                          NB. get input from user
prompt=: input@echo                        NB. prompt user for input
checkInput=: 'Choose 3 H/Ts' assert (Vals e.~ ]) , 3 = #
getUserSeq=: (] [ checkInput)@toupper@prompt
choose1st=: Vals {~ 3 ?@$ 2:               NB. computer chooses 1st
choose2nd=: (0 1 1=1 0 1{])&.(Vals&i.)     NB. computer chooses 2nd
 
playPenney=: verb define
  if. ?2 do.                               NB. randomize first chooser
    Comp=. choose1st ''
    'Computer chose %s' printf <Comp
    You=. getUserSeq 'Choose a sequence of three coin tosses (H/T):'
    'Choose a different sequence to computer' assert You -.@-: Comp
  else.
    You=. getUserSeq 'Choose a sequence of three coin tosses (H/T):'
    Comp=. choose2nd You
    'Computer chose %s ' printf <Comp
  end.
  Tosses=. Vals {~ 100 ?@$ 2
  Result=. (Comp,:You) {.@I.@E."1 Tosses
  'Toss sequence is %s' printf < (3 + <./ Result) {. Tosses
  echo ('No result';'You win!';'Computer won!') {::~ *-/ Result
)