using System;
using System.Collections.Generic;
using System.Linq;

namespace RockPaperScissors
{
    class Program
    {
        static void Main(string[] args)
        {
            // There is no limit on the amount of weapons supported by RPSGame. Matchups are calculated depending on the order.
            var rps = new RPSGame("scissors", "paper", "rock", "lizard", "spock");

            int wins = 0, losses = 0, draws = 0;

            while (true)
            {
                Console.WriteLine("Make your move: " + string.Join(", ", rps.Weapons) + ", quit");

                string weapon = Console.ReadLine().Trim().ToLower();

                if (weapon == "quit")
                    break;

                if (!rps.Weapons.Contains(weapon))
                {
                    Console.WriteLine("Invalid weapon!");
                    continue;
                }

                int result = rps.Next(weapon);

                Console.WriteLine("You chose {0} and your opponent chose {1}!", weapon, rps.LastAIWeapon);

                switch (result)
                {
                    case 1: Console.WriteLine("{0} pwns {1}. You're a winner!", weapon, rps.LastAIWeapon);
                        wins++;
                        break;
                    case 0: Console.WriteLine("Draw!");
                        draws++;
                        break;
                    case -1: Console.WriteLine("{0} pwns {1}. You're a loser!", rps.LastAIWeapon, weapon);
                        losses++;
                        break;
                }

                Console.WriteLine();
            }

            Console.WriteLine("\nPlayer Statistics\nWins: {0}\nLosses: {1}\nDraws: {2}", wins, losses, draws);
        }

        class RPSGame
        {
            public RPSGame(params string[] weapons)
            {
                Weapons = weapons;

                // Creates a new AI opponent, and gives it the list of weapons.
                _rpsAI = new RPSAI(weapons);
            }

            // Play next turn.
            public int Next(string weapon)
            {
                string aiWeapon = _rpsAI.NextMove(); // Gets the AI opponent's next move.
                LastAIWeapon = aiWeapon; // Saves the AI opponent's move in a property so the player can see it.

                _rpsAI.AddPlayerMove(weapon); // Let the AI know which weapon the player chose, for future predictions.
                return GetWinner(Weapons, weapon, aiWeapon); // Returns -1 if AI win, 0 if draw, and 1 if player win.
            }

            // Returns matchup winner.
            public static int GetWinner(string[] weapons, string weapon1, string weapon2)
            {
                if (weapon1 == weapon2)
                    return 0; // If weapons are the same, return 0 for draw.

                if (GetVictories(weapons, weapon1).Contains(weapon2))
                    return 1; // Returns 1 for weapon1 win.
                else if (GetVictories(weapons, weapon2).Contains(weapon1))
                    return -1; // Returns -1 for weapon2 win.

                throw new Exception("No winner found.");
            }

            /*
             * Return weapons that the provided weapon beats.
             * The are calculated in the following way:
             * If the index of the weapon is even, then all even indices less than it,
             * and all odd indices greater than it, are victories.
             * One exception is if it is an odd index, and also the last index in the set,
             * then the first index in the set is a victory.
             */
            public static IEnumerable<string> GetVictories(string[] weapons, string weapon)
            {
                // Gets index of weapon.
                int index = Array.IndexOf(weapons, weapon);

                // If weapon is odd and the final index in the set, then return the first item in the set as a victory.
                if (index % 2 != 0 && index == weapons.Length - 1)
                    yield return weapons[0];

                for (int i = index - 2; i >= 0; i -= 2)
                    yield return weapons[i];

                for (int i = index + 1; i < weapons.Length; i += 2)
                    yield return weapons[i];
            }

            public string LastAIWeapon
            {
                private set;
                get;
            }

            public readonly string[] Weapons;
            private RPSAI _rpsAI;

            class RPSAI
            {
                public RPSAI(params string[] weapons)
                {
                    _weapons = weapons;
                    _weaponProbability = new Dictionary<string, int>();

                    // The AI sets the probability for each weapon to be chosen as 1.
                    foreach (string weapon in weapons)
                        _weaponProbability.Add(weapon, 1);

                    _random = new Random();
                }

                // Increases probability of selecting each weapon that beats the provided move.
                public void AddPlayerMove(string weapon)
                {
                    int index = Array.IndexOf(_weapons, weapon);

                    foreach (string winWeapon in _weapons.Except(GetVictories(_weapons, weapon)))
                        if (winWeapon != weapon)
                            _weaponProbability[winWeapon]++;
                }

                // Gets the AI's next move.
                public string NextMove()
                {
                    double r = _random.NextDouble();

                    double divisor = _weaponProbability.Values.Sum();

                    var weightedWeaponRanges = new Dictionary<double, string>();

                    double currentPos = 0.0;

                    // Maps probabilities to ranges between 0.0 and 1.0. Returns weighted random weapon.
                    foreach (var weapon in _weaponProbability)
                    {
                        double weightedRange = weapon.Value / divisor;
                        if (r <= currentPos + (weapon.Value / divisor))
                            return weapon.Key;
                        currentPos += weightedRange;
                    }

                    throw new Exception("Error calculating move.");
                }

                Random _random;
                private readonly string[] _weapons;
                private Dictionary<string, int> _weaponProbability;
            }
        }
    }
}


#! /usr/bin/env tclsh
package require http

proc get url {
    set r [::http::geturl $url]
    set content [::http::data $r]
    ::http::cleanup $r
    return $content
}

proc grep {needle haystack} {
    lsearch -all \
            -inline \
            -glob \
            [split $haystack \n] \
            *[string map {* \\* ? \\? \\ \\\\ [ \\[ ] \\]} $needle]*
}

proc main argv {
    lassign $argv needle
    set urlTemplate http://tclers.tk/conferences/tcl/%Y-%m-%d.tcl
    set back 10
    set now [clock seconds]
    for {set i -$back} {$i <= 0} {incr i} {
        set date [clock add $now $i days]
        set url [clock format $date \
                              -format $urlTemplate \
                              -timezone :Europe/Berlin]
        set found [grep $needle [get $url]]
        if {$found ne {}} {
            puts $url\n------\n[join $found \n]\n------\n
        }
    }
}

main $argv


/* retrieve_and_search_chat_history.wren */

import "./date" for Date

var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001

class C {
    foreign static searchStr
    foreign static utcNow // format will be yyyy-mm-dd hh:MM:ss
}

foreign class Buffer {
    construct new() {}   // C will allocate buffer of a suitable size

    foreign value        // returns buffer contents as a string
}

foreign class Curl {
    construct easyInit() {}

    foreign easySetOpt(opt, param)

    foreign easyPerform()

    foreign easyCleanup()
}

var curl = Curl.easyInit()

var getContent = Fn.new { |url|
    var buffer = Buffer.new()
    curl.easySetOpt(CURLOPT_URL, url)
    curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
    curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0)  // write function to be supplied by C
    curl.easySetOpt(CURLOPT_WRITEDATA, buffer)
    curl.easyPerform()
    return buffer.value
}

var baseUrl = "http://tclers.tk/conferences/tcl/"
var searchStr = C.searchStr
var now = C.utcNow
var d = Date.parse(now)
d = d.adjustTime("CET") // adjust to German time
var fmt = "mmmm| |d| |yyyy| |H|:|MM|am| |zz|"
System.print("It's %(d.format(fmt)) just now in Germany.")
System.print("Searching for '%(searchStr)' in the TCL Chatroom logs for the last 10 days:\n")
for (i in 0..9) {
    var date = d.toString.split(" ")[0]
    var url = baseUrl + date + ".tcl"
    var underline = "-" * url.count
    var content = getContent.call(url)
    var lines = content.split("\n")
    System.print("%(url)")
    System.print(underline)
    for (line in lines) {
        if (line.indexOf(searchStr) >= 0) System.print(line)
    }
    System.print(underline + "\n")
    d = d.addDays(-1)
}

curl.easyCleanup()


#include <iostream>
#include <string>

std::string to_roman(int value)
{
  struct romandata_t { int value; char const* numeral; };
  static romandata_t const romandata[] =
     { 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",
          0, NULL }; // end marker

  std::string result;
  for (romandata_t const* current = romandata; current->value > 0; ++current)
  {
    while (value >= current->value)
    {
      result += current->numeral;
      value  -= current->value;
    }
  }
  return result;
}

int main()
{
  for (int i = 1; i <= 4000; ++i)
  {
    std::cout << to_roman(i) << std::endl;
  }
}


class example
{
  foo()
  {
    Msgbox Called example.foo()
  }

  __Call(method, params*)
  {
    funcRef := Func(funcName := this.__class "." method)
    if !IsObject(funcRef)
    {
      str := "Called undefined method " funcName "() with these parameters:"
      for k,v in params
        str .= "`n" v
      Msgbox %str%
    }
    else
    {
      return funcRef.(this, params*)
    }
  }
}

ex := new example
ex.foo()
ex.bar(1,2)


#<<<#
http://tclers.tk/conferences/tcl/:
2017-04-03.tcl      30610 bytes  Apr 03, 2017 21:55:37
2017-04-04.tcl      67996 bytes  Apr 04, 2017 21:57:01
...

Contents (eg 2017-01-19.tcl):
m 2017-01-19T23:01:02Z ijchain {*** Johannes13__ leaves}
m 2017-01-19T23:15:37Z ijchain {*** fahadash leaves}
m 2017-01-19T23:27:00Z ijchain {*** Buster leaves}
...
#<<<#

var [const] CURL=Import.lib("zklCurl")();	// libCurl instance

template:="http://tclers.tk/conferences/tcl/%4d-%02d-%02d.tcl";
ymd     :=Time.Clock.UTC[0,3];	// now, (y,m,d)
back    :=10;			// days in the past
needle  :=vm.nthArg(0);		// search string
foreach d in ([-back+1..0]){	// we want day -9,-8,-7..0 (today)
   date :=Time.Date.subYMD(ymd, 0,0,-d);   // date minus days
   url  :=template.fmt(date.xplode());
   haystack:=CURL.get(url);	// (request bytes, header length)
   haystack=haystack[0].del(0,haystack[1]);	// remove HTML header
   mentions:=haystack.filter("find",needle);	// search lines
   if(mentions) println("%s\n------\n%s------\n".fmt(url,mentions.text));
}


shared void run() {

	class Numeral(shared Character char, shared Integer int) {}

	value tiers = [
		[Numeral('I', 1),   Numeral('V', 5),   Numeral('X', 10)],
		[Numeral('X', 10),  Numeral('L', 50),  Numeral('C', 100)],
		[Numeral('C', 100), Numeral('D', 500), Numeral('M', 1k)]
	];

	String toRoman(Integer hindu, Integer tierIndex = 2) {

		assert (exists tier = tiers[tierIndex]);

		" Finds if it's a two character numeral like iv, ix, xl, xc, cd and cm."
		function findTwoCharacterNumeral() =>
			if (exists bigNum = tier.rest.find((numeral) => numeral.int - tier.first.int <= hindu < numeral.int))
			then [tier.first, bigNum]
			else null;

		if (hindu <= 0) {
			// if it's zero then we are done!
			return "";
		}
		else if (exists [smallNum, bigNum] = findTwoCharacterNumeral()) {
			value twoCharSymbol = "``smallNum.char````bigNum.char``";
			value twoCharValue = bigNum.int - smallNum.int;
			return "``twoCharSymbol````toRoman(hindu - twoCharValue, tierIndex)``";
		}
		else if (exists num = tier.reversed.find((Numeral elem) => hindu >= elem.int)) {
			return "``num.char````toRoman(hindu - num.int, tierIndex)``";
		}
		else {
			// nothing was found so move to the next smaller tier!
			return toRoman(hindu, tierIndex - 1);
		}
	}

	assert (toRoman(1) == "I");
	assert (toRoman(2) == "II");
	assert (toRoman(4) == "IV");
	assert (toRoman(1666) == "MDCLXVI");
	assert (toRoman(1990) == "MCMXC");
	assert (toRoman(2008) == "MMVIII");
}


(def arabic->roman
  (partial clojure.pprint/cl-format nil "[email protected]"))

(arabic->roman 147)
;"CXXIII"
(arabic->roman 99)
;"XCIX"


# conventional weapons
enum Choice
  Rock
  Paper
  Scissors
end

BEATS = {
  Choice::Rock     => [Choice::Paper],
  Choice::Paper    => [Choice::Scissors],
  Choice::Scissors => [Choice::Rock],
}

# uncomment to use additional weapons
# enum Choice
#   Rock
#   Paper
#   Scissors
#   Lizard
#   Spock
# end

# BEATS = {
#   Choice::Rock     => [Choice::Paper, Choice::Spock],
#   Choice::Paper    => [Choice::Scissors, Choice::Lizard],
#   Choice::Scissors => [Choice::Rock, Choice::Spock],
#   Choice::Lizard   => [Choice::Rock, Choice::Scissors],
#   Choice::Spock    => [Choice::Paper, Choice::Lizard],
# }

