import random, strutils, tables

type
  Choice {.pure.} = enum Rock, Paper, Scissors
  History = tuple[total: int; counts: CountTable[Choice]]

const Successor: array[Choice, Choice] = [Paper, Scissors, Rock]

func `>`(a, b: Choice): bool =
  ## By construction, only the successor is greater than the choice.
  a == Successor[b]

proc choose(history: History): Choice =
  ## Make a weighted random choice using the player counts
  ## then select the choice likely to beat it.
  var value = rand(1..history.total)
  for choice, count in history.counts.pairs:
    if value <= count:
      return Successor[choice]
    dec value, count

randomize()

# Initialize history with one for each choice in order to avoid special case.
var history: History = (3, [Rock, Paper, Scissors].toCountTable)

echo "To quit game, type 'q' when asked for your choice."

var myChoice, yourChoice: Choice
var myWins, yourWins = 0

while true:

  # Get player choice.
  try:
    stdout.write "Rock(1), paper(2), scissors(3). Your choice? "
    let answer = stdin.readLine().strip()
    if answer == "q":
      quit "Quitting game.", QuitSuccess
    if answer notin ["1", "2", "3"]:
      echo "Invalid choice."
      continue
    yourChoice = Choice(ord(answer[0]) - ord('1'))
  except EOFError:
    quit "Quitting game.", QuitFailure

  # Make my choice.
  myChoice = history.choose()
  echo "I choosed ", myChoice, '.'
  history.counts.inc yourChoice
  inc history.total

  # Display result of round.
  if myChoice == yourChoice:
    echo "It’s a tie."
  elif myChoice > yourChoice:
    echo "I win."
    inc myWins
  else:
    echo "You win."
    inc yourWins
  echo "Total wins. You: ", yourWins, "  Me: ", myWins


' FB 1.05.0 Win64

Function romanEncode(n As Integer) As String
  If n < 1 OrElse n > 3999 Then Return "" '' can only encode numbers in range 1 to 3999
  Dim roman1(0 To 2) As String = {"MMM", "MM", "M"}
  Dim roman2(0 To 8) As String = {"CM", "DCCC", "DCC", "DC", "D", "CD", "CCC", "CC", "C"}
  Dim roman3(0 To 8) As String = {"XC", "LXXX", "LXX", "LX", "L", "XL", "XXX", "XX", "X"}
  Dim roman4(0 To 8) As String = {"IX", "VIII", "VII", "VI", "V", "IV", "III", "II", "I"}
  Dim As Integer thousands, hundreds, tens, units
  thousands = n \ 1000
  n Mod= 1000
  hundreds = n \ 100
  n Mod= 100
  tens = n \ 10
  units = n Mod 10
  Dim roman As String = ""
  If thousands > 0  Then roman += roman1(3 - thousands)
  If hundreds > 0   Then roman += roman2(9 - hundreds)
  If tens > 0       Then roman += roman3(9 - tens)
  If units > 0      Then roman += roman4(9 - units)
  Return roman
End Function

Dim a(2) As Integer = {1990, 2008, 1666}
For i As Integer = 0 To 2
  Print a(i); " => "; romanEncode(a(i))
Next

Print
Print "Press any key to quit"
Sleep


10 COMPUTER=RND(3)+1
20 COMPUTER$="ROCK"
30 IF COMPUTER=2 THEN COMPUTER$="PAPER"
40 IF COMPUTER=3 THEN COMPUTER$="SCISSORS"
50 INPUT "ROCK, PAPER OR SCISSORS? ",HUMAN$
60 IF HUMAN$="ROCK" THEN GOTO 100
70 IF HUMAN$="PAPER" THEN GOTO 100
80 IF HUMAN$="SCISSORS" THEN GOTO 100
90 PRINT "INVALID GUESS. TRY AGAIN.": GOTO 50
100 PRINT "YOU CHOSE "HUMAN$" AND THE COMPUTER CHOSE "COMPUTER$"."
110 IF HUMAN$=COMPUTER$ THEN PRINT "THOSE ARE THE SAME CHOICES";", SO YOU TIED."
120 IF HUMAN$="ROCK" AND COMPUTER=2 THEN PRINT "PAPER COVERS ROCK, SO YOU LOSE."
130 IF HUMAN$="ROCK" AND COMPUTER=3 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU WIN."
140 IF HUMAN$="PAPER" AND COMPUTER=1 THEN PRINT "PAPER COVERS ROCK, SO YOU WIN."
150 IF HUMAN$="PAPER" AND COMPUTER=3 THEN PRINT "SCISSORS CUT PAPER";", SO YOU LOSE."
160 IF HUMAN$="SCISSORS" AND COMPUTER=1 THEN PRINT "ROCK BLUNTS SCISSORS";", SO YOU LOSE."
170 IF HUMAN$="SCISSORS" AND COMPUTER=2 THEN PRINT "SCISSORS CUT PAPER, SO YOU WIN."10 COMPUTER=RND(3)+1


let pf = Printf.printf ;;

let looses a b = match a, b with
     `R, `P -> true
   | `P, `S -> true
   | `S, `R -> true
   |  _,  _ -> false ;;

let rec get_move () =
   pf "[R]ock, [P]aper, [S]cisors [Q]uit? " ;
   match String.uppercase (read_line ()) with
        "P" -> `P
      | "S" -> `S
      | "R" -> `R
      | "Q" -> exit 0
      | _   -> get_move () ;;

let str_of_move = function
        `P -> "paper"
      | `R -> "rock"
      | `S -> "scisors" ;;

let comp_move r p s =
   let tot = r +. p +. s in
   let n = Random.float 1.0 in
   if n < r /. tot then
      `R
   else
      if n < (r +. p) /. tot then
         `P
      else
         `S ;;

let rec make_moves r p s =
   let cm = comp_move r p s in   (* Computer move is based on game history. *)
   let hm = get_move () in       (* Human move is requested. *)
   pf "Me: %s. You: %s. " (str_of_move cm) (str_of_move hm);
   let outcome =
      if looses hm cm then
         "I win. You loose.\n"
      else if cm = hm then
         "We draw.\n"
      else
         "You win. I loose.\n"
   in pf "%s" outcome;
   match hm with (* Play on with adapted strategy. *)
        `S -> make_moves (r +. 1.) p s
      | `R -> make_moves r (p +. 1.) s
      | `P -> make_moves r p (s +. 1.) ;;

(* Main loop. *)
make_moves 1. 1. 1. ;;


window 1

local fn DecimaltoRoman( decimal as short ) as Str15
  short arabic(12)
  Str15 roman(12)
  long  i
  Str15 result : result = ""

  arabic(0) = 1000 : arabic(1) = 900 : arabic(2) = 500 : arabic(3) = 400
  arabic(4) = 100  : arabic(5) = 90  : arabic(6) = 50  : arabic(7)  = 40
  arabic(8) = 10   : arabic(9) = 9   : arabic(10) = 5  : arabic(11) = 4: arabic(12) = 1

  roman(0) = "M" : roman(1) = "CM" : roman(2) = "D"  : roman(3)  = "CD"
  roman(4) = "C" : roman(5) = "XC" : roman(6) = "L"  : roman(7)  = "XL"
  roman(8) = "X" : roman(9) = "IX" : roman(10) = "V" : roman(11) = "IV" : roman(12) = "I"

  for i = 0 to 12
    while ( decimal >= arabic(i) )
      result = result + roman(i)
      decimal = decimal - arabic(i)
    wend
  next i
  if result == "" then result = "Zepherium"
end fn = result

print "1990 = "; fn DecimaltoRoman( 1990 )
print "2008 = "; fn DecimaltoRoman( 2008 )
print "2016 = "; fn DecimaltoRoman( 2016 )
print "1666 = "; fn DecimaltoRoman( 1666 )
print "3888 = "; fn DecimaltoRoman( 3888 )
print "1914 = "; fn DecimaltoRoman( 1914 )
print "1000 = "; fn DecimaltoRoman( 1000 )
print " 513 = "; fn DecimaltoRoman(  513 )
print "  33 = "; fn DecimaltoRoman(   33 )

HandleEvents


package main

import "fmt"

var (
    m0 = []string{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}
    m1 = []string{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}
    m2 = []string{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}
    m3 = []string{"", "M", "MM", "MMM", "I̅V̅",
        "V̅", "V̅I̅", "V̅I̅I̅", "V̅I̅I̅I̅", "I̅X̅"}
    m4 = []string{"", "X̅", "X̅X̅", "X̅X̅X̅", "X̅L̅",
        "L̅", "L̅X̅", "L̅X̅X̅", "L̅X̅X̅X̅", "X̅C̅"}
    m5 = []string{"", "C̅", "C̅C̅", "C̅C̅C̅", "C̅D̅",
        "D̅", "D̅C̅", "D̅C̅C̅", "D̅C̅C̅C̅", "C̅M̅"}
    m6 = []string{"", "M̅", "M̅M̅", "M̅M̅M̅"}
)

func formatRoman(n int) (string, bool) {
    if n < 1 || n >= 4e6 {
        return "", false
    }
    // this is efficient in Go.  the seven operands are evaluated,
    // then a single allocation is made of the exact size needed for the result.
    return m6[n/1e6] + m5[n%1e6/1e5] + m4[n%1e5/1e4] + m3[n%1e4/1e3] +
        m2[n%1e3/1e2] + m1[n%100/10] + m0[n%10],
        true
}

func main() {
    // show three numbers mentioned in task descriptions
    for _, n := range []int{1990, 2008, 1666} {
        r, ok := formatRoman(n)
        if ok {
            fmt.Println(n, "==", r)
        } else {
            fmt.Println(n, "not representable")
        }
    }
}


contest(rounds)={
  my(v=[1,1,1],wins,losses); \\ Laplace rule
  for(i=1,rounds,
    my(computer,player,t);
    t=random(v[1]+v[2]+v[3]);
    if(t<v[1], computer = "R",
      if(t<v[1]+v[2], computer = "P", computer = "S")
    );
    print("Rock, paper, or scissors?");
    t = Str(input());
    if(#t,
      player=Vec(t)[1];
      if(player <> "R" && player <> "P", player = "S")
    ,
      player = "S"
    );
    if (player == "R", v[2]++);
    if (player == "P", v[3]++);
    if (player == "S", v[1]++);
    print1(player" vs. "computer": ");
    if (computer <> player,
      if((computer == "R" && player = "P") || (computer == "P" && player = "S") || (computer == "S" && player == "R"),
        print("You win");
        losses++
      ,
        print("I win");
        wins++
      )
    ,
      print("Tie");
    )
  );
  [wins,losses]
};
contest(10)


#!/usr/bin/env golosh
----
This module takes a decimal integer and converts it to a Roman numeral.
----
module Romannumeralsencode

augment java.lang.Integer {

  function digits = |this| {

    var remaining = this
    let digits = vector[]
    while remaining > 0 {
      digits: prepend(remaining % 10)
      remaining = remaining / 10
    }
    return digits
  }

  ----
  123: digitsWithPowers() will return [[1, 2], [2, 1], [3, 0]]
  ----
  function digitsWithPowers = |this| -> vector[
    [ this: digits(): get(i), (this: digits(): size() - 1) - i ] for (var i = 0, i < this: digits(): size(), i = i + 1)
  ]

  function encode = |this| {

    require(this > 0, "the integer must be positive!")

    let romanPattern = |digit, powerOf10| -> match {
      when digit == 1 then i
      when digit == 2 then i + i
      when digit == 3 then i + i + i
      when digit == 4 then i + v
      when digit == 5 then v
      when digit == 6 then v + i
      when digit == 7 then v + i + i
      when digit == 8 then v + i + i + i
      when digit == 9 then i + x
      otherwise ""
    } with {
      i, v, x = [
        [ "I", "V", "X" ],
        [ "X", "L", "C" ],
        [ "C", "D", "M" ],
        [ "M", "?", "?" ]
      ]: get(powerOf10)
    }

    return vector[ romanPattern(digit, power) foreach digit, power in this: digitsWithPowers() ]: join("")
  }
}

function main = |args| {
  println("1990 == MCMXC? " + (1990: encode() == "MCMXC"))
  println("2008 == MMVIII? " + (2008: encode() == "MMVIII"))
  println("1666 == MDCLXVI? " + (1666: encode() == "MDCLXVI"))
}


symbols = [ 1:'I', 4:'IV', 5:'V', 9:'IX', 10:'X', 40:'XL', 50:'L', 90:'XC', 100:'C', 400:'CD', 500:'D', 900:'CM', 1000:'M' ]

def roman(arabic) {
    def result = ""
    symbols.keySet().sort().reverse().each {
        while (arabic >= it) {
            arabic-=it
            result+=symbols[it]
        }
    }
    return result
}
assert roman(1) == 'I'
assert roman(2) == 'II'
assert roman(4) == 'IV'
assert roman(8) == 'VIII'
assert roman(16) == 'XVI'
assert roman(32) == 'XXXII'
assert roman(25) == 'XXV'
assert roman(64) == 'LXIV'
assert roman(128) == 'CXXVIII'
assert roman(256) == 'CCLVI'
assert roman(512) == 'DXII'
assert roman(954) == 'CMLIV'
assert roman(1024) == 'MXXIV'
assert roman(1666) == 'MDCLXVI'
assert roman(1990) == 'MCMXC'
assert roman(2008) == 'MMVIII'


use 5.012;
use warnings;
use utf8;
use open qw(:encoding(utf-8) :std);
use Getopt::Long;