class RPSAI
  @stats = {} of Choice => Int32

  def initialize
    Choice.values.each do |c|
      @stats[c] = 1
    end
  end

  def choose
    v = rand(@stats.values.sum)
    @stats.each do |choice, rate|
      v -= rate
      return choice if v < 0
    end
    raise ""
  end

  def train(selected)
    BEATS[selected].each do |c|
      @stats[c] += 1
    end
  end
end

enum GameResult
  HumanWin
  ComputerWin
  Draw

  def to_s
    case self
    when .draw?
      "Draw"
    when .human_win?
      "You win!"
    when .computer_win?
      "I win!"
    end
  end
end

class RPSGame
  @score = Hash(GameResult, Int32).new(0)
  @ai = RPSAI.new

  def check(player, computer)
    return GameResult::ComputerWin if BEATS[player].includes? computer
    return GameResult::HumanWin if BEATS[computer].includes? player
    return GameResult::Draw
  end

  def round
    puts ""
    print "Your choice (#{Choice.values.join(", ")}):"
    s = gets.not_nil!.strip.downcase
    return false if "quit".starts_with? s
    player_turn = Choice.values.find { |choice| choice.to_s.downcase.starts_with? s }
    unless player_turn
      puts "Invalid choice"
      return true
    end
    ai_turn = @ai.choose
    result = check(player_turn, ai_turn)
    puts "H: #{player_turn}, C: #{ai_turn} => #{result}"
    @score[result] += 1
    puts "score: human=%d, computer=%d, draw=%d" % GameResult.values.map { |r| @score[r] }
    @ai.train player_turn
    true
  end
end

game = RPSGame.new
loop do
  break unless game.round
end


example = object.new

example.no_method = { meth_name, *args |
  p "#{meth_name} was called with these arguments: #{args}"
}

example.this_does_not_exist "at all"  #Prints "this_does_not_exist was called with these arguments: [at all]"


using System;
using System.Dynamic;

class Example : DynamicObject
{
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
        result = null;

        Console.WriteLine("This is {0}.", binder.Name);
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        dynamic ex = new Example();

        ex.Foo();
        ex.Bar();
    }
}


class animal {
public:
  virtual void bark() // concrete virtual, not pure
  {
    throw "implement me: do not know how to bark";
  }
};

class elephant : public animal // does not implement bark()
{
};

int main()
{
  elephant e;
  e.bark();  // throws exception
}


Class DynamicDispatch.Example Extends %RegisteredObject
{

Method Foo()
{
	Write "This is foo", !
}

Method Bar()
{
	Write "This is bar", !
}

Method %DispatchMethod(Method As %String, Args...)
{
	Write "Tried to handle unknown method '"_Method_"'"
	For i=1:1:$Get(Args) {
		Write ", " If i=1 Write "with arguments: "
		Write "'"_Args(i)_"'"
	}
	Write !
}

ClassMethod Test()
{
	Set obj=##class(DynamicDispatch.Example).%New()
	Do obj.Foo()
	Do obj.Bar()
	Do obj.Grill()
	Do obj.Ding("Dong", 11)
}

}


roman = cluster is encode
    rep = null

    dmap = struct[v: int, s: string]
    darr = array[dmap]
    own chunks: darr := darr$
       [dmap${v: 1000, s: "M"},
        dmap${v:  900, s: "CM"},
        dmap${v:  500, s: "D"},
        dmap${v:  400, s: "CD"},
        dmap${v:  100, s: "C"},
        dmap${v:   90, s: "XC"},
        dmap${v:   50, s: "L"},
        dmap${v:   40, s: "XL"},
        dmap${v:   10, s: "X"},
        dmap${v:    9, s: "IX"},
        dmap${v:    5, s: "V"},
        dmap${v:    4, s: "IV"},
        dmap${v:    1, s: "I"}]

    largest_chunk = proc (i: int) returns (int, string)
        for chunk: dmap in darr$elements(chunks) do
            if chunk.v <= i then return (chunk.v, chunk.s) end
        end
        return (0, "")
    end largest_chunk

    encode = proc (i: int) returns (string)
        result: string := ""
        while i > 0 do
            val: int chunk: string
            val, chunk := largest_chunk(i)
            result := result || chunk
            i := i - val
        end
        return (result)
    end encode
end roman

start_up = proc ()
    po: stream := stream$primary_output()
    tests: array[int] := array[int]$[1666, 2008, 1001, 1999, 3888, 2021]

    for test: int in array[int]$elements(tests) do
        stream$putl(po, int$unparse(test) || " = " || roman$encode(test))
    end
end start_up


IDENTIFICATION DIVISION.
PROGRAM-ID. TOROMAN.
DATA DIVISION.
working-storage section.
  01 ws-number pic 9(4) value 0.
  01 ws-save-number pic 9(4).
  01 ws-tbl-def.
    03 filler pic x(7) value '1000M  '.
    03 filler pic x(7) value '0900CM '.
    03 filler pic x(7) value '0500D  '.
    03 filler pic x(7) value '0400CD '.
    03 filler pic x(7) value '0100C  '.
    03 filler pic x(7) value '0090XC '.
    03 filler pic x(7) value '0050L  '.
    03 filler pic x(7) value '0040XL '.
    03 filler pic x(7) value '0010X  '.
    03 filler pic x(7) value '0009IX '.
    03 filler pic x(7) value '0005V  '.
    03 filler pic x(7) value '0004IV '.
    03 filler pic x(7) value '0001I  '.
  01  filler redefines ws-tbl-def.
    03 filler occurs 13 times indexed by rx.
      05 ws-tbl-divisor    pic 9(4).
      05 ws-tbl-roman-ch   pic x(1) occurs 3 times indexed by cx.
  01 ocx pic 99.
  01 ws-roman.
    03 ws-roman-ch         pic x(1) occurs 16 times.
PROCEDURE DIVISION.
  accept ws-number
  perform
  until ws-number = 0
    move ws-number to ws-save-number
    if ws-number > 0 and ws-number < 4000
      initialize ws-roman
      move 0 to ocx
      perform varying rx from 1 by +1
      until ws-number = 0
        perform until ws-number < ws-tbl-divisor (rx)
          perform varying cx from 1 by +1
  		  until ws-tbl-roman-ch (rx, cx) = spaces
            compute ocx = ocx + 1
            move ws-tbl-roman-ch (rx, cx) to ws-roman-ch (ocx)
          end-perform
          compute ws-number = ws-number - ws-tbl-divisor (rx)
        end-perform
      end-perform
      display 'inp=' ws-save-number ' roman=' ws-roman
    else
      display 'inp=' ws-save-number ' invalid'
    end-if
    accept ws-number
  end-perform
  .


import std.stdio, std.random, std.string, std.conv, std.array, std.typecons;

enum Choice { rock, paper, scissors }

bool beats(in Choice c1, in Choice c2) pure nothrow @safe @nogc {
    with (Choice) return (c1 == paper    && c2 == rock) ||
                         (c1 == scissors && c2 == paper) ||
                         (c1 == rock     && c2 == scissors);
}

Choice genMove(in int r, in int p, in int s) @safe /*@nogc*/ {
    immutable x = uniform!"[]"(1, r + p + s);
    if (x < s)      return Choice.rock;
    if (x <= s + r) return Choice.paper;
    else            return Choice.scissors;
}

Nullable!To maybeTo(To, From)(From x) pure nothrow @safe {
    try {
        return typeof(return)(x.to!To);
    } catch (ConvException) {
        return typeof(return)();
    } catch (Exception e) {
        static immutable err = new Error("std.conv.to failure");
        throw err;
    }
}

void main() /*@safe*/ {
    int r = 1, p = 1, s = 1;

    while (true) {
        write("rock, paper or scissors? ");
        immutable hs = readln.strip.toLower;
        if (hs.empty)
            break;

        immutable h = hs.maybeTo!Choice;
        if (h.isNull) {
            writeln("Wrong input: ", hs);
            continue;
        }

        immutable c = genMove(r, p, s);
        writeln("Player: ", h.get, " Computer: ", c);

             if (beats(h, c)) writeln("Player wins\n");
        else if (beats(c, h)) writeln("Player loses\n");
        else                  writeln("Draw\n");

        final switch (h.get) {
            case Choice.rock:     r++; break;
            case Choice.paper:    p++; break;
            case Choice.scissors: s++; break;
        }
    }
}


(defgeneric do-something (thing)
  (:documentation "Do something to thing."))

(defmethod no-applicable-method ((method (eql #'do-something)) &rest args)
  (format nil "No method for ~w on ~w." method args))

(defmethod do-something ((thing (eql 3)))
  (format nil "Do something to ~w." thing))


import std.stdio;

struct Catcher {
    void foo() { writeln("This is foo"); }

    void bar() { writeln("This is bar"); }

    void opDispatch(string name, ArgsTypes...)(ArgsTypes args) {
        writef("Tried to handle unknown method '%s'", name);
        if (ArgsTypes.length) {
            write(", with arguments: ");
            foreach (arg; args)
                write(arg, " ");
        }
        writeln();
    }
}

void main() {
    Catcher ca;
    ca.foo();
    ca.bar();
    ca.grill();
    ca.ding("dong", 11);
}


}
labda:
	print "One!"
:one

labda:
	print "Two!"
:two
local :obj {

labda:
	print "Nope, doesn't exist."
set-default obj

obj!one
obj!two
obj!three


def example {
    to foo() { println("this is foo") }
    to bar() { println("this is bar") }
    match [verb, args] {
        println(`got unrecognized message $verb`)
        if (args.size() > 0) {
            println(`it had arguments: $args`)
        }
    }
}


decimal_to_roman = (n) ->
  # This should work for any positive integer, although it
  # gets a bit preposterous for large numbers.
  if n >= 4000
    thousands = decimal_to_roman n / 1000
    ones = decimal_to_roman n % 1000
    return "M(#{thousands})#{ones}"

  s = ''
  translate_each = (min, roman) ->
    while n >= min
      n -= min
      s += roman
  translate_each 1000, "M"
  translate_each  900, "CM"
  translate_each  500, "D"
  translate_each  400, "CD"
  translate_each  100, "C"
  translate_each   90, "XC"
  translate_each   50, "L"
  translate_each   40, "XL"
  translate_each   10, "X"
  translate_each    9, "IX"
  translate_each    5, "V"
  translate_each    4, "IV"
  translate_each    1, "I"
  s

###################
tests =
  IV: 4
  XLII: 42
  MCMXC: 1990
  MMVIII: 2008
  MDCLXVI: 1666
  'M(IV)': 4000
  'M(VI)IX': 6009
  'M(M(CXXIII)CDLVI)DCCLXXXIX': 123456789
  'M(MMMV)I': 3005001

for expected, decimal of tests
  roman = decimal_to_roman(decimal)
  if roman == expected
    console.log "#{decimal} = #{roman}"
  else
    console.log "error for #{decimal}: #{roman} is wrong"


defmodule Rock_paper_scissors do
  def play, do: loop([1,1,1])

  defp loop([r,p,s]=odds) do
    IO.gets("What is your move? (R,P,S,Q) ") |> String.upcase |> String.first
    |> case do
           "Q" -> IO.puts "Good bye!"
           human when human in ["R","P","S"] ->
              IO.puts "Your move is #{play_to_string(human)}."
              computer = select_play(odds)
              IO.puts "My move is #{play_to_string(computer)}"
              case beats(human,computer) do
                  true  -> IO.puts "You win!"
                  false -> IO.puts "I win!"
                  _     -> IO.puts "Draw"
              end
              case human do
                  "R" -> loop([r+1,p,s])
                  "P" -> loop([r,p+1,s])
                  "S" -> loop([r,p,s+1])
              end
           _ ->
              IO.puts "Invalid play"
              loop(odds)
       end
  end

  defp beats("R","S"), do: true
  defp beats("P","R"), do: true
  defp beats("S","P"), do: true
  defp beats(x,x), do: :draw
  defp beats(_,_), do: false

  defp play_to_string("R"), do: "Rock"
  defp play_to_string("P"), do: "Paper"
  defp play_to_string("S"), do: "Scissors"

  defp select_play([r,p,s]) do
    n = :rand.uniform(r+p+s)
    cond do
        n <= r   -> "P"
        n <= r+p -> "S"
        true     -> "R"
    end
  end
end

Rock_paper_scissors.play


-module(rps).
-compile(export_all).

play() ->
    loop([1,1,1]).

loop([R,P,S]=Odds) ->
    case io:fread("What is your move? (R,P,S,Q) ","~c") of
        {ok,["Q"]} -> io:fwrite("Good bye!~n");
        {ok,[[Human]]} when Human == $R; Human == $P; Human == $S ->
            io:fwrite("Your move is ~s.~n",
                      [play_to_string(Human)]),
            Computer = select_play(Odds),
            io:fwrite("My move is ~s~n",
                      [play_to_string(Computer)]),
            case {beats(Human,Computer),beats(Computer,Human)} of
                {true,_} -> io:fwrite("You win!~n");
                {_,true} -> io:fwrite("I win!~n");
                _ -> io:fwrite("Draw~n")
            end,
            case Human of
                $R -> loop([R+1,P,S]);
                $P -> loop([R,P+1,S]);
                $S -> loop([R,P,S+1])
            end;
        _ ->
            io:fwrite("Invalid play~n"),
            loop(Odds)
    end.

beats($R,$S) -> true;
beats($P,$R) -> true;
beats($S,$P) -> true;
beats(_,_) -> false.

play_to_string($R) -> "Rock";
play_to_string($P) -> "Paper";
play_to_string($S) -> "Scissors".

select_play([R,P,S]) ->
    N = random:uniform(R+P+S),
    if
        N =< R -> $P;
        N =< R+P -> $S;
        true -> $R
    end.


import extensions;

class Example
{
    generic()
    {
        // __received is an built-in variable containing the incoming message name
        console.printLine(__received," was invoked")
    }

    generic(x)
    {
        console.printLine(__received,"(",x,") was invoked")
    }

    generic(x,y)
    {
        console.printLine(__received,"(",x,",",y,") was invoked")
    }
}

public program()
{
    var o := new Example();

    o.foo();
    o.bar(1);
    o.someMethod(1,2)
}


class CatchThemAll {
  def foo {
    "foo received" println
  }

  def bar {
    "bar received" println
  }

  def unknown_message: msg with_params: params {
    "message: " ++ msg print
    "arguments: " ++ (params join: ", ") println
  }
}

a = CatchThemAll new
a foo
a bar
a we_can_do_it
a they_can_too: "eat" and: "walk"


class A
{
  public Void doit (Int n)
  {
    echo ("known function called on $n")
  }

  // override the 'trap' method, which catches dynamic invocations of methods
  override Obj? trap(Str name, Obj?[]? args := null)
  {
    try
    {
      return super.trap(name, args)
    }
    catch (UnknownSlotErr err)
    {
      echo ("In trap, you called: " + name + " with args " + args.join(","))
      return null
    }
  }
}

class Main
{
  public static Void main ()
  {
    a := A()
    // note the dynamic dispatch
    a->doit (1)
    a->methodName (1, 2, 3)
  }
}


include FMS-SI.f
include FMS-SILib.f

var x  \ instantiate a class var object named x
x add: \ => "aborted: message not understood"


package main

import (
    "fmt"
    "reflect"
)

type example struct{}

func (example) Foo() int {
    return 42
}

// a method to call another method by name
func (e example) CallMethod(n string) int {
    if m := reflect.ValueOf(e).MethodByName(n); m.IsValid() {
        // it's known.  call it.
        return int(m.Call(nil)[0].Int())
    }
    // otherwise it's unknown.  handle as needed.
    fmt.Println("Unknown method:", n)
    return 0
}

func main() {
    var e example
    fmt.Println(e.CallMethod("Foo"))
    fmt.Println(e.CallMethod("Bar"))
}


(defun roman-numeral (n)
  (format nil "[email protected]" n))


include "cowgol.coh";
include "argv.coh";

# Encode the given number as a Roman numeral
sub decimalToRoman(num: uint16, buf: [uint8]): (rslt: [uint8]) is
    # return the start of the buffer for easy printing
    rslt := buf;

    # Add string to buffer
    sub Add(str: [uint8]) is
        while [str] != 0 loop
            [buf] := [str];
            buf := @next buf;
            str := @next str;
        end loop;
    end sub;

    # Table of Roman numerals
    record Roman is
        value: uint16;
        string: [uint8];
    end record;

    var numerals: Roman[] := {
        {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"}
    };

    var curNum := &numerals as [Roman];
    while num != 0 loop
        while num >= curNum.value loop
            Add(curNum.string);
            num := num - curNum.value;
        end loop;
        curNum := @next curNum;
    end loop;

    [buf] := 0; # terminate the string
end sub;

# Read numbers from the command line and print the corresponding Roman numerals
ArgvInit();
var buffer: uint8[100];
loop
    var argmt := ArgvNext();
    if argmt == (0 as [uint8]) then
        break;
    end if;

    var dummy: [uint8];
    var number: int32;
    (number, dummy) := AToI(argmt);

    print(decimalToRoman(number as uint16, &buffer as [uint8]));
    print_nl();
end loop;


function weighted_rand(sequence table)
    integer sum,r
    sum = 0
    for i = 1 to length(table) do
        sum += table[i]
    end for

    r = rand(sum)
    for i = 1 to length(table)-1 do
        r -= table[i]
        if r <= 0 then
            return i
        end if
    end for
    return length(table)
end function

constant names = { "Rock", "Paper", "Scissors" }
constant winner = { "We tied.", "Meself winned.", "You win." }
integer user_action, my_action, key, win
sequence user_rec, score
user_rec = {1,1,1}
score = {0,0}

while 1 do
    my_action = remainder(weighted_rand(user_rec)+1,3)+1
    puts(1,"Your choice [1-3]:\n")
    puts(1,"  1. Rock\n  2. Paper\n  3. Scissors\n> ")
    key = -1
    while (key < '1' or key > '3') and key != 'q' do
        key = get_key()
    end while
    puts(1,key)
    puts(1,'\n')
    if key = 'q' then
        exit
    end if
    user_action = key-'0'
    win = remainder(my_action-user_action+3,3)
    printf(1,"You chose %s; I chose %s. %s\n",
        { names[user_action],
          names[my_action],
          winner[win+1] })

    if win then
        score[win] += 1
    end if
    printf(1,"\nScore %d:%d\n",score)
    user_rec[user_action] += 1
end while


class MyObject {
    def foo() {
        println 'Invoked foo'
    }
    def methodMissing(String name, args) {
        println "Invoked missing method $name$args"
    }
}


procedure DynMethod(obj,meth,arglist[])
   local m

   if not (type(obj) ? ( tab(find("__")), ="__state", pos(0))) then
      runerr(205,obj)                       # invalid value - not an object

   if meth == ("initially"|"UndefinedMethod") then fail  # avoid protected

   m := obj.__m                                          # get methods list
   if fieldnames(m) == meth then                         # method exists?
      return m[meth]!push(copy(arglist),obj)             # ... call it
   else
      if fieldnames(m) == "UndefinedMethod" then         # handler exists?
         return obj.UndefinedMethod!arglist              # ... call it
      else runerr(207,obj)                  # error invalid method (i.e. field)
end


Example := Object clone do(
    foo := method(writeln("this is foo"))
    bar := method(writeln("this is bar"))
    forward := method(
        writeln("tried to handle unknown method ",call message name)
        if( call hasArgs,
            writeln("it had arguments: ",call evalArgs)
        )
    )
)

example := Example clone

example foo          // prints "this is foo"
example bar          // prints "this is bar"
example grill        // prints "tried to handle unknown method grill"
example ding("dong") // prints "tried to handle unknown method ding"
                     // prints "it had arguments: list("dong")"


string toRoman(int n) pure nothrow
in {
    assert(n < 5000);
} body {
    static immutable weights = [1000, 900, 500, 400, 100, 90,
                                50, 40, 10, 9, 5, 4, 1];
    static immutable symbols = ["M","CM","D","CD","C","XC","L",
                                "XL","X","IX","V","IV","I"];

    string roman;
    foreach (i, w; weights) {
        while (n >= w) {
            roman ~= symbols[i];
            n -= w;
        }
        if (n == 0)
            break;
    }
    return roman;
} unittest {
    assert(toRoman(455)  == "CDLV");
    assert(toRoman(3456) == "MMMCDLVI");
    assert(toRoman(2488) == "MMCDLXXXVIII");
}

void main() {}


open System

let random = Random ()
let rand = random.NextDouble () //Gets a random number in the range (0.0, 1.0)

/// Union of possible choices for a round of rock-paper-scissors
type Choice =
| Rock
| Paper
| Scissors

/// Gets the string representation of a Choice
let getString = function
    | Rock -> "Rock"
    | Paper -> "Paper"
    | Scissors -> "Scissors"

/// Defines rules for winning and losing
let beats (a : Choice, b : Choice) =
    match a, b with
    | Rock, Scissors -> true    // Rock beats Scissors
    | Paper, Rock -> true       // Paper beats Rock
    | Scissors, Paper -> true   // Scissors beat Paper
    | _, _ -> false

/// Generates the next move for the computer based on probability derived from previous player moves.
let genMove r p s =
    let tot = r + p + s
    let n = rand
    if n <= s / tot then Rock
    elif n <= (s + r) / tot then Paper
    else Scissors

/// Gets the move chosen by the player
let rec getMove () =
    printf "[R]ock, [P]aper, or [S]cissors?: "
    let choice = Console.ReadLine ()
    match choice with
    | "r" | "R" -> Rock
    | "p" | "P" -> Paper
    | "s" | "S" -> Scissors
    | _ ->
        printf "Invalid choice.\n\n"
        getMove ()

/// Place where all the game logic takes place.
let rec game (r : float, p : float, s : float) =
    let comp = genMove r p s
    let player = getMove ()
    Console.WriteLine ("Player: {0} vs Computer: {1}", getString player, getString comp)
    Console.WriteLine (
        if beats(player, comp) then "Player Wins!\n"
        elif beats(comp, player) then "Computer Wins!\n"
        else "Draw!\n"
    )
    let nextR = if player = Rock then r + 1.0 else r
    let nextP = if player = Paper then p + 1.0 else p
    let nextS = if player = Scissors then s + 1.0 else s
    game (nextR, nextP, nextS)

game(1.0, 1.0, 1.0)


example=:3 :0
   doSomething_z_=: assert&0 bind 'doSomething was not implemented'
   doSomething__y ''
)

doSomething_adhoc1_=: smoutput bind 'hello world'
dSomethingElse_adhoc2_=: smoutput bind 'hello world'


obj  = new Proxy({},
        { get : function(target, prop)
            {
                if(target[prop] === undefined)
                    return function()  {
                        console.log('an otherwise undefined function!!');
                    };
                else
                    return target[prop];
            }
        });
obj.f()        ///'an otherwise undefined function!!'
obj.l = function() {console.log(45);};
obj.l();       ///45


function add(a, b)
   try
       a + b
   catch
       println("caught exception")
       a * b
   end
end

println(add(2, 6))
println(add(1//2, 1//2))
println(add("Hello ", "world"))


// Kotlin JS version 1.2.0 (Firefox 43)

class C {
    // this method prevents a TypeError being thrown if an unknown method is called
    fun __noSuchMethod__(id: String, args: Array<Any>) {
        println("Class C does not have a method called $id")
        if (args.size > 0) println("which takes arguments: ${args.asList()}")
    }
}

fun main(args: Array<String>) {
    val c: dynamic = C()  // 'dynamic' turns off compile time checks
    c.foo() // the compiler now allows this call even though foo() is undefined
}


define exampletype => type {
	public foo() => {
		return 'this is foo\r'
	}
	public bar() => {
		return 'this is bar\r'
	}
	public _unknownTag(...) => {
		local(n = method_name->asString)
		return 'tried to handle unknown method called "'+#n+'"'+
			(#rest->size ? ' with args: "'+#rest->join(',')+'"')+'\r'
	}
}

local(e = exampletype)

#e->foo()
// outputs 'this is foo'

#e->bar()
// outputs 'this is bar'

#e->stuff()
// outputs 'tried to handle unknown method called "stuff"'

#e->dothis('here',12,'there','nowhere')
// outputs 'tried to handle unknown method called "dothis" with args: "here,12,there,nowhere"'


program RomanNumeralsEncode;

{$APPTYPE CONSOLE}

function IntegerToRoman(aValue: Integer): string;
var
  i: Integer;
const
  WEIGHTS: array[0..12] of Integer = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1);
  SYMBOLS: array[0..12] of string = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I');
begin
  for i := Low(WEIGHTS) to High(WEIGHTS) do
  begin
    while aValue >= WEIGHTS[i] do
    begin
      Result := Result + SYMBOLS[i];
      aValue := aValue - WEIGHTS[i];
    end;
    if aValue = 0 then
      Break;
  end;
end;

begin
  Writeln(IntegerToRoman(1990)); // MCMXC
  Writeln(IntegerToRoman(2008)); // MMVIII
  Writeln(IntegerToRoman(1666)); // MDCLXVI
end.


USING: combinators formatting io kernel math math.ranges qw
random sequences ;
IN: rosetta-code.rock-paper-scissors

CONSTANT: thing qw{ rock paper scissors }
CONSTANT: msg { "I win." "Tie!" "You win." }

: ai-choice ( r p s -- n )
    3dup + + nip [1,b] random {
        { [ 3dup nip >= ] [ 3drop 1 ] }
        { [ 3dup [ + ] dip >= ] [ 3drop 2 ] }
        [ 3drop 0 ]
    } cond ;

: player-choice ( -- n )
    "r/p/s/q? " write readln qw{ r p s q } index dup
    [ drop player-choice ] unless ;

! return:
! -1 for n1 loses to n2.
!  0 for n1 ties n2.
!  1 for n1 beats n2.
: outcome ( n1 n2 -- n3 ) - dup abs 1 > [ neg ] when sgn ;

: status. ( seq -- )
    "My wins: %d  Ties: %d  Your wins: %d\n" vprintf ;

: choices. ( n1 n2 -- )
    [ thing nth ] [email protected] "You chose: %s\nI chose: %s\n" printf ;

: tally ( seq n -- seq' ) over [ 1 + ] change-nth ;

: game ( seq -- seq' )
    dup status. player-choice dup 3 = [ drop ] [
        [ 3 + tally ] keep over 3 tail* first3 ai-choice 2dup
        choices. outcome 1 + dup [ tally ] dip msg nth print nl
        game
    ] if ;

! The game state is a sequence where the members are:
! losses, ties, wins, #rock, #paper, #scissors
: main ( -- ) { 0 0 0 1 1 1 } clone game drop ;

MAIN: main


include random.fs

0 value aiwins
0 value plwins

10 constant inlim
0  constant rock
1  constant paper
2  constant scissors

create rpshistory 0 , 0 , 0 ,
create inversemove 1 , 2 , 0 ,
3 constant historylen

: @a ( n array -- )
    swap cells + @ ;

: sum-history ( -- n )
    0 historylen 0 ?do
	i rpshistory @a 1+ + loop ;

: probable-choice ( -- n ) \ Simple linear search
    sum-history random
    historylen 0 ?do
	i rpshistory @a -
	dup 0< if drop i leave then
    loop inversemove @a ;

: rps-print ( addr u -- )
    cr type ;

: rpslog. ( -- )
    s"       ROCK    PAPER   SCISSORS  AI/W  PL/W" rps-print cr
    3 0 do i cells rpshistory + @ 9 u.r  loop aiwins 7 u.r plwins 6 u.r cr ;

create rpswords ' rock , ' paper , ' scissors , ' quit ,

: update-history! ( n -- )
    cells rpshistory + 1 swap +! ;

: thrown. ( n -- addr u )
    cells rpswords + @ name>string ;

: throws. ( n n -- )
    thrown. s" AI threw:  " 2swap s+ rps-print
    thrown. s" You threw: " 2swap s+ rps-print ;

: print-throws ( n n -- )
    rpslog. throws. ;

: tie. ( n n -- )
    s" Tie. " rps-print ;

: plwin ( n n -- )
    1 +to plwins s" You win. " rps-print ;

: aiwin ( n n -- )
    1 +to aiwins s" AI wins. " rps-print ;

create rpsstates ' tie. , ' plwin , ' aiwin ,

: determine-winner ( n n -- )
    >r abs r> abs - 3 + 3 mod
    cells rpsstates + @  execute ;

: rps-validate ( name -- )  ( Rude way of checking for only valid commands )
    4 0 do i cells rpswords + @ over = swap loop drop or or or ;

: rps-prompt. ( -- )
    s" Enter choice (rock, paper, scissors or quit):   " rps-print ;

: player-choice ( -- n ) recursive
    pad inlim accept pad swap find-name
    dup rps-validate if execute
    else drop rps-prompt. player-choice then ;

: update-log ( n n -- )
    update-history! update-history! ;

: rps ( -- ) recursive
    rps-prompt. player-choice probable-choice
    2dup update-log 2dup print-throws
    determine-winner rps ;


! compilation
! gfortran -std=f2008 -Wall -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f
!
! EXAMPLE
!
!$ ./f
!rock, paper, scissors?  papier
!scoring computer choice (r) and your choice (p)
!rock, paper, scissors?  sizzerz
!scoring computer choice (s) and your choice (s)
!rock, paper, scissors?  quit
!scoring computer choice (r) and your choice (q)
! Who's keeping score anyway???
!  0.5  1.5
! you won!
!$

program rpsgame

  integer, parameter :: COMPUTER=1, HAPLESSUSER=2
  integer, dimension(3) :: rps = (/1,1,1/)
  real, dimension(3) :: p
  character :: answer, cc ! computer choice
  integer :: exhaustion, i
  real, dimension(2) :: score = (/0, 0/)
  character(len=8), dimension(3) :: choices = (/'rock    ','paper   ','scissors'/)
  real :: harvest
  do exhaustion = 1, 30
    p = rps/real(sum(rps))
    p(2) = p(2) + p(1)
    p(3) = p(3) + p(2)
    call random_number(harvest)
    i = sum(merge(1,0,harvest.le.p)) ! In memory of Ken Iverson, logical is more useful as integer.
    cc = 'rsp'(i:i)
    write(6, "(2(A,', '),A,'?  ')", advance='no')(trim(choices(i)),i=1,size(choices))
    read(5, *) answer
    write(6, "('scoring computer choice (',A,') and your choice (',A,')')")cc,answer
    if (answer.eq.cc) then
      score = score + 0.5
    else
      i = HAPLESSUSER
      if (answer.eq.'r') then
        if (cc.eq.'p') i = COMPUTER
      else if (answer.eq.'p') then
        if (cc.eq.'s') i = COMPUTER
      else if (answer.eq.'s') then
        if (cc.eq.'r') i = COMPUTER
      else
        exit
      endif
      score(i) = score(i) + 1
    end if
    i = scan('rps',answer)
    rps(i) = rps(i) + 1
  end do
  if (25 .lt. exhaustion) write(6, *) "I'm bored out of my skull"
  write(6, *)"Who's keeping score anyway???"
  write(6, '(2f5.1)') score
  if (score(COMPUTER) .lt. score(HAPLESSUSER)) print*,'you won!'
end program rpsgame


:- object(foo).

	:- public(try/0).
	try :-
		catch(bar::message, Error, handler(Error)).

	handler(error(existence_error(predicate_declaration,message/0),_)) :-
		% handle the unknown message
		...

:- end_object.


local object={print=print}
setmetatable(object,{__index=function(t,k)return function() print("You called the method",k)end end})
object.print("Hi") -->Hi
object.hello() -->You called the method hello


module checkit  {

      Class Alfa {
            k=1000
            module a (x, y) {
                  Print x, y
            }
            module NoParam {
                  Print "ok"
            }
            Function Sqr(x) {
                  =Sqrt(x)
            }
            Function NoParam {
                  =.k
            }
            Function Sqr$(x) {
                  =Str$(Sqrt(x),1033)  ' using locale 1033, no leading space for positive
            }
      }
      \\ modules, functions numeric and string, and variables can use same name
      \\ here we have module invoke, function invoke, and function invoke$
      Module invoke (&a, method$) {
            param=(,)
            Read ? param
            Function Check(&a, method$) {
                  group b type "module "+method$+" {}"
                   =valid(@a as b)
            }
            if check(&a, method$) then {
                        for a {
                              \\ we call this.methodname
                              call "."+method$, !param
                        }
            }  else  Flush : Error  "unknown method "+method$   ' flush empty the stack
      }
      Function invoke (&a, method$) {
            \\ functions have own stack of values
            Function Check(&a, method$) {
                  group b type "Function "+filter$(method$, "()")+" {}"
                   =valid(@a as b)
            }
            if check(&a, method$) then {
                        for a {
                              =Function("."+method$, ![])
                        }
            }  else  Error  "unknown Function "+method$
      }
      \\ invoke string functions
      Function invoke$ (&a, method$) {
            \\ functions have own stack of values
            Function Check(&a, method$) {
                  group b type "Function "+filter$(method$, "()")+" {}"
                   =valid(@a as b)
            }
            if check(&a, method$) then {
                        for a {
                              \\ [] is a function which return current stack as a stack object, and pass to current stack a new stack object.
                              =Function$("."+method$, ![])
                        }
            }  else  Error  "unknown Function "+method$
      }

      Module obj.alfa {
            Flush 'empty stack
            Print "this is a fake module, is not part of obj"
      }
      Function obj.alfa {
                  Print "this is a fake function, is not part of obj"
      }
      Obj=Alfa()
      \\ normal invoke, interpreter not know that this is an object method
      \\ this method has a weak reference to obj, so anytime we use This. or just dot, this weak reference make the real name to execute
      Obj.a 10,20
      \\ call the fake method (can't access object methods and properties), has empty weak reference to object
      obj.alfa 10, 20

      \\ check before call using custom invoke
      \\ to check if a method (module) exist, we have to compare this object with other temporary object
      \\ we make one with the method name and empty definition, and then check if obj has anything this temp object has
      \\ arguments passed in a tuple (optional), so we didn't leave stack with unused items, if we have an unknown method.
      invoke &obj, "a", (10, 20)
      invoke &obj, "NoParam"
      \\ now with an unknown method, using alfa
      Try ok {
            invoke &obj, "Alfa", (10, 20)
      }
      If Error Then Print Error$
      \\ we can use invoke for functions
      Print Invoke(&obj, "Sqr()", 4), Invoke(&obj, "NoParam()")
      Print Invoke$(&obj, "Sqr$()",2)
      \ without custom invoke
      Print obj.Sqr(4), obj.Noparam(), obj.Sqr$(2)
      \\ so now we try to call Alfa() and Alfa$()  (unknown functions)
      Try ok {
            Print Invoke(&obj, "Alfa()")
      }
      If Error Then Print Error$
      Try ok {
            Print Invoke$(&obj, "Alfa$()")
      }
      If Error Then Print Error$

      \\ so now lets copy obj to obj2
      \\ fake method didn't passed to new object
      obj2=obj
      Try ok {
            invoke &obj2, "alfa", (10, 20)
      }
      If Error Then Print Error$

      p->obj2
      \\ if p is a pointer to named group we can pass it as is
      invoke &p, "a", (10, 20)
      \\ normal called
      p=>a 10,20

      For p {
            invoke &this, "a", (10, 20)
            Try ok {
                  invoke &this, "alfa", (10, 20)
            }
            If Error Then Print Error$
      }

      p->(obj2)   ' p point to a copy of obj2 (an unnamed group)
      For p {
            invoke &this, "a", (10, 20)
            \\ normal called
            p=>a 10, 20
            Try ok {
                  invoke &this, "alfa", (10, 20)
            }
            If Error Then Print Error$

      }

}
checkit


obj[foo] = "This is foo.";
obj[bar] = "This is bar.";
obj[f_Symbol] := "What is " <> SymbolName[f] <> "?";
Print[[email protected]];
Print[[email protected]];
Print[[email protected]];


{.experimental:"dotOperators".}
from strutils import join

type Foo = object

proc qux(f:Foo) = echo "called qux"

#for nicer output
func quoteStrings[T](x:T):string = (when T is string: "\"" & x & "\"" else: $x)

#dot operator catches all unmatched calls on Foo
template `.()`(f:Foo,field:untyped,args:varargs[string,quoteStrings]):untyped =
  echo "tried to call method '" & astToStr(`field`) & (if `args`.len > 0: "' with args: " & args.join(", ") else: "'")

let f = Foo()
f.bar()
#f.bar  #error: undeclared field
f.baz("hi",5)
f.qux()
f.qux("nope")


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

function toRoman(n : Integer) : String;
var
   i, w : Integer;
begin
   for i := 0 to weights.High do begin
      w := weights[i];
      while n >= w do begin
         Result += symbols[i];
         n -= w;
      end;
      if n = 0 then Break;
   end;
end;

PrintLn(toRoman(455));
PrintLn(toRoman(3456));
PrintLn(toRoman(2488));


Dim Shared As Byte ganador = 1, accion = 2, perdedor = 3, wp, wc
Dim Shared As String word(10, 3)
For n As Byte = 0 To 9
    Read word(n, ganador), word(n, accion), word(n, perdedor)
Next n

Sub SimonSay(n As Byte)
    Print Using "\       \  \        \  "; word(n, ganador); word(n, accion); word(n, perdedor)
End Sub

Sub Puntuacion()
    Print !"\nPlayer = "; wp; !"\tComputer = "; wc; !"\n"
End Sub

Dim As Byte n
Dim As String*1 k
Dim As String eleccionCPU, eleccionJUG
Randomize Timer
Do
    Cls
    eleccionCPU = word(Rnd *10, ganador)

    Print !"'Rock, Paper, Scissors, Lizard, Spock!' rules are:\n"
    For n = 0 To 9
        SimonSay(n)
    Next n

    Print !"\nType your choice letter:"
    Input !"(R)ock, (P)aper, (S)cissors, (L)izard, Spoc(K), (Q)uit  ", k

    k = Ucase(k)
    Select Case k
    Case "Q"
        Exit Do
    Case "R"
        eleccionJUG = "Rock"
    Case "P"
        eleccionJUG = "Paper"
    Case "S"
        eleccionJUG = "Scissors"
    Case "L"
        eleccionJUG = "Lizard"
    Case "K"
        eleccionJUG = "Spock"
    End Select

    Print !"\nPlayer chose "; eleccionJUG; " and Computer chose "; eleccionCPU
    For n = 0 To 9
        If word(n, ganador) = eleccionJUG And word(n, perdedor) = eleccionCPU Then
            SimonSay(n)
            Print !"\nWinner was Player"
            wp += 1
            Exit For
        Elseif word(n, ganador) = eleccionCPU And word(n, perdedor) = eleccionJUG Then
            SimonSay(n)
            Print !"\nWinner was Computer"
            wc += 1
            Exit For
        End If
    Next n
    If n = 10 Then Print !"\nOuch!"

    Puntuacion()
    Print "Press <SPACE> to continue"
    Sleep
Loop Until(k = "Q")

Cls
Puntuacion()
If wp > wc Then
    Print "Player win"
Elseif wc > wp Then
    Print "Computer win"
Else
    Print "Tie"
End If
Sleep
End

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"


type
  Tanimal = class
  public
    procedure bark(); virtual; abstract;
  end;

implementation

var
  animal: Tanimal;

initialization

  animal := Tanimal.Create;
  animal.bark(); // abstract method call exception at runtime here
  animal.Free;

end.


#include <Foundation/Foundation.h>

// The methods need to be declared somewhere
@interface Dummy : NSObject
- (void)grill;
- (void)ding:(NSString *)s;
@end

@interface Example : NSObject
- (void)foo;
- (void)bar;
@end

@implementation Example
- (void)foo {
  NSLog(@"this is foo");
}

- (void)bar {
  NSLog(@"this is bar");
}

- (void)forwardInvocation:(NSInvocation *)inv {
  NSLog(@"tried to handle unknown method %@", NSStringFromSelector([inv selector]));
  NSUInteger n = [[inv methodSignature] numberOfArguments];
  for (NSUInteger i = 0; i < n-2; i++) { // First two arguments are the object and selector.
    id __unsafe_unretained arg;          // We assume that all arguments are objects.
                                         // getArguments: is type-agnostic and does not perform memory management,
                                         //   therefore we must pass it a pointer to an unretained type
    [inv getArgument:&arg atIndex:i+2];
    NSLog(@"argument #%lu: %@", i, arg);
  }
}

// forwardInvocation: does not work without methodSignatureForSelector:
// The runtime uses the signature returned here to construct the invocation.
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector {
  int numArgs = [[NSStringFromSelector(aSelector) componentsSeparatedByString:@":"] count] - 1;
  // we assume that all arguments are objects
  // The type encoding is "[email protected]:@@@...", where "v" is the return type, void
  // "@" is the receiver, object type; ":" is the selector of the current method;
  // and each "@" after corresponds to an object argument
  return [NSMethodSignature signatureWithObjCTypes:
          [[@"[email protected]:" stringByPaddingToLength:numArgs+3 withString:@"@" startingAtIndex:0] UTF8String]];
}
@end

int main()
{
  @autoreleasepool {

    id example = [[Example alloc] init];

    [example foo];          // prints "this is foo"
    [example bar];          // prints "this is bar"
    [example grill];        // prints "tried to handle unknown method grill"
    [example ding:@"dong"]; // prints "tried to handle unknown method ding:"
                            // prints "argument #0: dong"

  }
  return 0;
}


values[] = [ 1000 900 500 400 100 90 50 40 10 9 5 4 1 ]
symbol$[] = [ "M" "CM" "D" "CD" "C" "XC" "L" "XL" "X" "IX" "V" "IV" "I" ]
func num2rom num . rom$ .
  rom$ = ""
  for i range len values[]
    while num >= values[i]
      rom$ &= symbol$[i]
      num -= values[i]
    .
  .
.
call num2rom 1990 r$
print r$
call num2rom 2008 r$
print r$
call num2rom 1666 r$
print r$


RomanEncode(UNSIGNED Int) := FUNCTION
  SetWeights := [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
  SetSymbols := ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
  ProcessRec := RECORD
    UNSIGNED val;
    STRING Roman;
  END;
  dsWeights  := DATASET(13,TRANSFORM(ProcessRec,SELF.val := Int, SELF := []));

  SymbolStr(i,n,STRING s) := CHOOSE(n+1,'',SetSymbols[i],SetSymbols[i]+SetSymbols[i],SetSymbols[i]+SetSymbols[i]+SetSymbols[i],s);

  RECORDOF(dsWeights) XF(dsWeights L, dsWeights R, INTEGER C) := TRANSFORM
    ThisVal := IF(C=1,R.Val,L.Val);
    IsDone := ThisVal = 0;
    SELF.Roman := IF(IsDone,L.Roman,L.Roman + SymbolStr(C,ThisVal DIV SetWeights[C],L.Roman));
    SELF.val := IF(IsDone,0,ThisVal - ((ThisVal DIV SetWeights[C])*SetWeights[C]));
  END;
  i := ITERATE(dsWeights,XF(LEFT,RIGHT,COUNTER));
  RETURN i[13].Roman;
END;

RomanEncode(1954);  //MCMLIV
RomanEncode(1990 ); //MCMXC
RomanEncode(2008 ); //MMVIII
RomanEncode(1666);  //MDCLXVI


if var.end=0 then
var.end=0
var.computerchoice=random(3) // 1 is rock, 2 is paper, and 3 is scissors.
debug="Press the R key for rock, the P key for paper, or the S key for scissors:"
endif
if pressed(Key.R)and var.end=0 then
   var.end=1
   if var.computerchoice=1 then
      debug="You chose rock, which the computer also chose, so it's a tie!"
   else
      if var.computerchoice=2 then
         debug="The computer chose paper, covering your choice of rock, so you lose!"
      else
         debug="You chose rock, smashing the computer's choice of scissors, so you win!"
      endif
   endif
endif
if pressed(Key.P)and var.end=0 then
   var.end=1
   if var.computerchoice=1 then
      debug="You chose paper, covering the computer's choice of rock, so you win!"
   else
      if var.computerchoice=2 then
         debug="You chose paper, which the computer also chose, so it's a tie!"
      else
         debug="The computer chose scissors, cutting your choice of paper, so you lose!"
      endif
   endif
endif
if pressed(Key.S)and var.end=0 then
   var.end=1
   if var.computerchoice=1 then
      debug="The computer chose rock, smashing your choice of scissors, so you lose!"
   else
      if var.computerchoice=2 then
         debug="You chose scissors, cutting the computer's choice of paper, so you win!"
      else
         debug="You chose scissors, which the computer also chose, so it's a tie!"
      endif
   endif
endif


package main

import (
    "fmt"
    "math/rand"
    "strings"
    "time"
)

const rps = "rps"

var msg = []string{
    "Rock breaks scissors",
    "Paper covers rock",
    "Scissors cut paper",
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println("Rock Paper Scissors")
    fmt.Println("Enter r, p, or s as your play.  Anything else ends the game.")
    fmt.Println("Running score shown as <your wins>:<my wins>")
    var pi string // player input
    var aScore, pScore int
    sl := 3               // for output alignment
    pcf := make([]int, 3) // pcf = player choice frequency
    var plays int
    aChoice := rand.Intn(3) // ai choice for first play is completely random
    for {
        // get player choice
        fmt.Print("Play: ")
        _, err := fmt.Scanln(&pi)  // lazy
        if err != nil || len(pi) != 1 {
            break
        }
        pChoice := strings.Index(rps, pi)
        if pChoice < 0 {
            break
        }
        pcf[pChoice]++
        plays++

        // show result of play
        fmt.Printf("My play:%s%c.  ", strings.Repeat(" ", sl-2), rps[aChoice])
        switch (aChoice - pChoice + 3) % 3 {
        case 0:
            fmt.Println("Tie.")
        case 1:
            fmt.Printf("%s.  My point.\n", msg[aChoice])
            aScore++
        case 2:
            fmt.Printf("%s.  Your point.\n", msg[pChoice])
            pScore++
        }

        // show score
        sl, _ = fmt.Printf("%d:%d  ", pScore, aScore)

        // compute ai choice for next play
        switch rn := rand.Intn(plays); {
        case rn < pcf[0]:
            aChoice = 1
        case rn < pcf[0]+pcf[1]:
            aChoice = 2
        default:
            aChoice = 0
        }
    }
}


1 first
[1:interpreter] ExRuntime : 1 does not understand method <#first>


u = .unknown~new
u~foo(1, 2, 3)

::class unknown
::method unknown
  use arg name, args
  say "Unknown method" name "invoked with arguments:" args~tostring('l',', ')


declare
  class Example
     meth init skip end

     meth foo {System.showInfo foo} end

     meth bar {System.showInfo bar} end

     meth otherwise(Msg)
        {System.showInfo "Unknown method "#{Label Msg}}
        if {Width Msg} > 0 then
           {System.printInfo "Arguments: "}
           {System.show {Record.toListInd Msg}}
        end
     end
  end

  Object = {New Example init}
 in
  {Object foo}
  {Object bar}
  {Object grill}
  {Object ding(dong)}


package Example;
sub new {
    bless {}
}
sub foo {
    print "this is foo\n";
}
sub bar {
    print "this is bar\n";
}
sub AUTOLOAD {
    my $name = $Example::AUTOLOAD;
    my ($self, @args) = @_;
    print "tried to handle unknown method $name\n";
    if (@args) {
        print "it had arguments: @args\n";
    }
}
sub DESTROY {}          # dummy method to prevent AUTOLOAD from
                        # being triggered when an Example is
                        # destroyed

package main;
my $example = Example->new;

$example->foo;          # prints "this is foo"
$example->bar;          # prints "this is bar"
$example->grill;        # prints "tried to handle unknown method Example::grill"
$example->ding("dong"); # prints "tried to handle unknown method Example::ding"
                        # and "it had arguments: dong"


class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
		local
			numbers: ARRAY [INTEGER]
		do
			numbers := <<1990, 2008, 1666, 3159, 1977, 2010>>
				   -- "MCMXC", "MMVIII", "MDCLXVI", "MMMCLIX", "MCMLXXVII", "MMX"
			across numbers as n loop
				print (n.item.out + " in decimal Arabic numerals is " +
				       decimal_to_roman (n.item) + " in Roman numerals.%N")
			end
		end

feature -- Roman numerals

	decimal_to_roman (a_int: INTEGER): STRING
		-- Representation of integer `a_int' as Roman numeral
		require
			a_int > 0
		local
			dnums: ARRAY[INTEGER]
			rnums: ARRAY[STRING]

			dnum: INTEGER
			rnum: STRING

			i: INTEGER
		do
			dnums := <<1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1>>
			rnums := <<"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I">>

			dnum := a_int
			rnum := ""

			from
				i := 1
			until
				i > dnums.count or dnum <= 0
			loop
				from
				until
					dnum < dnums[i]
				loop
					dnum := dnum - dnums[i]
					rnum := rnum + rnums[i]
				end
				i := i + 1
			end

			Result := rnum
		end
end


import System.Random (randomRIO)

data Choice
  = Rock
  | Paper
  | Scissors
  deriving (Show, Eq)

beats :: Choice -> Choice -> Bool
beats Paper Rock = True
beats Scissors Paper = True
beats Rock Scissors = True
beats _ _ = False

genrps :: (Int, Int, Int) -> IO Choice
genrps (r, p, s) = rps <$> rand
  where
    rps x
      | x <= s = Rock
      | x <= s + r = Paper
      | otherwise = Scissors
    rand = randomRIO (1, r + p + s) :: IO Int

getrps :: IO Choice
getrps = rps <$> getLine
  where
    rps "scissors" = Scissors
    rps "rock" = Rock
    rps "paper" = Paper
    rps _ = error "invalid input"

game :: (Int, Int, Int) -> IO a
game (r, p, s) = do
  putStrLn "rock, paper or scissors?"
  h <- getrps
  c <- genrps (r, p, s)
  putStrLn ("Player: " ++ show h ++ " Computer: " ++ show c)
  putStrLn
    (if beats h c
       then "player wins\n"
       else if beats c h
              then "player loses\n"
              else "draw\n")
  let rr =
        if h == Rock
          then r + 1
          else r
      pp =
        if h == Paper
          then p + 1
          else p
      ss =
        if h == Scissors
          then s + 1
          else s
  game (rr, pp, ss)

main :: IO a
main = game (1, 1, 1)


with javascript_semantics
enum METHODS

function invoke(object o, string name, sequence args={})
--(this works on any class, for any function, with any number or type of parameters)
    integer mdict = o[METHODS]
    integer node = getd_index(name,mdict)
    if node!=0 then
        return call_func(getd_by_index(node,mdict),args)
    end if
    return "no such method" -- or throw(), fatal(), etc
end function

--class X: Xmethods emulates a vtable
constant Xmethods = new_dict()

function exists()
    return "exists"
end function

setd("exists",routine_id("exists"),Xmethods)

--class X: create new instances
function newX()
    return {Xmethods}
end function

object x = newX()

?invoke(x,"exists")
?invoke(x,"non_existent_method")


<?php
class Example {
  function foo() {
    echo "this is foo\n";
  }
  function bar() {
    echo "this is bar\n";
  }
  function __call($name, $args) {
    echo "tried to handle unknown method $name\n";
    if ($args)
      echo "it had arguments: ", implode(', ', $args), "\n";
  }
}

$example = new Example();

$example->foo();        // prints "this is foo"
$example->bar();        // prints "this is bar"
$example->grill();      // prints "tried to handle unknown method grill"
$example->ding("dong"); // prints "tried to handle unknown method ding"
                        // prints "it had arguments: dong
?>


(redef send (Msg Obj . @)
   (or
      (pass try Msg Obj)
      (pass 'no-applicable-method> Obj Msg) ) )

(de no-applicable-method> (This Msg)
   (pack "No method for " Msg " on " This) )

(class +A)

(dm do-something> ()
   (pack "Do something to " This) )


open number string math

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]] :
  (toInt k - 1)

toRoman 0 = ""
toRoman x | x < 0     = fail "Negative roman numeral"
          | x >= 1000 = 'M' :: toRoman (x - 1000)
          | x >= 100  = let (q,r) = x `divrem` 100 in
                        digit 'C' 'D' 'M' q ++ toRoman r
          | x >= 10   = let (q,r) = x `divrem` 10 in
                        digit 'X' 'L' 'C' q ++ toRoman r
          | else = digit 'I' 'V' 'X' x

map (join "" << toRoman) [1999,25,944]


import system'collections;
import system'routines;
import extensions;
import extensions'text;

static RomanDictionary = Dictionary.new()
                            .setAt(1000, "M")
                            .setAt(900, "CM")
                            .setAt(500, "D")
                            .setAt(400, "CD")
                            .setAt(100, "C")
                            .setAt(90, "XC")
                            .setAt(50, "L")
                            .setAt(40, "XL")
                            .setAt(10, "X")
                            .setAt(9, "IX")
                            .setAt(5, "V")
                            .setAt(4, "IV")
                            .setAt(1, "I");

extension op
{
    toRoman()
        = RomanDictionary.accumulate(new StringWriter("I", self), (m,kv => m.replace(new StringWriter("I",kv.Key), kv.Value)));
}

public program()
{
    console.printLine("1990 : ", 1990.toRoman());
    console.printLine("2008 : ", 2008.toRoman());
    console.printLine("1666 : ", 1666.toRoman())
}


link printf

procedure main()

printf("Welcome to Rock, Paper, Scissors.\n_
        Rock beats scissors, Scissors beat paper, and Paper beats rock.\n\n")

historyP := ["rock","paper","scissors"]      # seed player history
winP := winC := draws := 0                   # totals

beats := ["rock","scissors","paper","rock"]  # what beats what 1 apart

repeat {
   printf("Enter your choice or rock(r), paper(p), scissors(s) or quit(q):")
   turnP := case map(read()) of {
      "q"|"quit": break
      "r"|"rock": "rock"
      "p"|"paper": "paper"
      "s"|"scissors": "scissors"
      default:  printf(" - invalid choice.\n") & next
      }

   turnC := beats[(?historyP == beats[i := 2 to *beats],i-1)]  # choose move

   put(historyP,turnP)                       # record history
   printf("You chose %s, computer chose %s",turnP,turnC)

   (beats[p := 1 to *beats] == turnP) &
      (beats[c := 1 to *beats] == turnC) & (abs(p-c) <= 1)  # rank play

   if p = c then
      printf(" - draw (#%d)\n",draws +:= 1 )
   else if p > c then
      printf(" - player win(#%d)\n",winP +:= 1)
   else
      printf(" - computer win(#%d)\n",winC +:= 1)
   }

printf("\nResults:\n %d rounds\n %d Draws\n %d Computer wins\n %d Player wins\n",
   winP+winC+draws,draws,winC,winP)
end


class CatchAll
{
    mixed `->(string name)
    {
        return lambda(int arg){ write("you are calling %s(%d);\n", name, arg); };
    }
}

> CatchAll()->hello(5);
you are calling hello(5);
> CatchAll()->something(99);
you are calling something(99);


class Example(object):
    def foo(self):
        print("this is foo")
    def bar(self):
        print("this is bar")
    def __getattr__(self, name):
        def method(*args):
            print("tried to handle unknown method " + name)
            if args:
                print("it had arguments: " + str(args))
        return method

example = Example()

example.foo()        # prints “this is foo”
example.bar()        # prints “this is bar”
example.grill()      # prints “tried to handle unknown method grill”
example.ding("dong") # prints “tried to handle unknown method ding”
                     # prints “it had arguments: ('dong',)”


#lang racket

(require racket/class)

(define-syntax-rule (send~ obj method x ...)
  ;; note: this is a naive macro, a real one should avoid evaluating `obj' and
  ;; the `xs' more than once
  (with-handlers ([(λ(e) (and (exn:fail:object? e)
                              ;; only do this if there *is* an `unknown-method'
                              (memq 'unknown-method (interface->method-names
                                                     (object-interface o)))))
                   (λ(e) (send obj unknown-method 'method x ...))])
    (send obj method x ...)))

(define foo%
  (class object%
    (define/public (foo x)
      (printf "foo: ~s\n" x))
    (define/public (unknown-method name . xs)
      (printf "Unknown method ~s: ~s\n" name xs))
    (super-new)))

(define o (new foo%))
(send~ o foo 1) ; => foo: 1
(send~ o whatever 1) ; Unknown method whatever: (1)


class Farragut {
    method FALLBACK ($name, *@rest) {
        say "{self.WHAT.raku}: $name.tc() the @rest[], full speed ahead!";
    }
}

class Sparrow is Farragut { }

Farragut.damn: 'torpedoes';
Sparrow.hoist: <Jolly Roger mateys>;


defmodule Roman_numeral do
  def encode(0), do: ''
  def encode(x) when x >= 1000, do: [?M | encode(x - 1000)]
  def encode(x) when x >= 100,  do: digit(div(x,100), ?C, ?D, ?M) ++ encode(rem(x,100))
  def encode(x) when x >= 10,   do: digit(div(x,10), ?X, ?L, ?C) ++ encode(rem(x,10))
  def encode(x) when x >= 1,    do: digit(x, ?I, ?V, ?X)

  defp digit(1, x, _, _), do: [x]
  defp digit(2, x, _, _), do: [x, x]
  defp digit(3, x, _, _), do: [x, x, x]
  defp digit(4, x, y, _), do: [x, y]
  defp digit(5, _, y, _), do: [y]
  defp digit(6, x, y, _), do: [y, x]
  defp digit(7, x, y, _), do: [y, x, x]
  defp digit(8, x, y, _), do: [y, x, x, x]
  defp digit(9, x, _, z), do: [x, z]
end


100 PROGRAM "Rock.bas"
110 RANDOMIZE
120 STRING CH$(1 TO 3)*8,K$*1
130 NUMERIC PLWINS(1 TO 3),SCORE(1 TO 3),PLSTAT(1 TO 3),CMSTAT(1 TO 3),PLCHOICE,CMCHOICE
140 CALL INIC
150 DO
160   CALL GUESS
170   PRINT :PRINT "Rock, paper, or scissors (1 = rock, 2 = paper, 3 = scissors, ESC = quit)"
180   DO
190     LET K$=INKEY$
200   LOOP UNTIL K$>="1" AND K$<="3" OR K$=CHR$(27)
210   IF K$=CHR$(27) THEN EXIT DO
220   LET PLCHOICE=VAL(K$)
230   LET CMSTAT(CMCHOICE)=CMSTAT(CMCHOICE)+1:LET PLSTAT(PLCHOICE)=PLSTAT(PLCHOICE)+1
240   PRINT "You chose ";CH$(PLCHOICE);" and I chose ";CH$(CMCHOICE);"."
250   SET #102:INK 3
260   IF PLCHOICE=CMCHOICE THEN
270     PRINT "Tie!"
280     LET SCORE(3)=SCORE(3)+1
290   ELSE IF CMCHOICE=PLWINS(PLCHOICE) THEN
300     PRINT "You won!"
310     LET SCORE(1)=SCORE(1)+1
320   ELSE
330     PRINT "I won!"
340     LET SCORE(2)=SCORE(2)+1
350   END IF
360   SET #102:INK 1
370 LOOP
380 PRINT :PRINT "Some useless statistics:"
390 PRINT "You won";SCORE(1);"times, and I won";SCORE(2);"times;";SCORE(3);"ties."
400 PRINT :PRINT ,,CH$(1),CH$(2),CH$(3)
410 PRINT "You chose:",PLSTAT(1),PLSTAT(2),PLSTAT(3)
420 PRINT "  I chose:",CMSTAT(1),CMSTAT(2),CMSTAT(3)
430 END
440 DEF INIC
450   LET CH$(1)="rock":LET CH$(2)="paper":LET CH$(3)="scissors"
460   LET PLWINS(1)=3:LET PLWINS(2)=1:LET PLWINS(3)=2
470   FOR I=1 TO 3
480     LET PLSTAT(I),CMSTAT(I),SCORE(I)=0
490   NEXT
500   TEXT 80
510 END DEF
520 DEF GUESS
530   LET CMCHOICE=INT(RND*(PLSTAT(1)+PLSTAT(2)+PLSTAT(3)+3))
540   SELECT CASE CMCHOICE
550   CASE 0 TO PLSTAT(1)
560     LET CMCHOICE=2
570   CASE PLSTAT(1)+1 TO PLSTAT(1)+PLSTAT(2)+1
580     LET CMCHOICE=3
590   CASE ELSE
600     LET CMCHOICE=1
610   END SELECT
620 END DEF


require'general/misc/prompt strings' NB. was 'misc strings' in older versions of J
game=:3 :0
  outcomes=. rps=. 0 0 0
  choice=. 1+?3
  while.#response=. prompt'  Choose Rock, Paper or Scissors: ' do.
    playerchoice=. 1+'rps' i. tolower {.deb response
    if.4 = playerchoice do.
      smoutput 'Unknown response.'
      smoutput 'Enter an empty line to quit'
      continue.
    end.
    smoutput '    I choose ',choice {::;:'. Rock Paper Scissors'
    smoutput (wintype=. 3 | choice-playerchoice) {:: 'Draw';'I win';'You win'
    outcomes=. outcomes+0 1 2 = wintype
    rps=. rps+1 2 3=playerchoice
    choice=. 1+3|(?0) I.~ (}:%{:)+/\ 0, rps
  end.
  ('Draws:','My wins:',:'Your wins: '),.":,.outcomes
)


load "stdlibcore.ring"

new test {
    anyMethodThatDoesNotExist()	# Define and call the new method
    anyMethodThatDoesNotExist()	# Call the new method
}

class test
      func braceerror
           if substr(cCatchError,"Error (R3)")
	      ? "You are calling a method that doesn't exist!"
	      aError = Split(cCatchError," ")
	      cMethodName = aError[len(aError)]
	      ? "The Method Name: " + cMethodName
	      AddMethod(self,cMethodName,func {
		        ? "Hello from the new method!"
	                })
	      ? "We defined the new method!"
	      call cMethodName()
           ok


class Example
    def foo
        puts "this is foo"
    end
    def bar
        puts "this is bar"
    end
    def method_missing(name, *args, &block)
        puts "tried to handle unknown method %s" % name # name is a symbol
        unless args.empty?
            puts "it had arguments: %p" % [args]
        end
    end
end

example = Example.new

example.foo          # prints “this is foo”
example.bar          # prints “this is bar”
example.grill        # prints “tried to handle unknown method grill”
example.ding("dong") # prints “tried to handle unknown method ding”
                     # prints “it had arguments: ["dong"]”


class DynamicTest extends Dynamic
{
  def foo()=println("this is foo")
  def bar()=println("this is bar")
  def applyDynamic(name: String)(args: Any*)={
    println("tried to handle unknown method "+name)
    if(!args.isEmpty)
      println("  it had arguments: "+args.mkString(","))
  }
}

object DynamicTest {
  def main(args: Array[String]): Unit = {
    val d=new DynamicTest()
    d.foo()
    d.bar()
    d.grill()
    d.ding("dong")
  }
}


class Example {
    method foo {
        say "this is foo"
    }
    method bar {
        say "this is bar"
    }
    method AUTOLOAD(_, name, *args) {
        say ("tried to handle unknown method %s" % name);
        if (args.len > 0) {
            say ("it had arguments: %s" % args.join(', '));
        }
    }
}

var example = Example.new;

example.foo;          # prints “this is foo”
example.bar;          # prints “this is bar”
example.grill;        # prints “tried to handle unknown method grill”
example.ding("dong"); # prints “tried to handle unknown method ding”
                      # prints “it had arguments: dong”


import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Random;

public class RPS {
	public enum Item{
		ROCK, PAPER, SCISSORS, /*LIZARD, SPOCK*/;
		public List<Item> losesToList;
		public boolean losesTo(Item other) {
			return losesToList.contains(other);
		}
		static {
			SCISSORS.losesToList = Arrays.asList(ROCK/*, SPOCK*/);
			ROCK.losesToList = Arrays.asList(PAPER/*, SPOCK*/);
			PAPER.losesToList = Arrays.asList(SCISSORS/*, LIZARD*/);
			/*
			SPOCK.losesToList = Arrays.asList(PAPER, LIZARD);
			LIZARD.losesToList = Arrays.asList(SCISSORS, ROCK);
			*/
                }
	}
	//EnumMap uses a simple array under the hood
	public final Map<Item, Integer> counts = new EnumMap<Item, Integer>(Item.class){{
		for(Item item:Item.values())
			put(item, 1);
	}};

	private int totalThrows = Item.values().length;

	public static void main(String[] args){
		RPS rps = new RPS();
		rps.run();
	}

	public void run() {
		Scanner in = new Scanner(System.in);
		System.out.print("Make your choice: ");
		while(in.hasNextLine()){
			Item aiChoice = getAIChoice();
			String input = in.nextLine();
			Item choice;
			try{
				choice = Item.valueOf(input.toUpperCase());
			}catch (IllegalArgumentException ex){
				System.out.println("Invalid choice");
				continue;
			}
			counts.put(choice, counts.get(choice) + 1);
			totalThrows++;
			System.out.println("Computer chose: " + aiChoice);
			if(aiChoice == choice){
				System.out.println("Tie!");
			}else if(aiChoice.losesTo(choice)){
				System.out.println("You chose...wisely. You win!");
			}else{
				System.out.println("You chose...poorly. You lose!");
			}
			System.out.print("Make your choice: ");
		}
	}

	private static final Random rng = new Random();
	private Item getAIChoice() {
		int rand = rng.nextInt(totalThrows);
		for(Map.Entry<Item, Integer> entry:counts.entrySet()){
			Item item = entry.getKey();
			int count = entry.getValue();
			if(rand < count){
				List<Item> losesTo = item.losesToList;
				return losesTo.get(rng.nextInt(losesTo.size()));
			}
			rand -= count;
		}
		return null;
	}
}


define: #shell &builder: [lobby newSubSpace].

[email protected] didNotUnderstand: message at: position
"Form a command string and execute it."
[
  position > 0
    ifTrue: [resend]
    ifFalse:
      [([| :command |
	message selector isUnarySelector ifTrue:
	  [command ; message selector.
	   message optionals pairsDo:
	     [| :key :value |
	      command ; ' -' ; (key as: String) allButFirst allButLast ; ' ' ; (value as: String)]].
	message selector isKeywordSelector ifTrue:
	  [| keywords args |
	   keywords: ((message selector as: String) splitWith: $:).
	   command ; keywords first.
	   keywords size = 1 ifTrue: "Read a string or array of arguments."
	     [args: message arguments second.
	      (args is: String) ifTrue: [command ; ' ' ; args]
				ifFalse: [args do: [| :arg | command ; ' ' ; arg]]]]] writingAs: String)
	 ifNil: [resend] ifNotNilDo: [| :cmd | [Platform run: cmd]]]
].


Object subclass: CatchThemAll [
    foo [ 'foo received' displayNl ]

    bar [ 'bar received' displayNl ]

    doesNotUnderstand: aMessage [
      ('message "' , (aMessage selector asString) , '"') displayNl.
      (aMessage arguments) do: [ :a |
        'argument: ' display. a printNl.
      ]
    ]
]

|a| a := CatchThemAll new.
a foo.
a bar.
a weCanDoIt.
a theyCanToo: 'eat' and: 'walk'.


Ingorabilis {

	tell {
		"I told you so".postln;
	}

	find {
		"I found nothing".postln
	}

	doesNotUnderstand { |selector ... args|
		"Method selector '%' not understood by %\n".postf(selector, this.class);
		"Giving you some good arguments in the following".postln;
		args.do { |x| x.postln };
		"And now I delegate the method to my respected superclass".postln;
		super.doesNotUnderstand(selector, args)
	}

}


package require TclOO
# First create a simple, conventional class and object
oo::class create Example {
    method foo {} {
        puts "this is foo"
    }
    method bar {} {
        puts "this is bar"
    }
}
Example create example

# Modify the object to have a custom ‘unknown method’ interceptor
oo::objdefine example {
    method unknown {name args} {
        puts "tried to handle unknown method \"$name\""
        if {[llength $args]} {
            puts "it had arguments: $args"
        }
    }
}

# Show off what we can now do...
example foo;       # prints “this is foo”
example bar;       # prints “this is bar”
example grill;     # prints “tried to handle unknown method "grill"”
example ding dong; # prints “tried to handle unknown method "ding"”
                   # prints “it had arguments: dong”


function handle_error {
  status=$?

  # 127 is: command not found
  if [[ $status -ne 127 ]]; then
    return
  fi

  lastcmd=$(history | tail -1 | sed 's/^ *[0-9]* *//')

  read cmd args <<< "$lastcmd"

  echo "you tried to call $cmd"
}

# Trap errors.
trap 'handle_error' ERR


PROGRAM ARAB2ROMAN

DIM ARABIC%[12],ROMAN$[12]

PROCEDURE TOROMAN(VALUE->ANS$)
LOCAL RESULT$
    FOR I%=0 TO 12 DO
        WHILE VALUE>=ARABIC%[I%] DO
            RESULT$+=ROMAN$[I%]
            VALUE-=ARABIC%[I%]
        END WHILE
    END FOR
    ANS$=RESULT$
END PROCEDURE

BEGIN
!
!Testing
!
   ARABIC%[]=(1000,900,500,400,100,90,50,40,10,9,5,4,1)
   ROMAN$[]=("M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I")
   TOROMAN(2009->ANS$) PRINT("2009 = ";ANS$)
   TOROMAN(1666->ANS$) PRINT("1666 = ";ANS$)
   TOROMAN(3888->ANS$) PRINT("3888 = ";ANS$)
END PROGRAM


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

function toRoman(integer val)
    sequence result
    result = ""
    for i = 1 to 13 do
        while val >= arabic[i] do
            result &= roman[i]
            val -= arabic[i]
        end while
    end for
    return result
end function

printf(1,"%d = %s\n",{2009,toRoman(2009)})
printf(1,"%d = %s\n",{1666,toRoman(1666)})
printf(1,"%d = %s\n",{3888,toRoman(3888)})


const logic = {
    rock: { w: 'scissor', l: 'paper'},
    paper: {w:'rock', l:'scissor'},
    scissor: {w:'paper', l:'rock'},
}

class Player {
    constructor(name){
        this.name = name;
    }
    setChoice(choice){
        this.choice = choice;
    }
    challengeOther(PlayerTwo){
        return logic[this.choice].w === PlayerTwo.choice;
    }
}

const p1 = new Player('Chris');
const p2 = new Player('John');

p1.setChoice('rock');
p2.setChoice('scissor');

p1.challengeOther(p2); //true (Win)


function rps()
	print("Welcome to Rock, paper, scissors! Go ahead and type your pick.\n
		r(ock), p(aper), or s(cissors)\n
		Enter 'q' to quit.\n>")
	comp_score = 0
	user_score = 0
	options = ["r","p","s"]
	new_pick() = options[rand(1:3)]
	i_win(m,y) = ((m == "r" && y == "s")|(m == "s" && y == "p")|(m == "p" && y == "r"))
	while true
		input = string(readline(STDIN)[1])
		input == "q" && break
		!ismatch(r"^[rps]",input) && begin print("Invalid guess: Please enter 'r', 'p', or 's'\n"); continue end
		answer = new_pick()
		if input == answer
			print("\nTie!\nScore still: \nyou $user_score\nme  $comp_score\n>")
			continue
		else
			i_win(answer,input) ? (comp_score += 1) : (user_score += 1)
			print(i_win(answer,input) ? "\nSorry you lose!\n" : "\nYou win!","Score: \nyou $user_score\nme  $comp_score\n>")
		end
	end
end


import "io" for Stdin, Stdout

class Test {
    construct new() {}

    foo() { System.print("Foo called.") }

    bar() { System.print("Bar called.") }

    missingMethod(m) {
        System.print(m)
        System.write("Try and continue anyway y/n ? ")
        Stdout.flush()
        var reply = Stdin.readLine()
        if (reply != "y" && reply != "Y") {
            Fiber.abort("Decided to abort due to missing method.")
        }
    }
}

var test = Test.new()
var f = Fiber.new {
    test.foo()
    test.bar()
    test.baz()
}
f.try()
var err = f.error
if (err) {
    if (err.startsWith("Test does not implement")) {
        test.missingMethod(err)
    } else {
        Fiber.abort(err) // rethrow other errors
    }
}
System.print("OK, continuing.")


class C{ fcn __notFound(name){println(name," not in ",self); bar}
   fcn bar{vm.arglist.println("***")}
}


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
  | _ -> failwith "invalid call to digit"

let rec to_roman acc = function
    | x when x >= 1000 -> to_roman (acc + "M") (x - 1000)
    | x when x >= 100 -> to_roman (acc + digit "C" "D" "M" (x / 100)) (x % 100)
    | x when x >= 10 -> to_roman (acc + digit "X" "L" "C" (x / 10)) (x % 10)
    | x when x > 0 -> acc + digit "I" "V" "X" x
    | 0 -> acc
    | _ -> failwith "invalid call to_roman (negative input)"

let roman n = to_roman "" n

[<EntryPoint>]
let main args =
    [1990; 2008; 1666]
    |> List.map (fun n -> roman n)
    |> List.iter (printfn "%s")
    0


// version 1.2.10

import java.util.Random

const val choices = "rpsq"
val rand = Random()

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

fun printScore() = println("Wins: You $pWins, Computer $cWins, Neither $draws\n")

fun getComputerChoice(): Char {
    // make a completely random choice until 3 games have been played
    if (games < 3) return choices[rand.nextInt(3)]
    val num = rand.nextInt(games)
    return when {
        num < pFreqs[0] -> 'p'
        num < pFreqs[0] + pFreqs[1] -> 's'
        else -> 'r'
    }
}

fun main(args: Array<String>) {
    println("Enter: (r)ock, (p)aper, (s)cissors or (q)uit\n")
    while (true) {
        printScore()
        var pChoice: Char
        while (true) {
            print("Your choice r/p/s/q : ")
            val input = readLine()!!.toLowerCase()
            if (input.length == 1) {
                pChoice = input[0]
                if (pChoice in choices) break
            }
            println("Invalid choice, try again")
        }
        if (pChoice == 'q') {
            println("OK, quitting")
            return
        }
        val cChoice = getComputerChoice()
        println("Computer's choice   : $cChoice")
        if (pChoice == 'r' && cChoice == 's') {
            println("Rock breaks scissors - You win!")
            pWins++
        }
        else if (pChoice == 'p' && cChoice == 'r') {
            println("Paper covers rock - You win!")
            pWins++
        }
        else if (pChoice == 's' && cChoice == 'p') {
            println("Scissors cut paper - You win!")
            pWins++
        }
        else if (pChoice == 's' && cChoice == 'r') {
            println("Rock breaks scissors - Computer wins!")
            cWins++
        }
        else if (pChoice == 'r' && cChoice == 'p') {
            println("Paper covers rock - Computer wins!")
            cWins++
        }
        else if (pChoice == 'p' && cChoice == 's') {
            println("Scissors cut paper - Computer wins!")
            cWins++
        }
        else {
            println("It's a draw!")
            draws++
        }
        pFreqs[choices.indexOf(pChoice)]++
        games++
        println()
    }
}


USE: roman
( scratchpad ) 3333 >roman .
"mmmcccxxxiii"


session_start('user')
session_addvar('user', 'historic_choices')
session_addvar('user', 'win_record')
session_addvar('user', 'plays')
var(historic_choices)->isNotA(::map) ? var(historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0))
var(plays)->isNotA(::integer) ? var(plays = 0)
var(win_record)->isNotA(::array) ? var(win_record = array)

define br => '
'
define winner(c::string,p::string) => {
	if(#c == $superior->find(#p)) => {
		$win_record->insert('lasso')
		return 'Lasso'
	else(#p == $superior->find(#c))
		$win_record->insert('user')
		return 'User'
	else
		$win_record->insert('tie')
		return 'Nobody'
		}
	}

	var(
		choice 				= web_request->param('choice')->asString,
	lookup 				= array('rock', 'paper', 'scissors'),
	computer_choice 	= $lookup->get(math_random(3,1)),
	superior			= map('rock'='paper', 'paper'='scissors', 'scissors'='rock'),
	controls			= 'Rock Paper Scissors Quit
'
)
if($choice == 'quit') => {^
	'See ya. Start over'
	session_end('user')
	$historic_choices = map('rock'=0, 'paper'=0, 'scissors'=0)
	$plays = 0
	$win_record = array

else(array('rock','paper','scissors') >> $choice)
		$controls

		if($plays != 0) => {
			local('possibilities') = array
			with i in $lookup do => {
				loop($historic_choices->find(#i)) => { #possibilities->insert(#i) }
			}

			$computer_choice = $superior->find(#possibilities->get(math_random($plays,1)))
		}

		'User chose ' + $choice + br
	'Lasso chose ' + $computer_choice + br
	winner($computer_choice->asString, $choice) + ' wins!'

		$historic_choices->find($choice) = $historic_choices->find($choice)+1
		$plays += 1

	else($choice->size == 0)
		$controls

	else
		'Invalid Choice.'+ br + $controls
^}
if($win_record->size) => {^
	br
	br
	'Win record: '+br
	'Lasso: '+($win_record->find('lasso')->size)+br
	'User: '+($win_record->find('user')->size)+br
	'Tie: '+($win_record->find('tie')->size)+br
^}


dim rps( 2), g$( 3)

g$( 0) ="rock": g$( 1) ="paper": g$( 2) ="scissors"
global total

total =0: draw  =0: pwin  =0: cwin  =0

rps( 0) =1: rps( 1) =1: rps( 2) =1          '   at first computer will play all three with equal probability

c =int( 3 *rnd( 1))                         '   first time, computer response is random

'   In the following code we set three integer %ages for the <human>'s biassed throws.
                                            '   set up the <human> player's key frequencies as %ages.
                                            '   Done like this it's easy to mimic the <human> input of q$
                                            '   It allows only integer %age frequency- not an important thing.
rockP =45                                   '   <<<<<<<<< Set here the <human>'s %age of 'rock' choices.
for i =1 to rockP: qF$ =qF$ +"R": next i

paprP =24                                    '   <<<<<<<<< Set here the %age of 'paper' choices.
for i =1 to paprP: qF$ =qF$ +"P": next i

scisP =100 -rockP -paprP                    '   <<<<<<<<< %age 'scissors' calculated to make 100%
for i =1 to scisP: qF$ =qF$ +"S": next i
'print qF$

do
  'do: input q$:loop until instr( "RPSrpsQq", q$)   '   for actual human input... possibly biassed.         <<<<<<<<<<<<< REM one or the other line...
  q$ =mid$( qF$, int( 100 *rnd( 1)), 1)              '   simulated <human> input with controlled bias.      <<<<<<<<<<<<<

  if total >10000 then q$ ="Q"

  g =int( ( instr( "RrPpSsQq", q$) -1) / 2)
  if g >2 then [endGame]

  total    =total   +1
  rps( g)  =rps( g) +1  '   accumulate plays the <human> has chosen. ( & hence their (biassed?) frequencies.)
  'print "  You chose "; g$( g); " and I chose "; g$( c); ". "

  select case g -c
    case 0
      draw =draw +1  ':print "It's a draw"
    case 1, -2
      pwin =pwin +1  ':print "You win!"
    case -1, 2
      cwin =cwin +1  ':print "I win!"
   end select

   r =int( total *rnd( 1))      '   Now select computer's choice for next confrontation.
   select case                  '   Using the accumulating data about <human>'s frequencies so far.
        case r <=rps( 0)
            c =1
        case r <=( rps( 0) +rps( 1))
            c =2
        case else
            c =0
   end select

   scan
loop until 0

[endGame]
    print
    print "  You won "; pwin; ", and I won "; cwin; ". There were "; draw; " draws."
    if cwin >pwin then print "      I AM THE CHAMPION!!" else print "        You won this time."
    print
    print "  At first I assumed you'd throw each equally often."
    print "  This means I'd win 1 time in 3; draw 1 in 3; lose 1 in 3."
    print "  However if I detect a bias in your throws,...."
    print "  ....this allows me to anticipate your most likely throw & on average beat it."
    print
    print "  In fact, keyboard layout & human frailty mean even if you TRY to be even & random..."
    print "  ... you may be typing replies with large bias. In 100 tries I gave 48 'P's, 29 'R' & 23 'S'!"
    print
    print "    This time I played.."
    print "      Rock "; using( "##.##", rps( 2)* 100 /total); "%    Paper "; using( "##.##", rps( 0) *100 /total); "%    Scissors "; using( "##.##", rps( 1) *100 /total); "%."
    print
    print "  ( PS. I have since learned your actual bias had been.."
    print "      Rock "; using( "##.##", rockP); "%    Paper "; using( "##.##", paprP ); "%    Scissors "; using( "##.##", ( 100 -rockP -paprP)); "%.)"
    print
    print "  The advantage I can gain gets bigger the further the 'human' entries are biassed."
    print "  The results statistically smooth out better with large runs."
    print "  Try 10,000,000, & have a cuppa while you wait."
    print
    print "  Can you see what will happen if, say, the 'human' is set to give 'Rock' EVERY time?"
    print "  Try different %ages by altering the marked code lines."
    print
    print "  Thanks for playing!"
    end


**
** converts a number to its roman numeral representation
**
class RomanNumerals
{

  private Str digit(Str x, Str y, Str z, Int i)
  {
    switch (i)
    {
      case 1: return x
      case 2: return x+x
      case 3: return x+x+x
      case 4: return x+y
      case 5: return y
      case 6: return y+x
      case 7: return y+x+x
      case 8: return y+x+x+x
      case 9: return x+z
    }
    return ""
  }

  Str toRoman(Int i)
  {
    if (i>=1000) { return "M" + toRoman(i-1000) }
    if (i>=100) { return digit("C", "D", "M", i/100) + toRoman(i%100) }
    if (i>=10) { return digit("X", "L", "C", i/10) + toRoman(i%10) }
    if (i>=1) { return digit("I", "V", "X", i) }
    return ""
  }

  Void main()
  {
    2000.times |i| { echo("$i = ${toRoman(i)}") }
  }

}


: vector create ( n -- ) 0 do , loop  does>  ( n -- ) swap cells + @ execute ;
\ these are ( numerals -- numerals )
: ,I  dup [email protected] C, ;  : ,V  dup 1 + [email protected] C, ;  : ,X  dup 2 + [email protected] C, ;

\ these are ( numerals -- )
:noname  ,I ,X     drop ;   :noname  ,V ,I ,I ,I  drop ;   :noname  ,V ,I ,I  drop ;
:noname  ,V ,I     drop ;   :noname  ,V           drop ;   :noname  ,I ,V     drop ;
:noname  ,I ,I ,I  drop ;   :noname  ,I ,I        drop ;   :noname  ,I        drop ;
' drop ( 0 : no output )  10 vector ,digit

: roman-rec ( numerals n -- )  10 /mod dup if >r over 2 + r> recurse else drop then ,digit ;
: roman ( n -- c-addr u )
  dup 0 4000 within 0= abort" EX LIMITO!"
  HERE SWAP  s" IVXLCDM" drop swap roman-rec  HERE OVER - ;

1999 roman type     \ MCMXCIX
  25 roman type     \ XXV
 944 roman type     \ CMXLIV


10 mode 1:defint a-z:randomize time
20 rps$="rps"
30 msg$(1)="Rock breaks scissors"
40 msg$(2)="Paper covers rock"
50 msg$(3)="Scissors cut paper"
60 print "Rock Paper Scissors":print
70 print "Enter r, p, or s as your play."
80 print "Running score shown as <your wins>:<my wins>"
90 achoice=rnd*2.99+.5 ' get integer between 1 and 3 from real between .5 and <3.5
100 ' get key
110 pin$=inkey$
120 if pin$="" then 110
130 pchoice=instr(rps$,pin$)
140 if pchoice=0 then print "Sorry?":goto 110
150 pcf(pchoice)=pcf(pchoice)+1
160 plays=plays+1
170 print "My play: "mid$(rps$,achoice,1)
180 sw=(achoice-pchoice+3) mod 3
190 if sw=0 then print "Tie." else if sw=1 then print msg$(achoice);". My point.":ascore=ascore+1 else print msg$(pchoice);". Your point.":pscore=pscore+1
200 print pscore":"ascore
210 rn=rnd*plays
220 if rn<pcf(1) then achoice=2 else if rn<pcf(1)+pcf(2) then achoice=3 else achoice=1
230 goto 110


function cpuMove()
  local totalChance = record.R + record.P + record.S
  if totalChance == 0 then  -- First game, unweighted random
    local choice = math.random(1, 3)
    if choice == 1 then return "R" end
    if choice == 2 then return "P" end
    if choice == 3 then return "S" end
  end
  local choice = math.random(1, totalChance)  -- Weighted random bit
  if choice <= record.R then return "P" end
  if choice <= record.R + record.P then return "S" end
  return "R"
end

function playerMove()  -- Get user input for choice of 'weapon'
  local choice
  repeat
    os.execute("cls")  -- Windows specific command, change per OS
    print("\nRock, Paper, Scissors")
    print("=====================\n")
    print("Scores -\tPlayer:", score.player)
    print("\t\tCPU:", score.cpu .. "\n\t\tDraws:", score.draws)
    io.write("\nChoose [R]ock [P]aper or [S]cissors: ")
    choice = io.read():upper():sub(1, 1)
  until choice == "R" or choice == "P" or choice == "S"
  return choice
end

-- Decide who won, increment scores
function checkWinner (c, p)
  io.write("I chose ")
  if c == "R" then print("rock...") end
  if c == "P" then print("paper...") end
  if c == "S" then print("scissors...") end
  if c == p then
    print("\nDraw!")
    score.draws = score.draws + 1
  elseif  (c == "R" and p == "P") or
      (c == "P" and p == "S") or
      (c == "S" and p == "R") then
        print("\nYou win!")
        score.player = score.player + 1
  else
    print("\nYou lose!")
    score.cpu = score.cpu + 1
  end
end

-- Main procedure
math.randomseed(os.time())
score = {player = 0, cpu = 0, draws = 0}
record = {R = 0, P = 0, S = 0}
local playerChoice, cpuChoice
repeat
  cpuChoice = cpuMove()
  playerChoice = playerMove()
  record[playerChoice] = record[playerChoice] + 1
  checkWinner(cpuChoice, playerChoice)
  io.write("\nPress ENTER to continue or enter 'Q' to quit . . . ")
until io.read():upper():sub(1, 1) == "Q"


program roman_numerals

  implicit none

  write (*, '(a)') roman (2009)
  write (*, '(a)') roman (1666)
  write (*, '(a)') roman (3888)

contains

function roman (n) result (r)

  implicit none
  integer, intent (in) :: n
  integer, parameter   :: d_max = 13
  integer              :: d
  integer              :: m
  integer              :: m_div
  character (32)       :: r
  integer,        dimension (d_max), parameter :: d_dec = &
    & (/1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1/)
  character (32), dimension (d_max), parameter :: d_rom = &
    & (/'M ', 'CM', 'D ', 'CD', 'C ', 'XC', 'L ', 'XL', 'X ', 'IX', 'V ', 'IV', 'I '/)

  r = ''
  m = n
  do d = 1, d_max
    m_div = m / d_dec (d)
    r = trim (r) // repeat (trim (d_rom (d)), m_div)
    m = m - d_dec (d) * m_div
  end do

end function roman

end program roman_numerals


DynamicModule[{record, play, text = "\nRock-paper-scissors\n",
  choices = {"Rock", "Paper", "Scissors"}},
 Evaluate[record /@ choices] = {1, 1, 1};
 play[x_] :=
  Module[{y = RandomChoice[record /@ choices -> [email protected]]},
   record[x]++;
   text = "Your Choice:" <> x <> "\nComputer's Choice:" <> y <> "\n" <>
      Switch[{x, y}, Alternatives @@ Partition[choices, 2, 1, 1],
      "You lost.",
      Alternatives @@ Reverse /@ Partition[choices, 2, 1, 1],
      "You win.", _, "Draw."]];
 [email protected]{Dynamic[text], ButtonBar[# :> play[#] & /@ choices]}]


:- module rps.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- use_module random, exception.
:- import_module list, string.

:- type play
    --->    rock
    ;       paper
    ;       scissors.

:- pred beats(play, play).
:- mode beats(in, in) is semidet.
beats(rock, scissors).
beats(paper, rock).
beats(scissors, paper).

:- pred random(play::out, random.supply::mdi, random.supply::muo) is det.
random(Play, !RS) :-
    random.random(1, 3, N, !RS),
    ( if N = 1 then
        Play = rock
    else if N = 2 then
        Play = paper
    else
        Play = scissors
    ).

main(!IO) :-
    seed(Seed, !IO),
    random.init(Seed, RS),
    play(RS, !IO).

:- pred play(random.supply::mdi, io::di, io::uo) is det.
play(!.RS, !IO) :-
    io.write_string("Your choice? ", !IO),
    io.read(Res, !IO),
    (
        Res = ok(Play),
        random(Counter, !RS),
        io.format("The computer chose %s\n", [s(string(Counter))], !IO),
        ( if beats(Counter, Play) then
            io.write_string("Computer wins.\n", !IO)
        else if beats(Play, Counter) then
            io.write_string("You win!\n", !IO)
        else
            io.write_string("It is a draw\n", !IO)
        ),
        play(!.RS, !IO)
    ;
        Res = eof
    ;
        Res = error(_, _),
        exception.throw(Res)
    ).

:- pragma foreign_decl("C", "#include <time.h>").
:- pred seed(int::out, io::di, io::uo) is det.
:- pragma foreign_proc("C",
    seed(Seed::out, _IO0::di, _IO::uo),
    [promise_pure, will_not_call_mercury],
"
    Seed = time(NULL);
").