package Game {
    use List::Util qw(shuffle first);

    my $turns        = 0;
    my %human_choice = ( rock => 0, paper => 0, scissors => 0, );
    my %comp_choice  = ( rock => 0, paper => 0, scissors => 0, );
    my %what_beats =
      ( rock => 'paper', paper => 'scissors', scissors => 'rock', );
    my $comp_wins  = 0;
    my $human_wins = 0;
    my $draws      = 0;

    sub save_human_choice {
        my $ch = lc pop;
        if ( exists $human_choice{ $ch } ) {
            ++$human_choice{ $ch };
        }
        else {
            die __PACKAGE__ . ":: wrong choice: '$ch'";
        }
    }

    sub get_comp_choice {
        my @keys = shuffle keys %human_choice;
        my $ch;
        my ( $prob, $rand ) = ( 0, rand );
        $ch = ( first { $rand <= ( $prob += ( $human_choice{ $_ } / $turns ) ) } @keys )
            if $turns > 0;
        $ch //= $keys[0];
        $ch = $what_beats{ $ch };
        ++$comp_choice{ $ch };
        return $ch;
    }

    sub make_turn {
        my ( $comp_ch, $human_ch ) = ( pop(), pop() );
        ++$turns;
        if ( $what_beats{ $human_ch } eq $comp_ch ) {
            ++$comp_wins;
            return 'I win!';
        }
        elsif ( $what_beats{ $comp_ch } eq $human_ch ) {
            ++$human_wins;
            return 'You win!';
        }
        else {
            ++$draws;
            return 'Draw!';
        }
    }

    sub get_final_report {
        my $report =
            "You chose:\n"
          . "  rock     = $human_choice{rock} times,\n"
          . "  paper    = $human_choice{paper} times,\n"
          . "  scissors = $human_choice{scissors} times,\n"
          . "I chose:\n"
          . "  rock     = $comp_choice{rock} times,\n"
          . "  paper    = $comp_choice{paper} times,\n"
          . "  scissors = $comp_choice{scissors} times,\n"
          . "Turns: $turns\n"
          . "I won: $comp_wins, you won: $human_wins, draws: $draws\n";
        return $report;
    }
}

sub main {
    GetOptions( 'quiet' => \my $quiet );
    greet() if !$quiet;
    while (1) {
        print_next_line() if !$quiet;
        my $input = get_input();
        last unless $input;
        if ( $input eq 'error' ) {
            print "I don't understand!\n" if !$quiet;
            redo;
        }
        my $comp_choice = Game::get_comp_choice();
        Game::save_human_choice($input);
        my $result = Game::make_turn( $input, $comp_choice );
        describe_turn_result( $input, $comp_choice, $result )
          if !$quiet;
    }
    print Game::get_final_report();
}

sub greet {
    print "Welcome to the Rock-Paper-Scissors game!\n"
      . "Choose 'rock', 'paper' or 'scissors'\n"
      . "Enter empty line or 'quit' to quit\n";
}

sub print_next_line {
    print 'Your choice: ';
}

sub get_input {
    my $input = <>;
    print "\n" and return if !$input;    # EOF
    chomp $input;
    return if !$input or $input =~ m/\A \s* q/xi;
    return
        ( $input =~ m/\A \s* r/xi ) ? 'rock'
      : ( $input =~ m/\A \s* p/xi ) ? 'paper'
      : ( $input =~ m/\A \s* s/xi ) ? 'scissors'
      :                               'error';
}

sub describe_turn_result {
    my ( $human_ch, $comp_ch, $result ) = @_;
    print "You chose \u$human_ch, I chose \u$comp_ch. $result\n";
}

main();


digit :: Char -> Char -> Char -> Integer -> String
digit x y z k =
  [[x], [x, x], [x, x, x], [x, y], [y], [y, x], [y, x, x], [y, x, x, x], [x, z]] !!
  (fromInteger k - 1)

toRoman :: Integer -> String
toRoman 0 = ""
toRoman x
  | x < 0 = error "Negative roman numeral"
toRoman x
  | x >= 1000 = 'M' : toRoman (x - 1000)
toRoman x
  | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r
  where
    (q, r) = x `divMod` 100
toRoman x
  | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r
  where
    (q, r) = x `divMod` 10
toRoman x = digit 'I' 'V' 'X' x

main :: IO ()
main = print $ toRoman <$> [1999, 25, 944]


--standard game
constant rule3 = {"rock blunts scissors",
                  "paper wraps rock",
                  "scissors cut paper"}
--extended version
constant rule5 = {"rock blunts scissors",
                  "rock crushes lizard",
                  "paper wraps rock",
                  "paper disproves spock",
                  "scissors cut paper",
                  "scissors decapitate lizard",
                  "lizard eats paper",
                  "lizard poisons spock",
                  "spock smashes scissors",
                  "spock vaporizes rock"}

constant rules = iff(rand(2)=1?rule3:rule5)

sequence what = {}
sequence beats = {}
string wkeys = ""
string question = "What is your move "
integer choices, hsum
sequence history, cplays, pplays

object x, verb, y

    for i=1 to length(rules) do
        {x} = split(rules[i])
        if not find(x,what) then
            what = append(what,x)
            if find(x[1],wkeys) then
                wkeys = append(wkeys,x[$])
                question &= x[1..-2]&"("&x[$]&"), "
            else
                wkeys = append(wkeys,x[1])
                question &= "("&x[1]&")"&x[2..$]&", "
            end if
        end if
    end for
    choices = length(wkeys)
    history = repeat(1,choices)
    hsum = 3
    cplays = repeat(0,choices)
    pplays = repeat(0,choices)
    beats = repeat(repeat(0,choices),choices)
    question[-2] = '?'
    for i=1 to length(rules) do
        {x,verb,y} = split(rules[i])
        beats[find(x,what)][find(y,what)] = verb
    end for

integer cmove, pmove, draws = 0, pwins = 0, cwins = 0
    while 1 do
        cmove = rand(hsum)
        for i=1 to choices do
            cmove -= history[i]
            if cmove<=0 then
                -- predicted user choice of i, find whatever beats it
                for j=1 to choices do
                    if string(beats[j][i]) then
                        cmove = j
                        exit
                    end if
                end for
                exit
            end if
        end for
        puts(1,question)
        while 1 do
            pmove = lower(wait_key())
            if pmove='q' then exit end if
            pmove = find(pmove,wkeys)
            if pmove!=0 then exit end if
        end while
        if pmove='q' then exit end if

        printf(1,"you: %s, me: %s, ",{what[pmove],what[cmove]})
        cplays[cmove] += 1
        pplays[pmove] += 1
        if cmove=pmove then
            printf(1,"a draw.\n")
            draws += 1
        else
            if string(beats[cmove][pmove]) then
                printf(1,"%s %s %s. I win.\n",{what[cmove],beats[cmove][pmove],what[pmove]})
                cwins += 1
            elsif string(beats[pmove][cmove]) then
                printf(1,"%s %s %s. You win.\n",{what[pmove],beats[pmove][cmove],what[cmove]})
                pwins += 1
            else
                ?9/0    -- sanity check
            end if
        end if
        history[pmove] += 1
        hsum += 1
    end while
    printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws})
    printf(1,"\n\nYour wins:%d, My wins:%d, Draws:%d\n",{pwins,cwins,draws})
    printf(1,"       ") for i=1 to choices do   printf(1,"%9s",what[i])     end for
    printf(1,"\nyou: ") for i=1 to choices do   printf(1,"%9d",pplays[i])   end for
    printf(1,"\n me: ") for i=1 to choices do   printf(1,"%9d",cplays[i])   end for


include ..\Utilitys.pmt

    0 var wh
    0 var wc

( "Scissors cuts Paper"
  "Paper covers Rock"
  "Rock crushes Lizard"
  "Lizard poisons Spock"
  "Spock smashes Scissors"
  "Scissors decapites Lizard"
  "Lizard eats Paper"
  "Paper disproves Spock"
  "Spock vaporizes Rock"
  "Rock blunts Scissors" )

  "'Rock, Paper, Scissors, Lizard, Spock!' rules are: " ? nl
  len for
    get ?
  endfor
  nl

  ( ( "S" "Scissors" ) ( "P" "Paper" ) ( "R" "Rock" ) ( "L" "Lizard" ) ( "K" "Spock" ) )

    true while
        "Choose (S)cissors, (P)paper, (R)ock, (L)izard, Spoc(K) or (Q)uit: " input nl upper
        dup "Q" == if
            nl drop false
        else
            getd if
                dup "You choose " print ? var he
                rand 5 * int 1 + 2 2 tolist sget
                dup "I choose " print ? var ce
                he ce == if
                    "Draw" ?
                else
                    swap len for
                        get dup
                        split 2 del
                        he ce 2 tolist
                        over over == rot rot reverse == or if exitfor else drop endif
                    endfor
                    dup ?
                    he find 1 == if wh 1 + var wh "You win!" else wc 1 + var wc "I win!" endif ? drop
                    swap
                endif
            else
                print " is a invalid input!" ?
            endif
            true
        endif
    endwhile
    drop drop
    "Your punctuation: " print wh ?
    "Mi punctuation: " print wc ?
    wh wc > if "You win!" else wh wc < if "I win!" else "Draw!" endif endif ?


<?php
echo "
" . "Choose: ROCK - PAPER - SCISSORS" . "
";
echo "
";
echo "";

$player = strtoupper( $_GET["moves"] );
$wins = [
    'ROCK' => 'SCISSORS',
    'PAPER' => 'ROCK',
    'SCISSORS' => 'PAPER'
  ];
$a_i = array_rand($wins);
echo "
";
echo "Player chooses " . "" . $player . "";
echo "
";
echo "
" . "A.I chooses " . ""  . $a_i . "";

$results = "";
if ($player == $a_i){
$results = "Draw";
} else if($wins[$a_i] == $player ){
  $results = "A.I wins";
} else {
  $results = "Player wins";
}

echo "
" . $results;
?>


CHARACTER Roman*20

CALL RomanNumeral(1990, Roman) ! MCMXC
CALL RomanNumeral(2008, Roman) ! MMVIII
CALL RomanNumeral(1666, Roman) ! MDCLXVI

END

SUBROUTINE RomanNumeral( arabic, roman)
  CHARACTER roman
  DIMENSION ddec(13)
  DATA      ddec/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1/

  roman = ' '
  todo = arabic
  DO d = 1, 13
    DO rep = 1, todo / ddec(d)
      roman = TRIM(roman) // TRIM(CHAR(d, 13, "M  CM D  CD C  XC L  XL X  OX V  IV I  "))
      todo = todo - ddec(d)
    ENDDO
  ENDDO
END


go ?=>
  println("\nEnd terms with '.'.\n'quit.' ends the session.\n"),
  Prev = findall(P,beats(P,_)),
  ChoiceMap = new_map([P=0 : P in Prev]),
  ResultMap = new_map([computer_wins=0,user_wins=0,draw=0]),
  play(Prev,ChoiceMap,ResultMap),
  nl,
  println("Summary:"),
  println(choiceMap=ChoiceMap),
  println(resultMap=ResultMap),
  nl.

go => true.

%
% Play an interactive game.
%
play(Prev,ChoiceMap,ResultMap) =>
  print("Your choice? "),
  P = read_term(),
  if P == quit then
    nl,
    print_result(ResultMap)
  else
    C = choice(ChoiceMap),
    printf("The computer chose %w%n", C),
    result(C,P,Prev,Next,Result),
    ChoiceMap.put(P,ChoiceMap.get(P)+1),
    ResultMap.put(Result,ResultMap.get(Result,0)+1),
    play(Next,ChoiceMap,ResultMap)
  end.

%
% Do a weighted random choice based on the user's previous choices.
%
weighted_choice(Map) = Choice =>
  Map2 = [(V+1)=K : K=V in Map].sort, % ensure that all choices can be made
  % Prepare the probability matrix M
  Total = sum([P : P=_ in Map2]),
  Len = Map2.len,
  M = new_array(Len,2),
  T = new_list(Len),
  foreach({I,P=C} in zip(1..Len,Map2))
    if I == 1 then
      M[I,1] := 1,
      M[I,2] := P
    else
      M[I,1] := M[I-1,2]+1,
      M[I,2] := M[I,1]+P-1
    end,
    T[I] := C
  end,
  M[Len,2] := Total,

  % Pick a random number in 1..Total
  R = random(1,Total),
  Choice = _,
  % Check were R match
  foreach(I in 1..Len, var(Choice))
    if M[I,1] <= R, M[I,2] >= R then
      Choice := T[I]
    end
  end.

%
% Check probably best counter choice.
%
choice(Map) = Choice =>
  % what is the Player's probably choice
  PlayersProbablyMove = weighted_choice(Map),
  % select the choice that beats it
  beats(Choice,PlayersProbablyMove).

print_result(ResultMap) =>
  foreach(C in ResultMap.keys)
    println(C=ResultMap.get(C))
  end,
  nl.

% This part is from the Prolog version.
result(C,P,R,[C|R],Result) :-
  beats(C,P),
  Result = computer_wins,
  printf("Computer wins.\n").
result(C,P,R,[B|R],Result) :-
  beats(P,C),
  beats(B,P),
  Result=user_wins,
  printf("You win!%n").
result(C,C,R,[B|R],Result) :-
  beats(B,C),
  Result=draw,
  printf("It is a draw\n").

beats(paper, rock).
beats(rock, scissors).
beats(scissors, paper).


(use (C Mine Your)
   (let (Rock 0  Paper 0  Scissors 0)
      (loop
         (setq Mine
            (let N (if (gt0 (+ Rock Paper Scissors)) (rand 1 @) 0)
               (seek
                  '((L) (le0 (dec 'N (caar L))))
                  '(Rock Paper Scissors .) ) ) )
         (prin "Enter R, P or S to play, or Q to quit: ")
         (loop
            (and (= "Q" (prinl (setq C (uppc (key))))) (bye))
            (T (setq Your (find '((S) (pre? C S)) '(Rock Paper Scissors))))
            (prinl "Bad input - try again") )
         (prinl
            "I say " (cadr Mine) ", You say " Your ": "
            (cond
               ((== Your (cadr Mine)) "Draw")
               ((== Your (car Mine)) "I win")
               (T "You win") ) )
         (inc Your) ) ) )


rock: procedure options (main);   /* 30 October 2013 */
   declare move character (1), cm fixed binary;

   put ('The Rock-Paper-Scissors game');
   put skip list ("please type 'r' for rock, 'p' for paper, 's' for scissors.");
   put skip list ("Anything else finishes:");
   do forever;
      get edit (move) (a(1));
      move = lowercase(move);
      if index('rpsq', move) = 0 then iterate;
      if move = 'q' then stop;
      cm = random()*3; /* computer moves: 0 = rock, 1 = paper, 2 = scissors */
      select (cm);
         when (0) select (move);
                     when ('r') put list ('rock and rock: A draw');
                     when ('p') put list ('paper beats rock: You win');
                     when ('s') put list ('rock breaks scissors: I win');
                  end;
         when (1) select (move);
                     when ('r') put list ('paper beats rock: I win');
                     when ('p') put list ('paper and paper: A draw');
                     when ('s') put list ('scissors cut paper: You win');
                  end;
         when (2) select (move);
                     when ('r') put list ('rock breaks scissors: You win');
                     when ('p') put list ('scissors cuts paper: I win');
                     when ('s') put list ('Scissors and Scissors: A draw');
                  end;
      end;
   end;
end rock;


link numbers   # commas, roman

procedure main(arglist)
every x := !arglist do
   write(commas(x), " -> ",roman(x)|"*** can't convert to Roman numerals ***")
end


       PLEASE WRITE IN .1
           DO READ OUT .1
           DO GIVE UP


play :-
  findall(P,beats(P,_),Prev),
  play(Prev).

play(Prev) :-
  write('your choice? '),
  read(P),
  random_member(C, Prev),
  format('The computer chose ~p~n', C),
  result(C,P,Prev,Next),
  !,
  play(Next).

result(C,P,R,[C|R]) :-
  beats(C,P),
  format('Computer wins.~n').
result(C,P,R,[B|R]) :-
  beats(P,C),
  beats(B,P),
  format('You win!~n').
result(C,C,R,[B|R]) :-
  beats(B,C),
  format('It is a draw~n').

beats(paper, rock).
beats(rock, scissors).
beats(scissors, paper).


Enumeration
  ;choices are in listed according to their cycle, weaker followed by stronger
  #rock
  #paper
  #scissors
  #numChoices ;this comes after all possible choices
EndEnumeration

;give names to each of the choices
Dim choices.s(#numChoices - 1)
choices(#rock) = "rock"
choices(#paper) = "paper"
choices(#scissors) = "scissors"

Define gameCount
Dim playerChoiceHistory(#numChoices - 1)

Procedure weightedRandomChoice()
  Shared gameCount, playerChoiceHistory()
  Protected x = Random(gameCount - 1), t, c

  For i = 0 To #numChoices - 1
    t + playerChoiceHistory(i)
    If t >= x
      c = i
      Break
    EndIf
  Next

  ProcedureReturn (c + 1) % #numChoices
EndProcedure

If OpenConsole()
  PrintN("Welcome to the game of rock-paper-scissors")
  PrintN("Each player guesses one of these three, and reveals it at the same time.")
  PrintN("Rock blunts scissors, which cut paper, which wraps stone.")
  PrintN("If both players choose the same, it is a draw!")
  PrintN("When you've had enough, choose Q.")

  Define computerChoice, playerChoice, response.s
  Define playerWins, computerWins, draw, quit

  computerChoice = Random(#numChoices - 1)
  Repeat
    Print(#CRLF$ + "What is your move (press R, P, or S)?")
    Repeat
      response = LCase(Input())
    Until FindString("rpsq", response) > 0

    If response = "q":
      quit = 1
    Else
      gameCount + 1
      playerChoice = FindString("rps", response) - 1

      result = (playerChoice - computerChoice + #numChoices) % #numChoices
      Print("You chose " + choices(playerChoice) + " and I chose " + choices(computerChoice))
      Select result
        Case 0
          PrintN(". It's a draw.")
          draw + 1
        Case 1
          PrintN(". You win!")
          playerWins + 1
        Case 2
          PrintN(". I win!")
          computerWins + 1
      EndSelect
      playerChoiceHistory(playerChoice) + 1
      computerChoice = weightedRandomChoice()
    EndIf
  Until quit

  Print(#CRLF$ + "You chose: ")
  For i = 0 To #numChoices - 1
    Print(choices(i) + " " + StrF(playerChoiceHistory(i) * 100 / gameCount, 1) + "%; ")
  Next
  PrintN("")
  PrintN("You won " + Str(playerWins) + ", and I won " + Str(computerWins) + ". There were " + Str(draw) + " draws.")
  PrintN("Thanks for playing!")

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
  CloseConsole()
EndIf


Roman := Object clone do (
    nums := list(1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
    rum := list("M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I")

    numeral := method(number,
        result := ""
        for(i, 0, nums size,
            if(number == 0, break)
            while(number >= nums at(i),
                number = number - nums at(i)
                result = result .. rum at(i)
            )
        )
        return result
    )
)

Roman numeral(1666) println


from random import choice

rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
previous = ['rock', 'paper', 'scissors']

while True:
    human = input('\nchoose your weapon: ')
    computer = rules[choice(previous)]  # choose the weapon which beats a randomly chosen weapon from "previous"

    if human in ('quit', 'exit'): break

    elif human in rules:
        previous.append(human)
        print('the computer played', computer, end='; ')

        if rules[computer] == human:  # if what beats the computer's choice is the human's choice...
            print('yay you win!')
        elif rules[human] == computer:  # if what beats the human's choice is the computer's choice...
            print('the computer beat you... :(')
        else: print("it's a tie!")

    else: print("that's not a valid choice")


play <- function()
{
  bias <- c(r = 1, p = 1, s = 1)
  repeat
  {
    playerChoice <- readline(prompt = "Rock (r), Paper (p), Scissors (s), or Quit (q)? ")
    if(playerChoice == "q") break
    rps <- c(Rock = "r", Paper = "p", Scissors = "s")
    if(!playerChoice %in% rps) next
    compChoice <- sample(rps, 1, prob = bias / sum(bias))
    cat("I choose", names(compChoice), "\n",
        c("We draw!", "I win!", "I lose!")[1 + (which(compChoice == rps) - which(playerChoice == rps)) %% 3], "\n")
    bias <- bias + (playerChoice == c("s", "r", "p"))
  }
}
play()


R1000=. ;L:1 ,{ <@(<;._1);._2]0 :0
  C CC CCC CD D DC DCC DCCC CM
  X XX XXX XL L LX LXX LXXX XC
  I II III IV V VI VII VIII IX
)

rfd=: ('M' $~ <[email protected]%&1000) , R1000 {::~ 1000&|


public class RN {

    enum Numeral {
        I(1), IV(4), V(5), IX(9), X(10), XL(40), L(50), XC(90), C(100), CD(400), D(500), CM(900), M(1000);
        int weight;

        Numeral(int weight) {
            this.weight = weight;
        }
    };

    public static String roman(long n) {

        if( n <= 0) {
            throw new IllegalArgumentException();
        }

        StringBuilder buf = new StringBuilder();

        final Numeral[] values = Numeral.values();
        for (int i = values.length - 1; i >= 0; i--) {
            while (n >= values[i].weight) {
                buf.append(values[i]);
                n -= values[i].weight;
            }
        }
        return buf.toString();
    }

    public static void test(long n) {
        System.out.println(n + " = " + roman(n));
    }

    public static void main(String[] args) {
        test(1999);
        test(25);
        test(944);
        test(0);
    }

}


#lang racket
(require math)

(define history (make-hash '((paper . 1) (scissors . 1) (rock . 1))))
(define total 3)

(define (update-history! human-choice)
  (set! total (+ total 1))
  (hash-update! history human-choice add1 0))

(define (pick-one)
  (sample
   (discrete-dist '(paper scissors rock)
                  (map (λ (x) (hash-ref history x))
                       '(scissors paper rock)))))

(define (find-winner computer human)
  (define order '(scissors paper rock scissors))
  (cond
    [(eq? computer human)                         'none]
    [(eq? (second (member computer order)) human) 'computer]
    [                                             'human]))

(define (game-loop)
  (define computer-choice (pick-one))
  (define human-choice (read))
  (define winner (find-winner computer-choice human-choice))
  (update-history! human-choice)
  (displayln (~a "Computer picked " computer-choice ", "
                 "human picked " human-choice ", "
                 winner " wins."))
  (game-loop))

(game-loop)


my %vs = (
    options => [<Rock Paper Scissors>],
    ro => {
        ro => [ 2, ''                        ],
        pa => [ 1, 'Paper covers Rock: '     ],
        sc => [ 0, 'Rock smashes Scissors: ' ]
    },
    pa => {
        ro => [ 0, 'Paper covers Rock: '    ],
        pa => [ 2, ''                       ],
        sc => [ 1, 'Scissors cut Paper: '   ]
    },
    sc => {
        ro => [ 1, 'Rock smashes Scissors: '],
        pa => [ 0, 'Scissors cut Paper: '   ],
        sc => [ 2, ''                       ]
    }
);

my %choices = %vs<options>.map({; $_.substr(0,2).lc => $_ });
my $keys    = %choices.keys.join('|');
my $prompt  = %vs<options>.map({$_.subst(/(\w\w)/, -> $/ {"[$0]"})}).join(' ')~"? ";
my %weight  = %choices.keys »=>» 1;

my @stats = 0,0,0;
my $round;

while my $player = (prompt "Round {++$round}: " ~ $prompt).lc {
    $player.=substr(0,2);
    say 'Invalid choice, try again.' and $round-- and next
      unless $player.chars == 2 and $player ~~ /<$keys>/;
    my $computer = (flat %weight.keys.map( { $_ xx %weight{$_} } )).pick;
    %weight{$_.key}++ for %vs{$player}.grep( { $_.value[0] == 1 } );
    my $result = %vs{$player}{$computer}[0];
    @stats[$result]++;
    say "You chose %choices{$player},  Computer chose %choices{$computer}.";
    print %vs{$player}{$computer}[1];
    print ( 'You win!', 'You Lose!','Tie.' )[$result];
    say " - (W:{@stats[0]} L:{@stats[1]} T:{@stats[2]})\n",
};


var roman = {
    map: [
        1000, 'M', 900, 'CM', 500, 'D', 400, 'CD', 100, 'C', 90, 'XC',
        50, 'L', 40, 'XL', 10, 'X', 9, 'IX', 5, 'V', 4, 'IV', 1, 'I',
    ],
    int_to_roman: function(n) {
        var value = '';
        for (var idx = 0; n > 0 && idx < this.map.length; idx += 2) {
            while (n >= this.map[idx]) {
                value += this.map[idx + 1];
                n -= this.map[idx];
            }
        }
        return value;
    }
}

roman.int_to_roman(1999); // "MCMXCIX"


import Prelude;

rel[str, str] whatbeats = {<"Rock", "Scissors">, <"Scissors", "Paper">, <"Paper", "Rock">};

list[str] ComputerChoices = ["Rock", "Paper", "Scissors"];

str CheckWinner(a, b){
	if(b == getOneFrom(whatbeats[a]))
		return a;
	elseif(a == getOneFrom(whatbeats[b]))
		return b;
	else return "Nobody";
}

public str RPS(human){
	computer = getOneFrom(ComputerChoices);
	x = if(human == "Rock") "Paper"; elseif(human == "Paper") "Scissors"; else "Rock";
	ComputerChoices += x;
	return "Computer played <computer>. <CheckWinner(human, computer)> wins!";
}


Red [Purpose: "Implement a rock-paper-scissors game with weighted probability"]

prior: rejoin choices: ["r" "p" "s"]

while [
	find choices pchoice: ask "choose rock: r, paper: p, or scissors: s^/"
] [
	print ["AI Draws:" cchoice: random/only prior]
	cwin: select "rpsr" pchoice
	close: select "rspr" pchoice

	print case [
		pchoice = cchoice ["tie"]
		cchoice = cwin ["you lose"]
		'else ["you win"]
	]

	append prior cwin		;adds what would have beaten player
	remove find prior close		;removes what would have lost to player
]


/* Roman numerals, in Jsish */
var Roman = {
    ord: ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'],
    val: [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],

    fromRoman: function(roman:string):number {
        var n = 0;
        var re = /IV|IX|I|V|XC|XL|X|L|CD|CM|C|D|M/g;
        var matches = roman.match(re);
        if (!matches) return NaN;
        for (var hit of matches) n += this.val[this.ord.indexOf(hit)];
        return n;
    },

    toRoman: function(n:number):string {
        var roman = '';
        var idx = 0;
        while (n > 0) {
            while (n >= this.val[idx]) {
                roman += this.ord[idx];
                n -= this.val[idx];
            }
            idx++;
        }
        return roman;
    }
};

provide('Roman', 1);

if (Interp.conf('unitTest')) {
;    Roman.fromRoman('VIII');
;    Roman.fromRoman('MMMDIV');
;    Roman.fromRoman('CDIV');
;    Roman.fromRoman('MDCLXVI');
;    Roman.fromRoman('not');

;    Roman.toRoman(8);
;    Roman.toRoman(3504);
;    Roman.toRoman(404);
;    Roman.toRoman(1666);
}

/*
=!EXPECTSTART!=
Roman.fromRoman('VIII') ==> 8
Roman.fromRoman('MMMDIV') ==> 3504
Roman.fromRoman('CDIV') ==> 404
Roman.fromRoman('MDCLXVI') ==> 1666
Roman.fromRoman('not') ==> NaN
Roman.toRoman(8) ==> VIII
Roman.toRoman(3504) ==> MMMDIV
Roman.toRoman(404) ==> CDIV
Roman.toRoman(1666) ==> MDCLXVI
=!EXPECTEND!=
*/


/*REXX program plays rock─paper─scissors with a human;  tracks what human tends to use. */
!= '────────';  err=! "***error***";    @.=0     /*some constants for this program.     */
prompt= ! 'Please enter one of:     Rock   Paper   Scissors      (or Quit)'
$.p= 'paper' ;  $.s= "scissors";   $.r= 'rock'   /*list of the choices in this program. */
t.p= $.r     ;  t.s= $.p       ;   t.r= $.s      /*thingys that beats  stuff.           */
w.p= $.s     ;  w.s= $.r       ;   w.r= $.p      /*stuff     "    "   thingys.          */
b.p= 'covers';  b.s= "cuts"    ;   b.r= 'breaks' /*verbs:   how the choice wins.        */

  do forever;     say;      say prompt;     say  /*prompt the CBLF; then get a response.*/
  c= word($.p $.s $.r,      random(1, 3) )       /*choose the computer's first pick.    */
  m= max(@.r, @.p, @.s);    c= w.r               /*prepare to examine the choice history*/
  if @.p==m  then c= w.p                         /*emulate JC's:  The Amazing Karnac.   */
  if @.s==m  then c= w.s                         /*   "     "      "     "       "      */
  c1= left(c, 1)                                 /*C1  is used for faster comparing.    */
  parse pull u;             a= strip(u)          /*get the CBLF's choice/pick (answer). */
  upper a c1  ;            a1= left(a, 1)        /*uppercase choices, get 1st character.*/
  ok= 0                                          /*indicate answer isn't OK  (so far).  */
       select                                    /*process/verify the  CBLF's  choice.  */
       when words(u)==0           then           say  err   'nothing entered'
       when words(u)>1            then say  err   'too many choices: '  u
       when abbrev('QUIT',    a)  then do;  say ! "quitting.";      exit;    end
       when abbrev('ROCK',    a) |,
            abbrev('PAPER',   a) |,
            abbrev('SCISSORS',a)  then ok=1      /*Yes?  This is a valid answer by CBLF.*/
       otherwise                  say err  'you entered a bad choice: '    u
       end   /*select*/

  if \ok          then iterate                   /*answer ¬OK?  Then get another choice.*/
  @.a1= @.a1 + 1                                 /*keep a history of the CBLF's choices.*/
  say !  'computer chose: '    c
  if   a1==  c1  then do;  say !  'draw.';   iterate;  end
  if $.a1==t.c1  then say  !  'the computer wins. '    !  $.c1  b.c1  $.a1
                 else say  !  'you win! '              !  $.a1  b.a1  $.c1
  end   /*forever*/                              /*stick a fork in it,  we're all done. */


using Printf

function romanencode(n::Integer)
    if n < 1 || n > 4999 throw(DomainError()) end

    DR = [["I", "X", "C", "M"] ["V", "L", "D", "MMM"]]
    rnum = ""
    for (omag, d) in enumerate(digits(n))
        if d == 0
            omr = ""
        elseif d <  4
            omr = DR[omag, 1] ^ d
        elseif d == 4
            omr = DR[omag, 1] * DR[omag, 2]
        elseif d == 5
            omr = DR[omag, 2]
        elseif d <  9
            omr = DR[omag, 2] * DR[omag, 1] ^ (d - 5)
        else
            omr = DR[omag, 1] * DR[omag + 1, 1]
        end
        rnum = omr * rnum
    end
    return rnum
end

testcases = [1990, 2008, 1668]
append!(testcases, rand(1:4999, 12))
testcases = unique(testcases)

println("Test romanencode, arabic => roman:")
for n in testcases
    @printf("%-4i => %s\n", n, romanencode(n))
end


val romanNumerals = mapOf(
    1000 to "M",
    900 to "CM",
    500 to "D",
    400 to "CD",
    100 to "C",
    90 to "XC",
    50 to "L",
    40 to "XL",
    10 to "X",
    9 to "IX",
    5 to "V",
    4 to "IV",
    1 to "I"
)

fun encode(number: Int): String? {
    if (number > 5000 || number < 1) {
        return null
    }
    var num = number
    var result = ""
    for ((multiple, numeral) in romanNumerals.entries) {
        while (num >= multiple) {
            num -= multiple
            result += numeral
        }
    }
    return result
}

fun main(args: Array<String>) {
    println(encode(1990))
    println(encode(1666))
    println(encode(2008))
}


# Project : Rock-paper-scissors

load "stdlib.ring"
load "guilib.ring"

width 		= 200
height 		= 200

myChose 	= 1
compChose 	= 1
nextPlayer 	= 1
myScore 	= 0
compScore 	= 0
C_FONTSIZE 	= 15

C_ROCK 		= "images/rock.jpg"
C_PAPER 	= "images/paper.jpg"
C_SCISSORS 	= "images/scissors.jpg"

ChoseList 	= [C_ROCK,C_PAPER,C_SCISSORS]

Button 		= list(len(ChoseList))

app = new QApp
{

	StyleFusion()

	win = new QWidget() {

		setWindowTitle('Stone Paper Scissors Game')
		setWinIcon(self,C_ROCK)
		setStyleSheet("background-color:cyan;")
		setWindowFlags(Qt_Window | Qt_WindowTitleHint | Qt_WindowCloseButtonHint | Qt_CustomizeWindowHint)
		reSize(900,600)
		winheight 	= height()
		fontSize	= 8 + (winheight / 100)

		for Col = 1 to len(ChoseList)
			Button[Col] = new QPushButton(win) {
				x = 150+(Col-1)*height
				setgeometry(x,35,width,height)
				setStyleSheet("background-color:white;")
				seticon(new qicon(new qpixmap(ChoseList[Col])))
				setIconSize(new qSize(200,200))
				setclickevent("ButtonPress(" + string(Col) + ")")
				setSizePolicy(1,1)
			}
		next

		labelMyChose = new QLabel(win) {
			setgeometry(200,250,150,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("My Chose:")
		}

		labelCompChose = new QLabel(win) {
			setgeometry(580,250,150,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("Comp Chose:")
		}

		labelScoreEnd = new QLabel(win) {
			setgeometry(0,510,win.width(),30)
			setAlignment(Qt_AlignHCenter | Qt_AlignVCenter)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("")
		}

		btnMyChose = new QPushButton(win) {
			setgeometry(150,300,width,height)
			setStyleSheet("background-color:white;")
		}

		btnCompChose = new QPushButton(win) {
			setgeometry(550,300,width,height)
			setStyleSheet("background-color:white;")
		}

		btnNewGame = new QPushButton(win) {
			setgeometry(170,550,150,40)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			setclickevent("NewGame()")
			settext("New Game")
		}

		btnExit = new QPushButton(win) {
			setgeometry(580,550,150,40)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			setclickevent("Close()")
			settext("Exit")
		}

		labelMyScore = new QLabel(win) {
			setgeometry(170,0,100,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("My Score: ")
		}

		labelMyScoreSum = new QLabel(win) {
			setgeometry(300,0,100,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("")
		}

		labelCompScore = new QLabel(win) {
			setgeometry(580,0,130,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("Comp Score: ")
		}

		labelCompScoreSum = new QLabel(win) {
			setgeometry(730,0,100,30)
			setFont(new qFont("Verdana",C_FONTSIZE,50,0))
			settext("")
		}

		show()

	}

	exec()

}

func ButtonPress Col

	if nextPlayer = 1
		myChose = Col
		btnMyChose {
			seticon(new qicon(new qpixmap(ChoseList[Col])))
			setIconSize(new qSize(width,height))
		}
		nextPlayer = 2
		compChose()
	ok

func compChose

	rndChose = random(len(ChoseList)-1) + 1
	compChose = rndChose
	btnCompChose {
		seticon(new qicon(new qpixmap(ChoseList[compChose])))
		setIconSize(new qSize(width,height))
	}
	nextPlayer = 1
	Result()

func Result

	if (myChose = compChose)
		labelScoreEnd.settext("Draw!")
	ok
	if (myChose = 1) and (compChose = 2)
		labelScoreEnd.settext("Computer Win!")
		compScore = compScore + 1
		labelCompScoreSum.settext(string(compScore))
	ok
	if (myChose = 1) and (compChose = 3)
		labelScoreEnd.settext("I Win!")
		myScore = myScore + 1
		labelMyScoreSum.settext(string(myScore))
	ok
	if (myChose = 2) and (compChose = 3)
		labelScoreEnd.settext("Computer Win!")
		compScore = compScore + 1
		labelCompScoreSum.settext(string(compScore))
	ok
	if (myChose = 2) and (compChose = 1)
		labelScoreEnd.settext("I Win!")
		myScore = myScore + 1
		labelMyScoreSum.settext(string(myScore))
	ok
	if (myChose = 3) and (compChose = 1)
		labelScoreEnd.settext("Computer Win!")
		compScore = compScore + 1
		labelCompScoreSum.settext(string(compScore))
	ok
	if (myChose = 3) and (compChose = 2)
		labelScoreEnd.settext("I Win!")
		myScore = myScore + 1
		labelMyScoreSum.settext(string(myScore))
	ok

func NewGame

	nextPlayer 	= 1
	myScore 	= 0
	compScore 	= 0

	btnMyChose {
		seticon(new qicon(new qpixmap("")))
		setIconSize(new qSize(200,200))
	}

	btnCompChose {
		seticon(new qicon(new qpixmap("")))
		setIconSize(new qSize(200,200))
	}

	labelScoreEnd.settext("")
	labelMyScoreSum.settext("0")
	labelCompScoreSum.settext("0")

func Close

	win.close()
	app.quit()


class RockPaperScissorsGame
  CHOICES = %w[rock paper scissors quit]
  BEATS = {
    'rock'     => 'paper',
    'paper'    => 'scissors',
    'scissors' => 'rock',
  }

  def initialize()
    @plays = {
      'rock'     => 1,
      'paper'    => 1,
      'scissors' => 1,
    }
    @score = [0, 0, 0]          # [0]:Human wins, [1]:Computer wins, [2]:draw

    play
  end

  def humanPlay
    loop do
      print "\nYour choice: #{CHOICES}? "
      answer = STDIN.gets.strip.downcase
      next if answer.empty?
      idx = CHOICES.find_index {|choice| choice.match(/^#{answer}/)}
      return CHOICES[idx] if idx
      puts "invalid answer, try again"
    end
  end

  def computerPlay
    total = @plays.values.reduce(:+)
    r = rand(total) + 1
    sum = 0
    CHOICES.each do |choice|
      sum += @plays[choice]
      return BEATS[choice] if r <= sum
    end
  end

  def play
    loop do
      h = humanPlay
      break if h == "quit"
      c = computerPlay
      print "H: #{h}, C: #{c} => "

      # only update the human player's history after the computer has chosen
      @plays[h] += 1

      if h == c
        puts "draw"
        @score[2] += 1
      elsif h == BEATS[c]
        puts "Human wins"
        @score[0] += 1
      else
        puts "Computer wins"
        @score[1] += 1
      end
      puts "score: human=%d, computer=%d, draw=%d" % [*@score]
    end
    @plays.each_key{|k| @plays[k] -= 1}
    puts "\nhumans chose #{@plays}"
  end
end

RockPaperScissorsGame.new


define br => '\r'
// encode roman
define encodeRoman(num::integer)::string => {
	local(ref = array('M'=1000, 'CM'=900, 'D'=500, 'CD'=400, 'C'=100, 'XC'=90, 'L'=50, 'XL'=40, 'X'=10, 'IX'=9, 'V'=5, 'IV'=4, 'I'=1))
	local(out = string)
	with i in #ref do => {
		while(#num >= #i->second) => {
			#out->append(#i->first)
			#num -= #i->second
		}
	}
	return #out
}

'1990 in roman is '+encodeRoman(1990)
br
'2008 in roman is '+encodeRoman(2008)
br
'1666 in roman is '+encodeRoman(1666)


\documentclass{minimal}
\newcounter{currentyear}
\setcounter{currentyear}{\year}
\begin{document}
Anno Domini \Roman{currentyear}
\end{document}


pri$ = "RSPR"
rps$ = "Rock,Paper,Sissors"
[loop]
button #r, "Rock",    [r]
button #p, "Paper",   [p]
button #s, "Scissors",[s]
button #q, "Quit",    [q]
wait
[r] y = 1 :goto [me]
[p] y = 2 :goto [me]
[s] y = 3
[me]
cls
y$ = word$(rps$,y,",")
m  = int((rnd(0) * 2) + 1)
m$ = word$(rps$,m,",")
print chr$(10);"You Chose:";y$;" I chose:";m$
yp = instr(pri$,left$(y$,1))
mp = instr(pri$,left$(m$,1))
if yp = 1 and mp = 3 then mp = 0
if mp = 1 and yp = 3 then yp = 0
if yp < mp then print "You win"
if yp = mp then print "Tie"
if yp > mp then print "I win"
goto [loop]
wait

[q] cls
print "Good Bye! I enjoyed the game"
end


extern crate rand;
#[macro_use]
extern crate rand_derive;

use std::io;
use rand::Rng;
use Choice::*;

#[derive(PartialEq, Clone, Copy, Rand, Debug)]
enum Choice {
    Rock,
    Paper,
    Scissors,
}

fn beats(c1: Choice, c2: Choice) -> bool {
    (c1 == Rock && c2 == Scissors) || (c1 == Scissors && c2 == Paper) || (c1 == Paper && c2 == Rock)
}

fn ai_move<R: Rng>(rng: &mut R, v: [usize; 3]) -> Choice {
    // weighted random choice, a dynamic version of `rand::distributions::WeightedChoice`
    let rand = rng.gen_range(0, v[0] + v[1] + v[2]);
    if rand < v[0] {
        Paper
    } else if rand < v[0] + v[1] {
        Scissors
    } else {
        Rock
    }
}

fn main() {
    let mut rng = rand::thread_rng();

    println!("Rock, paper, scissors!");
    let mut ai_choice: Choice = rng.gen();
    let mut ucf = [0, 0, 0]; // user choice frequency
    let mut score = [0, 0];

    loop {
        println!("Please input your move: 'r', 'p' or 's'. Type 'q' to quit");

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .expect("failed to read line");
        let u_choice = match input.to_lowercase().trim() {
            s if s.starts_with('r') => {
                ucf[0] += 1;
                Rock
            }
            s if s.starts_with('p') => {
                ucf[1] += 1;
                Paper
            }
            s if s.starts_with('s') => {
                ucf[2] += 1;
                Scissors
            }
            s if s.starts_with('q') => break,
            _ => {
                println!("Please enter a correct choice!");
                continue;
            }
        };
        println!("You chose {:?}, I chose {:?}.", u_choice, ai_choice);
        if beats(u_choice, ai_choice) {
            score[0] += 1;
            println!("You win!");
        } else if u_choice == ai_choice {
            println!("It's a tie!");
        } else {
            score[1] += 1;
            println!("I win!");
        }
        println!("-Score: You {}, Me {}", score[0], score[1]);

        // only after the 1st iteration the AI knows the stats and can make
        // its weighted random move
        ai_choice = ai_move(&mut rng, ucf);
    }
    println!("Thank you for the game!");
}


object RockPaperScissors extends App {
  import scala.collection.mutable.LinkedHashMap
  def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) {
    val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match {
      case null => println; return
      case "" => return
      case s => Symbol(s)
    }
    beats get h match {
      case Some(losers) =>
        def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match {
          case (s, i) if rand <= (accum + i) => s
          case (_, i) => weighted(todo, rand, accum + i)
        }
        val c = weighted(played.toIterator, 1 + scala.util.Random.nextInt(played.values.sum)) match {
          // choose an opponent that would beat the player's anticipated move
          case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1
        }
        print(s"  My move: $c\n  ")
        c match {
          case c if losers contains c => println("You won")
          case c if beats(c) contains h => println("You lost")
          case _ => println("We drew") // or underspecified
        }
      case x => println("  Unknown weapon, try again.")
    }
    play(beats, played get h match {
      case None => played
      case Some(count) => played.updated(h, count + 1)
    })
  }

  def play(beats: LinkedHashMap[Symbol,Set[Symbol]]): Unit =
      play(beats, beats.mapValues(_ => 1)) // init with uniform probabilities

  play(LinkedHashMap(
    'rock -> Set('lizard, 'scissors),
    'paper -> Set('rock, 'spock),
    'scissors -> Set('paper, 'lizard),
    'lizard -> Set('spock, 'paper),
    'spock -> Set('scissors, 'rock)
  ))
}


    dim arabic( 12)
    for i =0 to 12
        read k
        arabic( i) =k
    next i
    data 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1

    dim roman$( 12)
    for i =0 to 12
        read k$
        roman$( i) =k$
    next i
    data "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"

    print 2009, toRoman$( 2009)
    print 1666, toRoman$( 1666)
    print 3888, toRoman$( 3888)

    end

function toRoman$( value)
    i       =0
    result$ =""
    for i = 0 to 12
        while value >=arabic( i)
            result$ = result$ + roman$( i)
            value   = value   - arabic( i)
        wend
    next i
    toRoman$ =result$
end function


$ include "seed7_05.s7i";
$ include "keybd.s7i";

const array string: rockPaperScissors is [] ("Rock", "Paper", "Scissors");

const proc: main is func
  local
    var char: command is ' ';
    var integer: user is 0;
    var integer: comp is 0;
  begin
    writeln("Hello, Welcome to rock-paper-scissors");
    repeat
      write("Please type in 1 for Rock, 2 for Paper, 3 for Scissors, q to quit ");
      flush(OUT);
      repeat
        command := lower(getc(KEYBOARD));
      until command in {'1', '2', '3', 'q'};
      writeln(command);
      if command <> 'q' then
        user := integer parse str(command);
        comp := rand(1, 3);
        writeln("You Played: " <& rockPaperScissors[user]);
        writeln("Computer Played: " <& rockPaperScissors[comp]);
        if comp = user then
          writeln("You Tied");
        elsif succ(comp) = user or user + 2 = comp then
          writeln("Yay, You Won!");
        else
          writeln("Sorry, You Lost!");
        end if;
      end if;
    until command = 'q';
    writeln("Goodbye! Thanks for playing!");
  end func;


const rps = %w(r p s)

const msg = [
    "Rock breaks scissors",
    "Paper covers rock",
    "Scissors cut paper",
]

say <<"EOT"
\n>> Rock Paper Scissors <<\n
** Enter 'r', 'p', or 's' as your play.
** Enter 'q' to exit the game.
** Running score shown as <your wins>:<my wins>
EOT

var plays   = 0
var aScore  = 0
var pScore  = 0
var pcf     = [0,0,0]      # pcf = player choice frequency
var aChoice = pick(0..2)   # ai choice for first play is completely random

loop {
    var pi = Sys.scanln("Play: ")
    pi == 'q' && break

    var pChoice = rps.index(pi)

    if (pChoice == -1) {
        STDERR.print("Invalid input!\n")
        next
    }

    ++pcf[pChoice]
    ++plays

    # show result of play
    ">> My play: %-8s".printf(rps[aChoice])

    given ((aChoice - pChoice + 3) % 3) {
        when (0) { say "Tie." }
        when (1) { "%-*s %s".printlnf(30, msg[aChoice], 'My point');   aScore++ }
        when (2) { "%-*s %s".printlnf(30, msg[pChoice], 'Your point'); pScore++ }
    }

    # show score
    "%-6s".printf("%d:%d" % (pScore, aScore))

    # compute ai choice for next play
    given (plays.rand.int) { |rn|
        case (rn < pcf[0])        { aChoice = 1 }
        case (pcf[0]+pcf[1] > rn) { aChoice = 2 }
        default                   { aChoice = 0 }
    }
}


function toRoman intNum
    local roman,numArabic
    put "M,CM,D,CD,C,XC,L,XL,X,IX,V,IV,I" into romans
    put "1000,900,500,400,100,90,50,40,10,9,5,4,1" into arabics
    put intNum into numArabic
    repeat with n = 1 to the number of items of romans
        put numArabic div item n of arabics into nums
        if nums > 0 then
            put repeatChar(item n of romans,nums) after roman
            add -(nums * item n of arabics) to numArabic
        end if
    end repeat
return roman
end toRoman

function repeatChar c n
    local cc
    repeat n times
        put c after cc
    end repeat
    return cc
end repeatChar


// play it in the REPL, evaluating line by line

a = RockPaperScissors.new;
a.next(Scissors);
a.next(Scissors);
a.next(Scissors);
a.next(Paper);


enum Choice: CaseIterable {
  case rock
  case paper
  case scissors
  case lizard
  case spock
}

extension Choice {
  var weaknesses: Set<Choice> {
    switch self {
      case .rock:
        return [.paper, .spock]
      case .paper:
        return [.scissors, .lizard]
      case .scissors:
        return [.rock, .spock]
      case .lizard:
        return [.rock, .scissors]
      case .spock:
        return [.paper, .lizard]
    }
  }
}

struct Game {
  private(set) var history: [(Choice, Choice)] = []
  private(set) var p1Score: Int = 0
  private(set) var p2Score: Int = 0

  mutating func play(_ p1Choice: Choice, against p2Choice: Choice) {
    history.append((p1Choice, p2Choice))
    if p2Choice.weaknesses.contains(p1Choice) {
      p1Score += 1
    } else if p1Choice.weaknesses.contains(p2Choice) {
      p2Score += 1
    }
  }
}

func aiChoice(for game: Game) -> Choice {
  if let weightedWeekness = game.history.flatMap({ $0.0.weaknesses }).randomElement() {
    return weightedWeekness
  } else {
    // If history is empty, return random Choice
    return Choice.allCases.randomElement()!
  }
}

var game = Game()
print("Type your choice to play a round, or 'q' to quit")
loop: while true {
  let choice: Choice
  switch readLine().map({ $0.lowercased() }) {
    case "r", "rock":
      choice = .rock
    case "p", "paper":
      choice = .paper
    case "scissors":
      choice = .scissors
    case "l", "lizard":
      choice = .lizard
    case "spock":
      choice = .spock
    case "q", "quit", "exit":
      break loop
    case "s":
      print("Do you mean Spock, or scissors?")
      continue
    default:
      print("Unknown choice. Type 'q' to quit")
      continue
  }
  let p2Choice = aiChoice(for: game)
  print("You played \(choice) against \(p2Choice)")
  game.play(choice, against: p2Choice)
  print("Current score: \(game.p1Score) : \(game.p2Score)")
}


package require Tcl 8.5

### Choices are represented by integers, which are indices into this list:
###    Rock, Paper, Scissors
### Normally, idiomatic Tcl code uses names for these sorts of things, but it
### turns out that using integers simplifies the move-comparison logic.

# How to ask for a move from the human player
proc getHumanMove {} {
    while 1 {
	puts -nonewline "Your move? \[R\]ock, \[P\]aper, \[S\]cissors: "
	flush stdout
	gets stdin line
	if {[eof stdin]} {
	    puts "\nBye!"
	    exit
	}
	set len [string length $line]
	foreach play {0 1 2} name {"rock" "paper" "scissors"} {
	    # Do a prefix comparison
	    if {$len && [string equal -nocase -length $len $line $name]} {
		return $play
	    }
	}
	puts "Sorry, I don't understand that. Try again please."
    }
}

# How to ask for a move from the machine player
proc getMachineMove {} {
    global states
    set choice [expr {int(rand() * [::tcl::mathop::+ {*}$states 3])}]
    foreach play {1 2 0} count $states {
	if {[incr sum [expr {$count+1}]] > $choice} {
	    puts "I play \"[lindex {Rock Paper Scissors} $play]\""
	    return $play
	}
    }
}

# Initialize some state variables
set states {0 0 0}
set humanWins 0
set machineWins 0

# The main game loop
while 1 {
    # Get the moves for this round
    set machineMove [getMachineMove]
    set humanMove [getHumanMove]
    # Report on what happened
    if {$humanMove == $machineMove} {
	puts "A draw!"
    } elseif {($humanMove+1)%3 == $machineMove} {
	puts "I win!"
	incr machineWins
    } else {
	puts "You win!"
	incr humanWins
    }
    puts "Cumulative scores: $humanWins to you, $machineWins to me"
    # Update the state of how the human has played in the past
    lset states $humanMove [expr {[lindex $states $humanMove] + 1}]
}


make "roman.rules [
  [1000 M] [900 CM] [500 D] [400 CD]
  [ 100 C] [ 90 XC] [ 50 L] [ 40 XL]
  [  10 X] [  9 IX] [  5 V] [  4 IV]
  [   1 I]
]

to roman :n [:rules :roman.rules] [:acc "||]
  if empty? :rules [output :acc]
  if :n < first first :rules [output (roman :n bf :rules :acc)]
  output (roman :n - first first :rules  :rules  word :acc last first :rules)
end


HAI 1.2
I HAS A Romunz ITZ A BUKKIT
Romunz HAS A SRS  0 ITZ "M"
Romunz HAS A SRS  1 ITZ "CM"
Romunz HAS A SRS  2 ITZ "D"
Romunz HAS A SRS  3 ITZ "CD"
Romunz HAS A SRS  4 ITZ "C"
Romunz HAS A SRS  5 ITZ "XC"
Romunz HAS A SRS  6 ITZ "L"
Romunz HAS A SRS  7 ITZ "XL"
Romunz HAS A SRS  8 ITZ "X"
Romunz HAS A SRS  9 ITZ "IX"
Romunz HAS A SRS 10 ITZ "V"
Romunz HAS A SRS 11 ITZ "IV"
Romunz HAS A SRS 12 ITZ "I"

I HAS A Valuez ITZ A BUKKIT
Valuez HAS A SRS  0 ITZ 1000
Valuez HAS A SRS  1 ITZ  900
Valuez HAS A SRS  2 ITZ  500
Valuez HAS A SRS  3 ITZ  400
Valuez HAS A SRS  4 ITZ  100
Valuez HAS A SRS  5 ITZ   90
Valuez HAS A SRS  6 ITZ   50
Valuez HAS A SRS  7 ITZ   40
Valuez HAS A SRS  8 ITZ   10
Valuez HAS A SRS  9 ITZ    9
Valuez HAS A SRS 10 ITZ    5
Valuez HAS A SRS 11 ITZ    4
Valuez HAS A SRS 12 ITZ    1

HOW IZ I Romunize YR Num
  I HAS A Result ITZ ""
  IM IN YR Outer UPPIN YR Dummy TIL BOTH SAEM Num AN 0
     IM IN YR Inner UPPIN YR Index TIL BOTH SAEM Index AN 13
       BOTH SAEM Num AN BIGGR OF Num AN Valuez'Z SRS Index, O RLY?
         YA RLY
            Num R DIFF OF Num AN Valuez'Z SRS Index
            Result R SMOOSH Result Romunz'Z SRS Index MKAY
            GTFO
        OIC
      IM OUTTA YR Inner
    IM OUTTA YR Outer
    FOUND YR Result
IF U SAY SO

VISIBLE SMOOSH 2009 " = " I IZ Romunize YR 2009 MKAY MKAY
VISIBLE SMOOSH 1666 " = " I IZ Romunize YR 1666 MKAY MKAY
VISIBLE SMOOSH 3888 " = " I IZ Romunize YR 3888 MKAY MKAY
KTHXBYE


PROGRAM:RPS
:{0,0,0}→L1
:{0,0,0}→L2
:Lbl ST
:Disp "R/P/S"
:Disp "1/2/3"
:Lbl EC
:Input A
:If A>3 or A<1
:Then
:Goto NO
:End
:randInt(1,3+L1(1)+L1(2)+L1(3)→C
:If C≤1+L1(1)
:Then
:2→B
:Goto NS
:End
:If C>2+L1(2)
:Then
:1→B
:Else
:3→B
:End
:Lbl NS
:L1(A)+1→L1(A)
:If A=B
:Then
:Disp "TIE GAME"
:L2(3)+1→L2(3)
:Goto TG
:End
:If (A=1 and B=2) or (A=2 and B=3) or (A=3 and B=1)
:Then
:Disp "I WIN"
:L2(1)+1→L2(1)
:Else
:Disp "YOU WIN"
:L2(2)+1→L2(2)
:End
:Lbl TG
:Disp "PLAY AGAIN?"
:Input Str1
:If Str1="YES"
:Then
:ClrHome
:Goto ST
:Else
:Goto EN
:End
:Lbl NO
:ClrHome
:Pause "PICK 1,2, or 3"
:ClrHome
:Goto EC
:Lbl EN
:ClrHome
:Disp "I WON:"
:Disp L2(1)
:Disp "YOU WON:"
:Disp L2(2)
:Disp "WE TIED:"
:Disp L2(3)
:Disp "BYE"


while(isobject(RockPaperScissors))
	RockPaperScissors.delete();

new scriptObject(RockPaperScissors);

function RockPaperScissors::startGame(%this)
{
	%this.idle = true;
	echo("Starting rock paper scissors, please type choose(\"choice\"); to proceed!");
}

function RockPaperScissors::endGame(%this)
{
	%this.idle = true;
}

function RockPaperScissors::main(%this)
{
	%this.idle = 0;

	if(getRandom(1,2) == 1)
	{
		%result = %this.getChoiceByUserFrequency();
	}
	else
	{
		%c[0] = "rock";
		%c[1] = "paper";
		%c[2] = "scissors";

		%result = %c[getRandom(0,2)];
	}

	%userChoice = %this.current;

	%winner = thisVSthat(%userChoice,%result);

	if(%winner == 0)
	{
		echo("You both chose "@%[email protected]", tie!");
	}
	else
	if(%winner == 1)
	{
		echo("You chose "@%[email protected]" computer chose "@%[email protected]", you win!");
	}
	else
	if(%winner == 2)
	{
		echo("You chose "@%[email protected]" computer chose "@%[email protected]", you lose!");
	}

	%this.idle = true;
}

function RockPaperScissors::getChoiceByUserFrequency(%this)
{
	%weakness["rock"] = "paper";
	%weakness["paper"] = "Scissors";
	%weakness["scissors"] = "rock";

	%a[0] = %this.choice["rock"];
	%a[1] = %this.choice["paper"];
	%a[2] = %this.choice["Scissors"];

	%b[0] = "rock";
	%b[1] = "paper";
	%b[2] = "scissors";

	for(%i=0;%i<3;%i++)
	{
		%curr = %a[%i];

		if(%temp $= "")
		{
			%temp = %curr;
			%tempi = %i;
		}
		else
		if(%curr > %temp)
		{
			%temp = %curr;
			%tempi = %i;
		}
	}

	return %weakness[%b[%tempi]];
}

function choose(%this)
{
	%rps = rockPaperScissors;

	if(!%rps.idle)
	{
		return 0;
	}
	else
	if(%this !$= "rock" && %this !$= "paper" && %this !$= "scissors")
	{
		return 0;
	}

	%rps.choice[%this]++;
	%rps.current = %this;
	%rps.main();

	return %this;
}

function thisVSthat(%this,%that)
{
	if(%this !$= "rock" && %this !$= "paper" && %this !$= "scissors")
	{
		return 0;
	}
	else
	if(%that !$= "rock" && %that !$= "paper" && %that !$= "scissors")
	{
		return 0;
	}

	%weakness["rock"] = "paper";
	%weakness["paper"] = "Scissors";
	%weakness["scissors"] = "rock";

	if(%weakness[%this] $= %that)
	{
		%result = 2;
	}
	else
	if(%weakness[%that] $= %this)
	{
		%result = 1;
	}
	else
		%result = 0;

	return %result;
}


 20 LET P=0: LET Q=0: LET Z=0
 30 INPUT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors)? ", A
 40 IF A>3 THEN GOTO 400
 50 IF A=3 THEN LET A=4
 60 IF A<1 THEN GOTO 400
 70 C=RND(3) : LET D=4: FOR B=1 TO C+1 : LET D = D+D : NEXT : GOTO (A+D)*10
 90 Z=Z+1 : PRINT "We both chose 'rock'. It's a draw." : GOTO 30
100 P=P+1 : PRINT "You chose 'paper', I chose 'rock'. You win.." : GOTO 30
120 Q=Q+1 : PRINT "You chose 'scissors', I chose 'rock'. I win!" : GOTO 30
170 Q=Q+1 : PRINT "You chose 'rock', I chose 'paper'. I win!" : GOTO 30
180 Z=Z+1 : PRINT "We both chose 'paper'. It's a draw." : GOTO 30
200 P=P+1 : PRINT "You chose 'scissors', I chose 'paper'. You win.." : GOTO 30
330 P=P+1 : PRINT "You chose 'rock', I chose 'scissors'. You win.." : GOTO 30
340 Q=Q+1 : PRINT "You chose 'paper', I chose 'scissors'. I win!" : GOTO 30
360 Z=Z+1 : PRINT "We both chose 'scissors'. It's a draw." : GOTO 30
400 PRINT "There were ";Z;" draws. I lost ";P;" times, you lost ";Q;" times." : END


Function toRoman(value) As String
	Dim arabic(12) As Integer
	Dim roman(12) As String

	arabic(0) = 1000
	arabic(1) = 900
	arabic(2) = 500
	arabic(3) = 400
	arabic(4) = 100
	arabic(5) = 90
	arabic(6) = 50
	arabic(7) = 40
	arabic(8) = 10
	arabic(9) = 9
	arabic(10) = 5
	arabic(11) = 4
	arabic(12) = 1

	roman(0) = "M"
	roman(1) = "CM"
	roman(2) = "D"
	roman(3) = "CD"
	roman(4) = "C"
	roman(5) = "XC"
	roman(6) = "L"
	roman(7) = "XL"
	roman(8) = "X"
	roman(9) = "IX"
	roman(10) = "V"
	roman(11) = "IV"
	roman(12) = "I"

	Dim i As Integer, result As String

	For i = 0 To 12
		Do While value >= arabic(i)
			result = result + roman(i)
			value = value - arabic(i)
		Loop
	Next i

	toRoman = result
End Function


#!/bin/bash
choices=(rock paper scissors)

# comparison function, works like Perl
# winner x y =  2 if y beats x, 1 if x beats 1, 0 if it's a tie
winner() {
  local left="$1" right="$2"
  echo $(( (3 + left - right) % 3 ))
}

human_counts=(1 1 1)
human_count=3
computer_counts=(0 0 0)
games=0 human=0 computer=0

PS3="What do you throw? "
while true; do
  select choice in rock paper scissors quit; do
    if [ -z "$choice" ]; then choice="$REPLY"; fi
    if [ "$choice" = "quit" ]; then
      break 2
    fi
    for (( h=0; h<${#choices[@]}; ++h )); do
      if [ "${choices[h]}" = "$choice" ]; then
        break
      fi
    done
    if (( h < 3 )); then
      break
    fi
    echo "Unrecognized choice.  Try again!"
  done

  let n=RANDOM%human_count
  for (( c=0; c<${#human_counts[@]}; ++c )); do
    let n-=${human_counts[c]}
    if (( n < 0 )); then
       break
    fi
  done
  let computer_counts[c]+=1
  echo
  echo "You chose ${choices[h]^^}"
  echo "I chose ${choices[c]^^}"
  w="$(winner "$c" "$h")"
  case "$w" in
     2) echo "YOU WIN!"; let human+=1;;
     0) echo "TIE!";;
     1) echo "I WIN!"; let computer+=1;;
     *) echo "winner returned weird result '$w'";;
  esac
  echo
  let games+=1
  (( human_counts[(h+1)%3]+=1, human_count+=1 ))
done

echo
echo "We played $games games.  You won $human, and I won $computer."
for (( i=0; i<3; ++i )); do
  echo "You picked ${choices[i]} $(( human_counts[ (i+1)%3 ] - 1 )) times."
  echo "I picked ${choices[i]} $(( computer_counts[i] )) times."
done


> for n in [ 1666, 1990, 2008 ] do printf( "%d\t%s\n", n, convert( n, 'roman' ) ) end:
1666    MDCLXVI
1990    MCMXC
2008    MMVIII


let entered=0
let keycode=0
let rcounter=1
print 1 "Enter R for rock, P for paper, or S for scissors. (not case sensitive)"
while entered=0
input human$
if human=$="r"
let human$="rock"
let entered=1
elseif human=$="R"
let human$="rock"
let entered=1
elseif human=$="p"
let human$="paper"
let entered=1
elseif human=$="P"
let human$="paper"
let entered=1
elseif human=$="s"
let human$="scissors"
let entered=1
elseif human=$="S"
let human$="scissors"
let entered=1
elseif entered=0
print 1 "That choice is invalid."
endif
wend
print 1 "Press any key so the computer can make its choice."
while keycode=0
let rcounter=rcounter+1
let keycode=key()
if rcounter=4
let rcounter=1
endif
wend
if rcounter=1
let cpu$="rock"
elseif rcounter=2
let cpu$="paper"
elseif rcounter=3
let cpu$="scissors"
endif
print 1 "You chose"+human$+"."
print 1 "The computer chose"+cpu$+"."
if human$=cpu$
print 1 "You tied."
endif
if human$="rock"
if cpu$="paper"
print 1 "Paper covers rock, so you lose."
endif
if cpu$="scissors"
print 1 "Rock blunts scissors, so you win."
endif
endif
if human$="paper"
if cpu$="rock"
print 1 "Paper covers rock, so you win."
endif
if cpu$="scissors"
print 1 "Scissors cut paper, so you lose."
endif
endif
if human$="scissors"
if cpu$="rock"
print 1 "Rock blunts scissors, so you lose."
endif
if cpu$="paper"
print 1 "Scissors cut paper, so you win."
endif
endif
end


import "random" for Random
import "/str" for Str
import "/ioutil" for Input

var choices = "rpsq"
var rand = Random.new()

var pWins  = 0          // player wins
var cWins  = 0          // computer wins
var draws  = 0          // neither wins
var games  = 0          // games played
var pFreqs = [0, 0, 0]  // player frequencies for each choice (rps)

var printScore = Fn.new {
    System.print("Wins: You %(pWins), Computer %(cWins), Neither %(draws)\n")
}

var getComputerChoice = Fn.new {
    // make a completely random choice until 3 games have been played
    if (games < 3) return choices[rand.int(3)]
    var num = rand.int(games)
    return (num < pFreqs[0]) ? "p" :
           (num < pFreqs[0] + pFreqs[1]) ? "s" : "r"
}

System.print("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n")
while (true) {
    printScore.call()
    var pChoice = Str.lower(Input.option("Your choice r/p/s/q : ", "rpsqRPSQ"))
    if (pChoice == "q") {
        System.print("OK, quitting")
        return
    }
    var cChoice = getComputerChoice.call()
    System.print("Computer's choice   : %(cChoice)")
    if (pChoice == "r" && cChoice == "s") {
        System.print("Rock breaks scissors - You win!")
        pWins = pWins + 1
    } else if (pChoice == "p" && cChoice == "r") {
        System.print("Paper covers rock - You win!")
        pWins = pWins + 1
    } else if (pChoice == "s" && cChoice == "p") {
        System.print("Scissors cut paper - You win!")
        pWins = pWins + 1
    } else if (pChoice == "s" && cChoice == "r") {
        System.print("Rock breaks scissors - Computer wins!")
        cWins = cWins + 1
    } else if (pChoice == "r" && cChoice == "p") {
        System.print("Paper covers rock - Computer wins!")
        cWins = cWins + 1
    } else if (pChoice == "p" && cChoice == "s") {
        System.print("Scissors cut paper - Computer wins!")
        cWins = cWins + 1
    } else {
        System.print("It's a draw!")
        draws = draws + 1
    }
    var pf = pFreqs[choices.indexOf(pChoice)]
    pFreqs[choices.indexOf(pChoice)] = pf + 1
    games = games + 1
    System.print()
}


RomanNumeral[4]
RomanNumeral[99]
RomanNumeral[1337]
RomanNumeral[1666]
RomanNumeral[6889]


:- module roman.

:- interface.

:- import_module io.

:- pred main(io::di, io::uo) is det.

:- implementation.

:- import_module char, int, list, string.

main(!IO) :-
    command_line_arguments(Args, !IO),
    filter(is_all_digits, Args, CleanArgs),
    foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :-
               ( Roman = to_roman(Arg) ->
                     format("%s => %s", [s(Arg), s(Roman)], !IO), nl(!IO)
               ;     format("%s cannot be converted.", [s(Arg)], !IO), nl(!IO) )
          ), CleanArgs, !IO).

:- func to_roman(string::in) = (string::out) is semidet.
to_roman(Number) = from_char_list(build_roman(reverse(to_char_list(Number)))).

:- func build_roman(list(char)) = list(char).
:- mode build_roman(in)         = out is semidet.
build_roman([]) = [].
build_roman([D|R]) = Roman :-
    map(promote, build_roman(R), Interim),
    Roman = Interim ++ digit_to_roman(D).

:- func digit_to_roman(char) = list(char).
:- mode digit_to_roman(in)   = out is semidet.
digit_to_roman('0') = [].
digit_to_roman('1') = ['I'].
digit_to_roman('2') = ['I','I'].
digit_to_roman('3') = ['I','I','I'].
digit_to_roman('4') = ['I','V'].
digit_to_roman('5') = ['V'].
digit_to_roman('6') = ['V','I'].
digit_to_roman('7') = ['V','I','I'].
digit_to_roman('8') = ['V','I','I','I'].
digit_to_roman('9') = ['I','X'].

:- pred promote(char::in, char::out) is semidet.
promote('I', 'X').
promote('V', 'L').
promote('X', 'C').
promote('L', 'D').
promote('C', 'M').

:- end_module roman.


REM Yabasic 2.763 version

WINNER = 1 : ACTION = 2 : LOSSER = 3
dim word$(10, 3)

for n = 0 to 9
    read word$(n, WINNER), word$(n, ACTION), word$(n, LOSSER)
next n

repeat
    clear screen
    computerChoice$ = word$(ran(10), WINNER)
    print "'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
    for n = 0 to 9
        SimonSay(n)
    next n
    print "\nType your choice letter:"
    print "(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit\n"
    k$ = upper$(inkey$)
    if k$ = "Q" break
    switch k$
        case "R": humanChoice$ = "Rock" : break
        case "P": humanChoice$ = "Paper" : break
        case "S": humanChoice$ = "Scissors" : break
        case "L": humanChoice$ = "Lizard" : break
        case "K": humanChoice$ = "Spock" : break
    end switch
    print "Player chose ", humanChoice$, " and Computer chose ", computerChoice$
    for n = 0 to 9
        if word$(n, WINNER) = humanChoice$ and word$(n, LOSSER) = computerChoice$ then
            SimonSay(n)
            print "Winner was Player"
            wp = wp + 1
            break
        elseif word$(n, WINNER) = computerChoice$ and word$(n, LOSSER) = humanChoice$ then
            SimonSay(n)
            print "Winner was Computer"
            wc = wc + 1
            break
        end if
    next n
    if n = 10 then
        print "Ouch!"
    end if
    punctuation()
    print "\nPress any key to continue"
    inkey$
until(k$ = "Q")

punctuation()
if wp > wc then
    print "Player win"
elseif wc > wp then
    print "Computer win"
else
    print "Tie"
end if

end

sub SimonSay(n)
    print word$(n, WINNER), " ", word$(n, ACTION), " ", word$(n, LOSSER)
end sub

sub punctuation()
    print "\nPlayer = ", wp, "\tComputer = ", wc, "\n"
end sub

data "Scissors","cuts","Paper"
data "Paper","covers","Rock"
data "Rock","crushes","Lizard"
data "Lizard","poisons","Spock"
data "Spock","smashes","Scissors"
data "Scissors","decapites","Lizard"
data "Lizard","eats","Paper"
data "Paper","disproves","Spock"
data "Spock","vaporizes","Rock"
data "Rock","blunts","Scissors"


arabicNumeral = 1990
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MCMXC
arabicNumeral = 2018
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMXVIII
arabicNumeral = 3888
ConvertToRoman()
TextWindow.WriteLine(romanNumeral) 'MMMDCCCLXXXVIII

Sub ConvertToRoman
  weights[0] = 1000
  weights[1] =  900
  weights[2] =  500
  weights[3] =  400
  weights[4] =  100
  weights[5] =   90
  weights[6] =   50
  weights[7] =   40
  weights[8] =   10
  weights[9] =    9
  weights[10] =   5
  weights[11] =   4
  weights[12] =   1
  symbols[0] = "M"
  symbols[1] = "CM"
  symbols[2] = "D"
  symbols[3] = "CD"
  symbols[4] = "C"
  symbols[5] = "XC"
  symbols[6] = "L"
  symbols[7] = "XL"
  symbols[8] = "X"
  symbols[9] = "IX"
  symbols[10] = "V"
  symbols[11] = "IV"
  symbols[12] = "I"
  romanNumeral = ""
  i = 0
  While (i <= 12) And (arabicNumeral > 0)
    While arabicNumeral >= weights[i]
      romanNumeral = Text.Append(romanNumeral, symbols[i])
      arabicNumeral = arabicNumeral - weights[i]
    EndWhile
    i = i + 1
  EndWhile
EndSub


MODULE RomanNumeralsEncode;

FROM Strings IMPORT
  Append;
FROM STextIO IMPORT
  WriteString, WriteLn;

CONST
  MaxChars = 15;
  (* 3888 or MMMDCCCLXXXVIII (15 chars) is the longest string properly encoded
     with these symbols. *)

TYPE
  TRomanNumeral = ARRAY [0 .. MaxChars - 1] OF CHAR;

PROCEDURE ToRoman(AValue: CARDINAL; VAR OUT Destination: ARRAY OF CHAR);
TYPE
  TRomanSymbols = ARRAY [0 .. 1] OF CHAR;
  TWeights = ARRAY [0 .. 12] OF CARDINAL;
  TSymbols = ARRAY [0 .. 12] OF TRomanSymbols;
CONST
  Weights = TWeights {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
  Symbols = TSymbols {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX",
    "V", "IV", "I"};
VAR
  I: CARDINAL;
BEGIN
  Destination := "";
  I := 0;
  WHILE (I <= HIGH(Weights)) AND (AValue > 0) DO
    WHILE AValue >= Weights[I] DO
      Append(Symbols[I], Destination);
      AValue := AValue - Weights[I]
    END;
    INC(I);
  END;
END ToRoman;

VAR
  Numeral: TRomanNumeral;

BEGIN
  ToRoman(1990, Numeral); WriteString(Numeral); WriteLn; (* MCMXC *)
  ToRoman(2018, Numeral); WriteString(Numeral); WriteLn; (* MMXVIII *)
  ToRoman(3888, Numeral); WriteString(Numeral); WriteLn; (* MMMDCCCLXXXVIII *)
END RomanNumeralsEncode.


TOROMAN(INPUT)
 ;Converts INPUT into a Roman numeral. INPUT must be an integer between 1 and 3999
 ;OUTPUT is the string to return
 ;I is a loop variable
 ;CURRVAL is the current value in the loop
 QUIT:($FIND(INPUT,".")>1)!(INPUT<=0)!(INPUT>3999) "Invalid input"
 NEW OUTPUT,I,CURRVAL
 SET OUTPUT="",CURRVAL=INPUT
 SET:$DATA(ROMANNUM)=0 ROMANNUM="I^IV^V^IX^X^XL^L^XC^C^CD^D^CM^M"
 SET:$DATA(ROMANVAL)=0 ROMANVAL="1^4^5^9^10^40^50^90^100^400^500^900^1000"
 FOR I=$LENGTH(ROMANVAL,"^"):-1:1 DO
 .FOR  Q:CURRVAL<$PIECE(ROMANVAL,"^",I)  SET OUTPUT=OUTPUT_$PIECE(ROMANNUM,"^",I),CURRVAL=CURRVAL-$PIECE(ROMANVAL,"^",I)
 KILL I,CURRVAL
 QUIT OUTPUT


bundle Default {
  class Roman {
    nums: static : Int[];
    rum : static : String[];

    function : Init() ~ Nil {
      nums := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
      rum := ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"];
    }

    function : native : ToRoman(number : Int) ~ String {
      result := "";

      for(i :=0; i < nums->Size(); i += 1;) {
        while(number >= nums[i]) {
          result->Append(rum[i]);
          number -= nums[i];
        };
      };

      return result;
    }

    function : Main(args : String[]) ~ Nil {
      Init();

      ToRoman(1999)->PrintLine();
      ToRoman(25)->PrintLine();
      ToRoman(944)->PrintLine();
    }
  }
}


let digit x y z = function
    1 -> [x]
  | 2 -> [x;x]
  | 3 -> [x;x;x]
  | 4 -> [x;y]
  | 5 -> [y]
  | 6 -> [y;x]
  | 7 -> [y;x;x]
  | 8 -> [y;x;x;x]
  | 9 -> [x;z]

let rec to_roman x =
  if x = 0 then []
  else if x < 0 then
    invalid_arg "Negative roman numeral"
  else if x >= 1000 then
    'M' :: to_roman (x - 1000)
  else if x >= 100 then
    digit 'C' 'D' 'M' (x / 100) @ to_roman (x mod 100)
  else if x >= 10 then
    digit 'X' 'L' 'C' (x / 10) @ to_roman (x mod 10)
  else
    digit 'I' 'V' 'X' x


FUNCTION encodeRoman RETURNS CHAR (
   i_i AS INT
):

   DEF VAR cresult   AS CHAR.
   DEF VAR croman    AS CHAR EXTENT 7 INIT [  "M", "D", "C", "L", "X", "V", "I" ].
   DEF VAR idecimal  AS INT  EXTENT 7 INIT [ 1000, 500, 100,  50,  10,   5,   1 ].
   DEF VAR ipos      AS INT  INIT 1.

   DO WHILE i_i > 0:

      IF i_i - idecimal[ ipos ] >= 0 THEN
         ASSIGN
            cresult  =  cresult + croman[ ipos ]
            i_i      =  i_i - idecimal[ ipos ]
            .
      ELSE IF ipos < EXTENT( croman ) - 1 AND i_i - ( idecimal[ ipos ] - idecimal[ ipos + 2 ] ) >= 0 THEN
         ASSIGN
            cresult  =  cresult + croman[ ipos + 2 ] + croman[ ipos ]
            i_i      =  i_i - ( idecimal[ ipos ] - idecimal[ ipos + 2 ] )
            ipos     =  ipos + 1
            .
      ELSE
         ipos = ipos + 1.
   END.

   RETURN cresult.

END FUNCTION. /* encodeRoman */

MESSAGE
   1990 encodeRoman( 1990 ) SKIP
   2008 encodeRoman( 2008 ) SKIP
   2000 encodeRoman( 2000 ) SKIP
   1666 encodeRoman( 1666 ) SKIP
VIEW-AS ALERT-BOX.


declare
  fun {Digit X Y Z K}
     unit([X] [X X] [X X X] [X Y] [Y] [Y X] [Y X X] [Y X X X] [X Z])
     .K
  end

  fun {ToRoman X}
     if     X == 0    then ""
     elseif X < 0     then raise toRoman(negativeInput X) end
     elseif X >= 1000 then "M"#{ToRoman X-1000}
     elseif X >= 100  then {Digit &C &D &M  X div 100}#{ToRoman X mod 100}
     elseif X >= 10   then {Digit &X &L &C  X div 10}#{ToRoman X mod 10}
     else                  {Digit &I &V &X  X}
     end
  end
in
  {ForAll {Map [1999 25 944] ToRoman} System.showInfo}


<@ DEFUDOLITLIT>_RO|__Transformer|<@ DEFKEYPAR>__NationalNumericID|2</@><@ LETRESCS%NNMPAR>...|1</@></@>

<@ ENU$$DLSTLITLIT>1990,2008,1,2,64,124,1666,10001|,|
<@ SAYELTLST>...</@> is <@ SAY_ROELTLSTLIT>...|RomanLowerUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanUpperUnicode</@> <@ SAY_ROELTLSTLIT>...|RomanASCII</@>
</@>


function toRoman(integer v)
    constant roman  = {"M", "CM", "D","CD", "C","XC","L","XL","X","IX","V","IV","I"},
             decml  = {1000, 900, 500, 400, 100, 90, 50,  40,  10,  9,  5,   4,  1 }
    string res = ""
    integer val = v
    for i=1 to length(roman) do
        while val>=decml[i] do
            res &= roman[i]
            val -= decml[i]
        end while
    end for
--  return res
    return {v,res}  -- (for output)
end function

?apply({1990,2008,1666},toRoman)


include ..\Utilitys.pmt

def romanEnc   /# n -- s #/
    var number
    "" var res
    ( ( 1000 "M" ) ( 900 "CM" ) ( 500 "D" ) ( 400 "CD" ) ( 100 "C" ) ( 90 "XC" )
      ( 50 "L" ) ( 40 "XL" ) ( 10 "X" ) ( 9 "IX" ) ( 5 "V" ) ( 4 "IV" ) ( 1 "I" ) )

    len for
        get 1 get
        number over / int
        number rot mod var number
        swap 2 get rot dup if
            for drop res over chain var res endfor
        else
            drop
        endif
        drop drop
    endfor
    drop
    res
enddef

1968 romanEnc print


/**
 * int2roman
 * Convert any positive value of a 32-bit signed integer to its modern roman
 * numeral representation. Numerals within parentheses are multiplied by
 * 1000. ie. M == 1 000, (M) == 1 000 000, ((M)) == 1 000 000 000
 *
 * @param number - an integer between 1 and 2147483647
 * @return roman numeral representation of number
 */
function int2roman($number)
{
	if (!is_int($number) || $number < 1) return false; // ignore negative numbers and zero

	$integers = array(900, 500,  400, 100,   90,  50,   40,  10,    9,   5,    4,   1);
	$numerals = array('CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I');
	$major = intval($number / 1000) * 1000;
	$minor = $number - $major;
	$numeral = $leastSig = '';

	for ($i = 0; $i < sizeof($integers); $i++) {
		while ($minor >= $integers[$i]) {
			$leastSig .= $numerals[$i];
			$minor  -= $integers[$i];
		}
	}

	if ($number >= 1000 && $number < 40000) {
		if ($major >= 10000) {
			$numeral .= '(';
			while ($major >= 10000) {
				$numeral .= 'X';
				$major -= 10000;
			}
			$numeral .= ')';
		}
		if ($major == 9000) {
			$numeral .= 'M(X)';
			return $numeral . $leastSig;
		}
		if ($major == 4000) {
			$numeral .= 'M(V)';
			return $numeral . $leastSig;
		}
		if ($major >= 5000) {
			$numeral .= '(V)';
			$major -= 5000;
		}
		while ($major >= 1000) {
			$numeral .= 'M';
			$major -= 1000;
		}
	}

	if ($number >= 40000) {
		$major = $major/1000;
		$numeral .= '(' . int2roman($major) . ')';
	}

	return $numeral . $leastSig;
}


import String;
int main(){
   write(int2roman(2009) + "\n");
   write(int2roman(1666) + "\n");
   write(int2roman(1337) + "\n");
}


/* From Wiki Fortran */
roman: procedure (n) returns(character (32) varying);
   declare n fixed binary nonassignable;
   declare (d, m) fixed binary;
   declare (r, m_div) character (32) varying;
   declare d_dec(13) fixed binary static initial
      (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);
   declare d_rom(13) character (2) varying static initial
      ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L',
       'XL', 'X', 'IX', 'V', 'IV', 'I');
   r = '';
   m = n;
   do d = 1 to 13;
      m_div = m / d_dec (d);
      r = r || copy (d_rom (d), m_div);
      m = m - d_dec (d) * m_div;
   end;
   return (r);
end roman;


/*****************************************************************
 * $Author: Atanas Kebedjiev $
 *****************************************************************
 * Encoding an Arabic numeral to a Roman in the range 1..3999 is much simpler as Oracle provides the conversion formats.
 * Please see also the SQL solution for the same task.
 */

CREATE OR REPLACE
FUNCTION rencode(an IN NUMBER)
  RETURN VARCHAR2
IS
BEGIN
  RETURN to_char(an, 'RN');
END rencode;

BEGIN

    DBMS_OUTPUT.PUT_LINE ('2012 = ' || rencode('2012'));     -- MMXII
    DBMS_OUTPUT.PUT_LINE ('1951 = ' || rencode('1951'));     -- MCMLI
    DBMS_OUTPUT.PUT_LINE ('1987 = ' || rencode('1987'));     -- MCMLXXXVII
    DBMS_OUTPUT.PUT_LINE ('1666 = ' || rencode('1666'));     -- MDCLXVI
    DBMS_OUTPUT.PUT_LINE ('1999 = ' || rencode('1999'));     -- MCMXCIX

END;


\def\upperroman#1{\uppercase\expandafter{\romannumeral#1}}
Anno Domini \upperroman{\year}
\bye


FUNCTION toRoman(value AS INTEGER) AS STRING
    DIM arabic(0 TO 12) AS INTEGER
    DIM roman(0 TO 12) AS STRING
    ARRAY ASSIGN arabic() = 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1
    ARRAY ASSIGN roman() = "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"

    DIM i AS INTEGER
    DIM result AS STRING

    FOR i = 0 TO 12
        DO WHILE value >= arabic(i)
            result = result & roman(i)
            value = value - arabic(i)
        LOOP
    NEXT i
    toRoman = result
END FUNCTION

FUNCTION PBMAIN
    'Testing
    ? "2009 = " & toRoman(2009)
    ? "1666 = " & toRoman(1666)
    ? "3888 = " & toRoman(3888)
END FUNCTION


Filter ToRoman {
	$output = ''

	if ($_ -ge 4000) {
		throw 'Number too high'
	}

	$current = 1000
	$subtractor = 'M'
	$whole = $False
	$decimal = $_
	'C','D','X','L','I','V',' ' `
	| %{
		$divisor = $current
		if ($whole = !$whole) {
			$current /= 10
			$subtractor = $_ + $subtractor[0]
			$_ = $subtractor[1]
		}
		else {
			$divisor *= 5
			$subtractor = $subtractor[0] + $_
		}

		$multiple = [Math]::floor($decimal / $divisor)
		if ($multiple) {
			$output += [string]$_ * $multiple
			$decimal %= $divisor
		}
		if ($decimal -ge ($divisor -= $current)) {
			$output += $subtractor
			$decimal -= $divisor
		}
	}

	$output
}


F addsub(x, y)
   R (x + y, x - y)

V (summ, difference) = addsub(33, 12)
print(‘33 + 12 = ’summ)
print(‘33 - 12 = ’difference)


#SymbolCount = 12 ;0 based count
DataSection
  denominations:
  Data.s "M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" ;0-12

  denomValues:
  Data.i  1000,900,500,400,100,90,50,40,10,9,5,4,1 ;values in decending sequential order
EndDataSection

;-setup
Structure romanNumeral
  symbol.s
  value.i
EndStructure

Global Dim refRomanNum.romanNumeral(#SymbolCount)

Restore denominations
For i = 0 To #SymbolCount
  Read.s refRomanNum(i)\symbol
Next

Restore denomValues
For i = 0 To #SymbolCount
  Read refRomanNum(i)\value
Next

Procedure.s decRoman(n)
  ;converts a decimal number to a roman numeral
  Protected roman$, i

  For i = 0 To #SymbolCount
    Repeat
      If n >= refRomanNum(i)\value
        roman$ + refRomanNum(i)\symbol
        n - refRomanNum(i)\value
      Else
        Break
      EndIf
    ForEver
  Next

  ProcedureReturn roman$
EndProcedure

If OpenConsole()

  PrintN(decRoman(1999)) ;MCMXCIX
  PrintN(decRoman(1666)) ;MDCLXVI
  PrintN(decRoman(25))   ;XXV
  PrintN(decRoman(954))  ;CMLIV

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


#include <future>
#include <iomanip>
#include <iostream>
#include <vector>

#include <gmpxx.h>
#include <primesieve.hpp>

std::vector<uint64_t> repunit_primes(uint32_t base,
                                     const std::vector<uint64_t>& primes) {
    std::vector<uint64_t> result;
    for (uint64_t prime : primes) {
        mpz_class repunit(std::string(prime, '1'), base);
        if (mpz_probab_prime_p(repunit.get_mpz_t(), 25) != 0)
            result.push_back(prime);
    }
    return result;
}

int main() {
    std::vector<uint64_t> primes;
    const uint64_t limit = 2700;
    primesieve::generate_primes(limit, &primes);
    std::vector<std::future<std::vector<uint64_t>>> futures;
    for (uint32_t base = 2; base <= 36; ++base) {
        futures.push_back(std::async(repunit_primes, base, primes));
    }
    std::cout << "Repunit prime digits (up to " << limit << ") in:\n";
    for (uint32_t base = 2, i = 0; base <= 36; ++base, ++i) {
        std::cout << "Base " << std::setw(2) << base << ':';
        for (auto digits : futures[i].get())
            std::cout << ' ' << digits;
        std::cout << '\n';
    }
}


UnpackNibbles:
; Takes accumulator as input.
; Separates a two-digit hex number into its component "nibbles." Left nibble in X, right nibble in Y.

pha          ;backup the input.
and #$0F     ;chop off the left nibble. What remains is our Y.
tay
pla          ;restore input
and #$F0     ;chop off the right nibble. What remains is our X, but it needs to be bit shifted into the right nibble.
lsr
lsr
lsr
lsr
tax          ;store in X
rts


foo:
MOVE.L D2,D0
MOVE.L D3,D1
ADD.L D1,D0
SUB.L D2,D3
MOVE.L D3,D1
RTS


mov ax,cx
mov bx,dx
add ax,bx
sub cx,dx
mov bx,cx
ret


DIM SHARED arabic(0 TO 12)
DIM SHARED roman$(0 TO 12)

FUNCTION toRoman$ (value)
    LET result$ = ""
    FOR i = 0 TO 12
        DO WHILE value >= arabic(i)
           LET result$ = result$ + roman$(i)
           LET value = value - arabic(i)
        LOOP
    NEXT i
    toRoman$ = result$
END FUNCTION

FOR i = 0 TO 12
    READ arabic(i), roman$(i)
NEXT i

DATA 1000, "M", 900, "CM", 500, "D", 400, "CD", 100, "C", 90, "XC"
DATA 50, "L", 40, "XL", 10, "X", 9, "IX", 5, "V",  4, "IV", 1, "I"

'Testing
PRINT "2009 = "; toRoman$(2009)
PRINT "1666 = "; toRoman$(1666)
PRINT "3888 = "; toRoman$(3888)


// Repunit primes. Nigel Galloway: January 24th., 2022
let rUnitP(b:int)=let b=bigint b in primes32()|>Seq.takeWhile((>)1000)|>Seq.map(fun n->(n,((b**n)-1I)/(b-1I)))|>Seq.filter(fun(_,n)->Open.Numeric.Primes.MillerRabin.IsProbablePrime &n)|>Seq.map fst
[2..16]|>List.iter(fun n->printf $"Base %d{n}: "; rUnitP(n)|>Seq.iter(printf "%d "); printfn "")


package main

import (
    "fmt"
    big "github.com/ncw/gmp"
    "rcu"
    "strings"
)

func main() {
    limit := 2700
    primes := rcu.Primes(limit)
    s := new(big.Int)
    for b := 2; b <= 36; b++ {
        var rPrimes []int
        for _, p := range primes {
            s.SetString(strings.Repeat("1", p), b)
            if s.ProbablyPrime(15) {
                rPrimes = append(rPrimes, p)
            }
        }
        fmt.Printf("Base %2d: %v\n", b, rPrimes)
    }
}


using Primes

repunitprimeinbase(n, base) = isprime(evalpoly(BigInt(base), [1 for _ in 1:n]))

for b in 2:40
    println(rpad("Base $b:", 9), filter(n -> repunitprimeinbase(n, b), 1:2700))
end


ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
ClearAll[RepUnitPrimeQ]
RepUnitPrimeQ[b_][n_] := PrimeQ[FromDigits[ConstantArray[1, n], b]]
Do[
 Print["Base ", b, ": ", Select[Range[2700], RepUnitPrimeQ[b]]]
 ,
 {b, 2, 16}
]


use strict;
use warnings;
use ntheory <is_prime fromdigits>;

my $limit = 1000;

print "Repunit prime digits (up to $limit) in:\n";

for my $base (2..16) {
    printf "Base %2d: %s\n", $base, join ' ', grep { is_prime $_ and is_prime fromdigits(('1'x$_), $base) and " $_" } 1..$limit
}


;; To return multiple values:
(defun multiple-values (a b)
   (mv a b))

;; To extract the values:
(mv-let (x y)
        (multiple-values 1 2)
   (+ x y))


with Ada.Text_IO; use Ada.Text_IO;
procedure MultiReturn is
   procedure SumAndDiff (x, y : Integer; sum, diff : out Integer) is begin
      sum := x + y;
      diff := x - y;
   end SumAndDiff;
   inta : Integer := 5;
   intb : Integer := 3;
   thesum, thediff : Integer;
begin
   SumAndDiff (inta, intb, thesum, thediff);
   Put_Line ("Sum:" & Integer'Image (thesum));
   Put_Line ("Diff:" & Integer'Image (thediff));
end MultiReturn;


  [ $ ""
    swap 1000 /mod $ "M" rot of rot swap join swap
    dup   900 < not if [ 900 - dip [ $ "CM" join ] ]
    dup   500 < not if [ 500 - dip [ $  "D" join ] ]
    dup   400 < not if [ 400 - dip [ $ "CD" join ] ]
          100 /mod $ "C" rot of rot swap join swap
    dup    90 < not if [  90 - dip [ $ "XC" join ] ]
    dup    50 < not if [  50 - dip [ $  "L" join ] ]
    dup    40 < not if [  40 - dip [ $ "XL" join ] ]
           10 /mod $ "X" rot of rot swap join swap
    dup     9 < not if [   9 - dip [ $ "IX" join ] ]
    dup     5 < not if [   5 - dip [ $  "V" join ] ]
    dup     4 < not if [   4 - dip [ $ "IV" join ] ]
    $ "I" swap of join ]
                              is ->roman ( n --> $ )

  1990 dup echo say " = " ->roman echo$ cr
  2008 dup echo say " = " ->roman echo$ cr
  1666 dup echo say " = " ->roman echo$ cr


with javascript_semantics
include mpfr.e
procedure repunit(mpz z, integer n, base=10)
    mpz_set_si(z,0)
    for i=1 to n do
        mpz_mul_si(z,z,base)
        mpz_add_si(z,z,1)
    end for
end procedure

atom t0 = time()
constant {limit,blimit} = iff(platform()=JS?{400,16} -- 8.8s
                                           :{1000,16}) -- 50.3s
--                                         :{1000,36}) -- 4 min 20s
--                                         :{2700,16}) -- 28 min 35s
--                                         :{2700,36}) -- >patience
sequence primes = get_primes_le(limit)
mpz z = mpz_init()
for base=2 to blimit do
    sequence rprimes = {}
    for i=1 to length(primes) do
        integer p = primes[i]
        repunit(z,p,base)
        if mpz_prime(z) then
            rprimes = append(rprimes,sprint(p))
        end if
    end for
    printf(1,"Base %2d: %s\n", {base, join(rprimes)})
end for
?elapsed(time()-t0)


from sympy import isprime
for b in range(2, 17):
    print(b, [n for n in range(2, 1001) if isprime(n) and isprime(int('1'*n, base=b))])


my $limit = 2700;

say "Repunit prime digits (up to $limit) in:";

.put for (2..16).hyper(:1batch).map: -> $base {
    $base.fmt("Base %2d: ") ~ (1..$limit).grep(&is-prime).grep( (1 x *).parse-base($base).is-prime )
}


# define a function returning three values
mv := proc() is
    return 1, 2, "three"
end ; # mv

scope # test the mv() proc
    local a, b, c := mv();
    print( c, b, a )
epocs


# example mode for returning multiple values from a procedure #
MODE PAIR = STRUCT( STRING name, INT value );

# procedure returning multiple values via a structure #
PROC get pair = ( INT a )PAIR:
    CASE a
    IN #1#    ( "H",  0 )
    ,  #2#    ( "He", 1 )
    ,  #3#    ( "Li", 3 )
    OUT       ( "?",  a )
    ESAC
;

main: (
    # use the result as a whole #
    print( ( get pair( 3 ), newline ) );
    # access the components separately #
    print( ( name OF get pair( 1 ), value OF get pair( 2 ), newline ) )
)


#lang racket
(define (encode/roman number)
  (cond ((>= number 1000) (string-append "M" (encode/roman (- number 1000))))
        ((>= number 900) (string-append "CM" (encode/roman (- number 900))))
        ((>= number 500) (string-append "D" (encode/roman (- number 500))))
        ((>= number 400) (string-append "CD" (encode/roman (- number 400))))
        ((>= number 100) (string-append "C" (encode/roman (- number 100))))
        ((>= number 90) (string-append "XC" (encode/roman (- number 90))))
        ((>= number 50) (string-append "L" (encode/roman (- number 50))))
        ((>= number 40) (string-append "XL" (encode/roman (- number 40))))
        ((>= number 10) (string-append "X" (encode/roman (- number 10))))
        ((>= number 9) (string-append "IX" (encode/roman (- number 9))))
        ((>= number 5) (string-append "V" (encode/roman (- number 5))))
        ((>= number 4) (string-append "IV" (encode/roman (- number 4))))
        ((>= number 1) (string-append "I" (encode/roman (- number 1))))
        (else "")))


my %symbols =
    1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C",
    500 => "D", 1_000 => "M";

my @subtractors =
    1_000, 100,  500, 100,  100, 10,  50, 10,  10, 1,  5, 1,  1, 0;

multi sub roman (0) { '' }
multi sub roman (Int $n) {
    for @subtractors -> $cut, $minus {
        $n >= $cut
            and return %symbols{$cut} ~ roman($n - $cut);
        $n >= $cut - $minus
            and return %symbols{$minus} ~ roman($n + $minus);
     }
}

# Sample usage

for 1 .. 2_010 -> $x {
    say roman($x);
}


; Test whether any integer is a probable prime.
(define prime<probably>?
  (lambda (n)
    ; Fast modular exponentiation.
    (define modexpt
      (lambda (b e m)
        (cond
          ((zero? e) 1)
          ((even? e) (modexpt (mod (* b b) m) (div e 2) m))
          ((odd? e) (mod (* b (modexpt b (- e 1) m)) m)))))
    ; Return multiple values s, d such that d is odd and 2^s * d = n.
    (define split
      (lambda (n)
        (let recur ((s 0) (d n))
          (if (odd? d)
            (values s d)
            (recur (+ s 1) (div d 2))))))
    ; Test whether the number a proves that n is composite.
    (define composite-witness?
      (lambda (n a)
        (let*-values (((s d) (split (- n 1)))
                      ((x) (modexpt a d n)))
          (and (not (= x 1))
               (not (= x (- n 1)))
               (let try ((r (- s 1)))
                 (set! x (modexpt x 2 n))
                 (or (zero? r)
                     (= x 1)
                     (and (not (= x (- n 1)))
                          (try (- r 1)))))))))
    ; Test whether n > 2 is a Miller-Rabin pseudoprime, k trials.
    (define pseudoprime?
      (lambda (n k)
        (or (zero? k)
            (let ((a (+ 2 (random (- n 2)))))
              (and (not (composite-witness? n a))
                   (pseudoprime? n (- k 1)))))))
    ; Compute and return Probable Primality using the Miller-Rabin algorithm.
    (and (> n 1)
         (or (= n 2)
             (and (odd? n)
                  (pseudoprime? n 50))))))


var limit = 1000

say "Repunit prime digits (up to #{limit}) in:"

for n in (2..20) {
    printf("Base %2d: %s\n", n,
        {|k| is_prime((n**k - 1) / (n-1)) }.grep(1..limit))
}


begin
    % example using a record type to return multiple values from a procedure %
    record Element ( string(2) symbol; integer atomicNumber );
    reference(Element) procedure getElement( integer value n ) ;
    begin
        Element( if      n < 1 then   "?<"
                 else if n > 3 then   "?>"
                 else case n of ( %1% "H"
                                , %2% "He"
                                , %3% "Li"
                                )
               , n
               )
    end getElement ;
    % test the procedure %
    begin
        reference(Element) elementData;
        for n := 0 until 4 do begin
            elementData := getElement(n);
            write( s_w := 0, i_w := 1
                 , atomicNumber(elementData)
                 , " "
                 , symbol(elementData)
                 );
        end
    end

end.


100 DECLARE EXTERNAL SUB sumdiff
110 !
120 CALL sumdiff(5, 3, sum, diff)
130 PRINT "Sum is "; sum
140 PRINT "Difference is "; diff
150 END
160 !
170 EXTERNAL SUB sumdiff(a, b, c, d)
180 LET c = a + b
190 LET d = a - b
200 END SUB


foo:
MOV R2,R0
MOV R3,R1
ADD R0,R2,R3
SUB R1,R2,R3
BX LR


table: [1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 5 V 4 IV 1 I]

to-Roman: function [n [integer!] return: [string!]][
    out: copy ""
    foreach [a r] table [while [n >= a][append out r n: n - a]]
    out
]

foreach number [40 33 1888 2016][print [number ":" to-Roman number]]