import java.math.BigInteger
import kotlin.math.min

val one: BigInteger = BigInteger.ONE
val two: BigInteger = BigInteger.valueOf(2)
val three: BigInteger = BigInteger.valueOf(3)

fun pierpont(n: Int): List<List<BigInteger>> {
    val p = List(2) { MutableList(n) { BigInteger.ZERO } }
    p[0][0] = two
    var count = 0
    var count1 = 1
    var count2 = 0
    val s = mutableListOf<BigInteger>()
    s.add(one)
    var i2 = 0
    var i3 = 0
    var k = 1
    var n2: BigInteger
    var n3: BigInteger
    var t: BigInteger
    while (count < n) {
        n2 = s[i2] * two
        n3 = s[i3] * three
        if (n2 < n3) {
            t = n2
            i2++
        } else {
            t = n3
            i3++
        }
        if (t > s[k - 1]) {
            s.add(t)
            k++
            t += one
            if (count1 < n && t.isProbablePrime(10)) {
                p[0][count1] = t
                count1++
            }
            t -= two
            if (count2 < n && t.isProbablePrime(10)) {
                p[1][count2] = t
                count2++
            }
            count = min(count1, count2)
        }
    }
    return p
}

fun main() {
    val p = pierpont(2000)

    println("First 50 Pierpont primes of the first kind:")
    for (i in 0 until 50) {
        print("%8d ".format(p[0][i]))
        if ((i - 9) % 10 == 0) {
            println()
        }
    }

    println("\nFirst 50 Pierpont primes of the second kind:")
    for (i in 0 until 50) {
        print("%8d ".format(p[1][i]))
        if ((i - 9) % 10 == 0) {
            println()
        }
    }

    println("\n250th Pierpont prime of the first kind: ${p[0][249]}")
    println("\n250th Pierpont prime of the first kind: ${p[1][249]}")

    println("\n1000th Pierpont prime of the first kind: ${p[0][999]}")
    println("\n1000th Pierpont prime of the first kind: ${p[1][999]}")

    println("\n2000th Pierpont prime of the first kind: ${p[0][1999]}")
    println("\n2000th Pierpont prime of the first kind: ${p[1][1999]}")
}


local function isprime(n)
  if n < 2 then return false end
  if n % 2 == 0 then return n==2 end
  if n % 3 == 0 then return n==3 end
  local f, limit = 5, math.sqrt(n)
  for f = 5, limit, 6 do
    if n % f == 0 then return false end
    if n % (f+2) == 0 then return false end
  end
  return true
end

local function s3iter()
  local s, i2, i3 = {1}, 1, 1
  return function()
    local n2, n3, val = 2*s[i2], 3*s[i3], s[#s]
    s[#s+1] = math.min(n2, n3)
    i2, i3 = i2 + (n2<=n3 and 1 or 0), i3 + (n2>=n3 and 1 or 0)
    return val
  end
end

local function pierpont(n)
  local list1, list2, s3next = {}, {}, s3iter()
  while #list1 < n or #list2 < n do
    local s3 = s3next()
    if #list1 < n then
      if isprime(s3+1) then list1[#list1+1] = s3+1 end
    end
    if #list2 < n then
      if isprime(s3-1) then list2[#list2+1] = s3-1 end
    end
  end
  return list1, list2
end

local N = 50
local p1, p2 = pierpont(N)

print("First 50 Pierpont primes of the first kind:")
for i, p in ipairs(p1) do
  io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end

print()

print("First 50 Pierpont primes of the second kind:")
for i, p in ipairs(p2) do
  io.write(string.format("%8d%s", p, (i%10==0 and "\n" or " ")))
end


Module Pierpoint_Primes {
      Form 80
      Set Fast !
      const NPP=50
      dim pier(1 to 2, 1 to NPP), np(1 to 2) = 0
      def long x = 1, j
      while np(1)<=NPP or np(2)<=NPP
          x++
          j = @is_pierpont(x)
          if j>0 Else Continue
          if j mod 2 = 1 then np(1)++ :if np(1) <= NPP then pier(1, np(1)) = x
          if j > 1 then np(2)++ : if np(2) <= NPP then pier(2, np(2)) = x
      end while

      print "First ";NPP;" Pierpont primes of the first kind:"
      for j = 1 to NPP
          print pier(2, j),
      next j
      if pos>0 then print
      print "First ";NPP;" Pierpont primes of the second kind:"
      for j = 1 to NPP
          print pier(1, j),
      next j
      if pos>0 then print
      Set Fast
      function is_prime(n as decimal)
          if n < 2 then = false  : exit function
          if n <4 then = true : exit function
          if n mod 2 = 0 then = false : exit function
          local i as long
          for i = 3 to int(sqrt(n))+1 step 2
              if n mod i = 0 then = false  : exit function
          next i
          = true
      end function

      function is_23(n as long)
          while n mod 2 = 0
              n = n div 2
          end while
          while n mod 3 = 0
              n = n div 3
          end while
          if n = 1 then = true else = false
      end function

      function is_pierpont(n as long)
          if not @is_prime(n) then = 0& : exit function 'not prime
          Local p1 = @is_23(n+1), p2 = @is_23(n-1)
          if p1 and p2 then = 3  : exit function      'pierpont prime of both kinds
          if p1 then = 1 : exit function              'pierpont prime of the 1st kind
          if p2 then = 2 : exit function              'pierpont prime of the 2nd kind
          = 0                         'prime, but not pierpont
      end function
}
Pierpoint_Primes


ClearAll[FindUpToMax]
FindUpToMax[max_Integer, b_Integer] := Module[{res, num},
  res = {};
  Do[
   num = 2^u 3^v + b;
   If[PrimeQ[num], AppendTo[res, num]]
   ,
   {u, 0, [email protected][2, max]}
   ,
   {v, 0, [email protected][3, max]}
   ];
  res //= Select[LessEqualThan[max]];
  res //= Sort;
  res
  ]
Print["Piermont primes of the first kind:"]
Take[FindUpToMax[10^10, +1], UpTo[50]]
Print["Piermont primes of the second kind:"]
Take[FindUpToMax[10^10, -1], UpTo[50]]
Print["250th Piermont prime of the first kind:"]
Part[FindUpToMax[10^34, +1], 250]
Print["250th Piermont prime of the second kind:"]
Part[FindUpToMax[10^34, -1], 250]
Print["1000th Piermont prime of the first kind:"]
Part[FindUpToMax[10^130, +1], 1000]
Print["1000th Piermont prime of the second kind:"]
Part[FindUpToMax[10^150, -1], 1000]


import math, strutils

func isPrime(n: int): bool =
  ## Check if "n" is prime by trying successive divisions.
  ## "n" is supposed not to be a multiple of 2 or 3.
  var d = 5
  var delta = 2
  while d <= int(sqrt(n.toFloat)):
    if n mod d == 0: return false
    inc d, delta
    delta = 6 - delta
  result = true

func isProduct23(n: int): bool =
  ## Check if "n" has only 2 and 3 for prime divisors
  ## (i.e. that "n = 2^u * 3^v").
  var n = n
  while (n and 1) == 0: n = n shr 1
  while n mod 3 == 0: n = n div 3
  result = n == 1

iterator pierpont(maxCount: Positive; k: int): int =
  ## Yield the Pierpoint primes of first or second kind according
  ## to the value of "k" (+1 for first kind, -1 for second kind).
  yield 2
  yield 3
  var n = 5
  var delta = 2   # 2 and 4 alternatively to skip the multiples of 2 and 3.
  yield n
  var count = 3
  while count < maxCount:
    inc n, delta
    delta = 6 - delta
    if isProduct23(n - k) and isPrime(n):
      inc count
      yield n

template pierpont1*(maxCount: Positive): int = pierpont(maxCount, +1)
template pierpont2*(maxCount: Positive): int = pierpont(maxCount, -1)

when isMainModule:

  echo "First 50 Pierpont primes of the first kind:"
  var count = 0
  for n in pierpont1(50):
    stdout.write ($n).align(9)
    inc count
    if count mod 10 == 0: stdout.write '\n'

  echo ""
  echo "First 50 Pierpont primes of the second kind:"
  count = 0
  for n in pierpont2(50):
    stdout.write ($n).align(9)
    inc count
    if count mod 10 == 0: stdout.write '\n'


use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<is_prime>;

# index of mininum value in list
sub min_index { my $b = $_[my $i = 0]; $_[$_] < $b && ($b = $_[$i = $_]) for 0..$#_; $i }

sub iter1 { my $m = shift; my $e = 0; return sub { $m ** $e++;    } }
sub iter2 { my $m = shift; my $e = 1; return sub { $m * ($e *= 2) } }

sub pierpont {
    my($max ) = shift || die 'Must specify count of primes to generate.';
    my($kind) = @_ ? shift : 1;
    die "Unknown type: $kind. Must be one of 1 (default) or 2" unless $kind == 1 || $kind == 2;
    $kind = -1 if $kind == 2;

    my $po3     = 3;
    my $add_one = 3;
    my @iterators;
    push @iterators, iter1(2);
    push @iterators, iter1(3); $iterators[1]->();
    my @head = ($iterators[0]->(), $iterators[1]->());

    my @pierpont;
    do {
        my $key = min_index(@head);
        my $min = $head[$key];
        push @pierpont, $min + $kind if is_prime($min + $kind);

        $head[$key] = $iterators[$key]->();

        if ($min >= $add_one) {
            push @iterators, iter2($po3);
            $add_one = $head[$#iterators] = $iterators[$#iterators]->();
            $po3 *= 3;
        }
    } until @pierpont == $max;
    @pierpont;
}

my @pierpont_1st = pierpont(250,1);
my @pierpont_2nd = pierpont(250,2);

say "First 50 Pierpont primes of the first kind:";
my $fmt = "%9d"x10 . "\n";
for my $row (0..4) { printf $fmt, map { $pierpont_1st[10*$row + $_] } 0..9 }
say "\nFirst 50 Pierpont primes of the second kind:";
for my $row (0..4) { printf $fmt, map { $pierpont_2nd[10*$row + $_] } 0..9 }

say "\n250th Pierpont prime of the first kind:    " . $pierpont_1st[249];
say "\n250th Pierpont prime of the second kind: "   . $pierpont_2nd[249];


-- demo/rosetta/Pierpont_primes.exw
with javascript_semantics
include mpfr.e

function pierpont(integer n)
    sequence p = {{mpz_init(2)},{}},
             s = {mpz_init(1)}
    integer i2 = 1, i3 = 1
    mpz {n2, n3, t} = mpz_inits(3)
    atom t1 = time()+1
    while min(length(p[1]),length(p[2])) < n do
        mpz_mul_si(n2,s[i2],2)
        mpz_mul_si(n3,s[i3],3)
        if mpz_cmp(n2,n3)<0 then
            mpz_set(t,n2)
            i2 += 1
        else
            mpz_set(t,n3)
            i3 += 1
        end if
        if mpz_cmp(t,s[$]) > 0 then
            s = append(s, mpz_init_set(t))
            mpz_add_ui(t,t,1)
            if length(p[1]) < n and mpz_prime(t) then
                p[1] = append(p[1],mpz_init_set(t))
            end if
            mpz_sub_ui(t,t,2)
            if length(p[2]) < n and mpz_prime(t) then
                p[2] = append(p[2],mpz_init_set(t))
            end if
        end if
        if time()>t1 then
            printf(1,"Found: 1st:%d/%d, 2nd:%d/%d\r",
                     {length(p[1]),n,length(p[2]),n})
            t1 = time()+1
        end if
    end while
    return p
end function

--constant limit = 2000         -- 2 mins
--constant limit = 1000         -- 8.1s
constant limit = 250            -- 0.1s
atom t0 = time()
sequence p = pierpont(limit)
constant fs = {"first","second"}

for i=1 to length(fs) do
    printf(1,"First 50 Pierpont primes of the %s kind:\n",{fs[i]})
    for j=1 to 50 do
        printf(1,"%8s ", {mpz_get_str(p[i][j])})
        if mod(j,10)=0 then printf(1,"\n") end if
    end for
    printf(1,"\n")
end for

constant t = {250,1000,2000}
for i=1 to length(t) do
    integer ti = t[i]
    if ti>limit then exit end if
    for j=1 to length(fs) do
        string zs = shorten(mpz_get_str(p[j][ti]))
        printf(1,"%dth Pierpont prime of the %s kind: %s\n",{ti,fs[j],zs})
    end for
    printf(1,"\n")
end for
printf(1,"Took %s\n", elapsed(time()-t0))


?- use_module(library(heaps)).

three_smooth(Lz) :-
    singleton_heap(H, 1, nothing),
    lazy_list(next_3smooth, 0-H, Lz).

next_3smooth(Top-H0, N-H2, N) :-
    min_of_heap(H0, Top, _), !,
    get_from_heap(H0, Top, _, H1),
    next_3smooth(Top-H1, N-H2, N).
next_3smooth(_-H0, N-H3, N) :-
    get_from_heap(H0, N, _, H1),
    N2 is N * 2,
    N3 is N * 3,
    add_to_heap(H1, N2, nothing, H2),
    add_to_heap(H2, N3, nothing, H3).

first_kind(K) :-
    three_smooth(Ns), member(N, Ns),
    K is N + 1,
    prime(K).

second_kind(K) :-
    three_smooth(Ns), member(N, Ns),
    K is N - 1,
    prime(K).

show(Seq, N) :-
    format("The first ~w values of ~s are: ", [N, Seq]),
    once(findnsols(N, X, call(Seq, X), L)),
    write(L), nl,
    once(offset(249, call(Seq, TwoFifty))),
    format("The 250th value of ~w is ~w~n", [Seq, TwoFifty]).

main :-
    show(first_kind, 50), nl,
    show(second_kind, 50), nl,
    halt.

% primality checker -- Miller Rabin preceded with a round of trial divisions.

prime(N) :-
    integer(N),
    N > 1,
    divcheck(
        N,
        [  2,   3,   5,   7,  11,  13,  17,  19,  23,  29,  31,
          37,  41,  43,  47,  53,  59,  61,  67,  71,  73,  79,
          83,  89,  97, 101, 103, 107, 109, 113, 127, 131, 137,
         139, 149],
        Result),
    ((Result = prime, !); miller_rabin_primality_test(N)).

divcheck(_, [],    unknown) :- !.
divcheck(N, [P|_], prime) :- P*P > N, !.
divcheck(N, [P|Ps], State) :- N mod P =\= 0, divcheck(N, Ps, State).

miller_rabin_primality_test(N) :-
    bases(Bases, N),
    forall(member(A, Bases), strong_fermat_pseudoprime(N, A)).

miller_rabin_precision(16).

bases([31, 73], N) :- N < 9_080_191, !.
bases([2, 7, 61], N) :- N < 4_759_123_141, !.
bases([2, 325, 9_375, 28_178, 450_775, 9_780_504, 1_795_265_022], N) :-
    N < 18_446_744_073_709_551_616, !. % 2^64
bases(Bases, N) :-
    miller_rabin_precision(T), RndLimit is N - 2,
    length(Bases, T), maplist(random_between(2, RndLimit), Bases).

strong_fermat_pseudoprime(N, A) :-  % miller-rabin strong pseudoprime test with base A.
    succ(Pn, N), factor_2s(Pn, S, D),
    X is powm(A, D, N),
    ((X =:= 1, !); \+ composite_witness(N, S, X)).

composite_witness(_, 0, _) :- !.
composite_witness(N, K, X) :-
    X =\= N-1,
    succ(Pk, K), X2 is (X*X) mod N, composite_witness(N, Pk, X2).

factor_2s(N, S, D) :- factor_2s(0, N, S, D).
factor_2s(S, D, S, D) :- D /\ 1 =\= 0, !.
factor_2s(S0, D0, S, D) :-
    succ(S0, S1), D1 is D0 >> 1,
    factor_2s(S1, D1, S, D).

?- main.


import random

# Copied from https://rosettacode.org/wiki/Miller-Rabin_primality_test#Python
def is_Prime(n):
    """
    Miller-Rabin primality test.

    A return value of False means n is certainly not prime. A return value of
    True means n is very likely a prime.
    """
    if n!=int(n):
        return False
    n=int(n)
    #Miller-Rabin test for prime
    if n==0 or n==1 or n==4 or n==6 or n==8 or n==9:
        return False

    if n==2 or n==3 or n==5 or n==7:
        return True
    s = 0
    d = n-1
    while d%2==0:
        d>>=1
        s+=1
    assert(2**s * d == n-1)

    def trial_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True

    for i in range(8):#number of trials
        a = random.randrange(2, n)
        if trial_composite(a):
            return False

    return True

def pierpont(ulim, vlim, first):
    p = 0
    p2 = 1
    p3 = 1
    pp = []
    for v in xrange(vlim):
        for u in xrange(ulim):
            p = p2 * p3
            if first:
                p = p + 1
            else:
                p = p - 1
            if is_Prime(p):
                pp.append(p)
            p2 = p2 * 2
        p3 = p3 * 3
        p2 = 1
    pp.sort()
    return pp

def main():
    print "First 50 Pierpont primes of the first kind:"
    pp = pierpont(120, 80, True)
    for i in xrange(50):
        print "%8d " % pp[i],
        if (i - 9) % 10 == 0:
            print
    print "First 50 Pierpont primes of the second kind:"
    pp2 = pierpont(120, 80, False)
    for i in xrange(50):
        print "%8d " % pp2[i],
        if (i - 9) % 10 == 0:
            print
    print "250th Pierpont prime of the first kind:", pp[249]
    print "250th Pierpont prime of the second kind:", pp2[249]

main()


  [ stack ] is pierponts
  [ stack ] is kind
  [ stack ] is quantity

  [ 1 - -2 * 1+ kind put
    1+ quantity put
    ' [ -1 ] pierponts put
    ' [ 2 3 ] smoothwith
      [ -1 peek
        kind share +
        dup isprime not iff
          [ drop false ] done
        pierponts share -1 peek
        over = iff
          [ drop false ] done
        pierponts take
        swap join
        dup size swap
        pierponts put
        quantity share = ]
    drop
    quantity release
    kind release
    pierponts take
    behead drop ]                is pierpontprimes

  say "Pierpont primes of the first kind." cr
  50 1 pierpontprimes echo
  cr cr
  say "Pierpont primes of the second kind." cr
  50 2 pierpontprimes echo


use ntheory:from<Perl5> <is_prime>;

sub pierpont ($kind is copy = 1) {
    fail "Unknown type: $kind. Must be one of 1 (default) or 2" if $kind !== 1|2;
    $kind = -1 if $kind == 2;
    my $po3 = 3;
    my $add-one = 3;
    my @iterators = [1,2,4,8 … *].iterator, [3,9,27 … *].iterator;
    my @head = @iterators».pull-one;

    gather {
        loop {
            my $key = @head.pairs.min( *.value ).key;
            my $min = @head[$key];
            @head[$key] = @iterators[$key].pull-one;

            take $min + $kind if "{$min + $kind}".&is_prime;

            if $min >= $add-one {
                @iterators.push: ([|((2,4,8).map: * * $po3) … *]).iterator;
                $add-one = @head[+@iterators - 1] = @iterators[+@iterators - 1].pull-one;
                $po3 *= 3;
            }
        }
    }
}

say "First 50 Pierpont primes of the first kind:\n" ~ pierpont[^50].rotor(10)».fmt('%8d').join: "\n";

say "\nFirst 50 Pierpont primes of the second kind:\n" ~ pierpont(2)[^50].rotor(10)».fmt('%8d').join: "\n";

say "\n250th Pierpont prime of the first kind: " ~ pierpont[249];

say "\n250th Pierpont prime of the second kind: " ~ pierpont(2)[249];


/*REXX program finds and displays  Pierpont primes  of the  first  and  second  kinds.  */
parse arg n .                                    /*obtain optional argument from the CL.*/
if n=='' | n==","  then n= 50                    /*Not specified?  Then use the default.*/
numeric digits n                                 /*ensure enough decimal digs (bit int).*/
big= copies(9, digits() )                        /*BIG:  used as a max number (a limit).*/
@.= '2nd';                      @.1= '1st'
        do t=1  to -1  by -2;   usum= 0;   vsum= 0;    s= 0       /*T  is  1,  then  -1.*/
        #= 0                                     /*number of Pierpont primes  (so far). */
        $=;    do j=0  until #>=n                /*$:   the list  "  "      "      "    */
               if usum<=s  then usum= get(2, 3);    if vsum<=s  then vsum= get(3, 2)
               s= min(vsum, usum);  if \isPrime(s)  then iterate /*get min;  Not prime? */
               #= # + 1;            $= $ s                       /*bump counter; append.*/
               end   /*j*/
        say
        w= length(word($, #) )                                   /*biggest prime length.*/
        say center(n   " Pierpont primes of the "   @.t ' kind',  max(10 *(w+1), 80), "═")

          do p=1  by 10  to #;      _=;      do k=p  for 10;   _= _ right( word($, k),  w)
                                             end   /*k*/
          if _\==''  then say substr( strip(_, "T"),  2)
          end   /*p*/
        end     /*t*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure; parse arg x '' -1 _; if x<17  then return wordpos(x,"2 3 5 7 11 13")>0
         if _==5  then return 0;           if x//2==0  then return 0       /*not prime. */
         if x//3==0  then return 0;        if x//7==0  then return 0       /* "    "    */
            do j=11  by 6  until j*j>x                                     /*skip ÷ 3's.*/
            if x//j==0  then return 0;  if x//(j+2)==0  then return 0      /*not prime. */
            end   /*j*/;                                     return 1      /*it's prime.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
get: parse arg c1,c2; m=big;  do   ju=0;  pu= c1**ju;  if pu+t>s  then return min(m, pu+t)
                                do jv=0;  pv= c2**jv;  if pv  >s  then iterate ju
                                _= pu*pv  +  t;        if _   >s  then m= min(_, m)
                                end   /*jv*/
                              end     /*ju*/           /*see the    RETURN    (above).  */


load "stdlib.ring"

see "working..." + nl

pierpont = []
limit1 = 18
limit2 = 8505000
limit3 = 50
limit4 = 21
limit5 = 30500000

for n = 0 to limit1
    for m = 0 to limit1
        num = pow(2,n)*pow(3,m) + 1
        if isprime(num) and num < limit2
           add(pierpont,num)
        ok
        if num > limit2
           exit
        ok
     next
next

pierpont = sort(pierpont)

see "First 50 Pierpont primes of the first kind:" + nl + nl

for n = 1 to limit3
    see "" + n + ". " + pierpont[n] + nl
next

see "done1..." + nl

pierpont = []

for n = 0 to limit4
    for m = 0 to limit4
        num = pow(2,n)*pow(3,m) - 1
        if isprime(num) and num < limit5
           add(pierpont,num)
        ok
        if num > limit5
           exit
        ok
     next
next

pierpont = sort(pierpont)

see "First 50 Pierpont primes of the second kind:" + nl + nl

for n = 1 to limit3
    see "" + n + ". " + pierpont[n] + nl
next

see "done2..." + nl


require 'gmp'

def  smooth_generator(ar)
  return to_enum(__method__, ar) unless block_given?
  next_smooth = 1
  queues = ar.map{|num| [num, []] }
  loop do
    yield next_smooth
    queues.each {|m, queue| queue << next_smooth * m}
    next_smooth = queues.collect{|m, queue| queue.first}.min
    queues.each{|m, queue| queue.shift if queue.first == next_smooth }
  end
end

def pierpont(num = 1)
    return to_enum(__method__, num) unless block_given?
    smooth_generator([2,3]).each{|smooth| yield smooth+num if GMP::Z(smooth + num).probab_prime? > 0}
end

def puts_cols(ar, n=10)
  ar.each_slice(n).map{|slice|puts  slice.map{|n| n.to_s.rjust(10)}.join }
end

n, m = 50, 250
puts "First #{n} Pierpont primes of the first kind:"
puts_cols(pierpont.take(n))
puts "#{m}th Pierpont prime of the first kind: #{pierpont.take(250).last}",""
puts "First #{n} Pierpont primes of the second kind:"
puts_cols(pierpont(-1).take(n))
puts "#{m}th Pierpont prime of the second kind: #{pierpont(-1).take(250).last}"


func smooth_generator(primes) {
    var s = primes.len.of { [1] }
    {
        var n = s.map { .first }.min
        { |i|
            s[i].shift if (s[i][0] == n)
            s[i] << (n * primes[i])
        } * primes.len
        n
    }
}

func pierpont_primes(n, k = 1) {
    var g = smooth_generator([2,3])
    1..Inf -> lazy.map { g.run + k }.grep { .is_prime }.first(n)
}

say "First 50 Pierpont primes of the 1st kind: "
say pierpont_primes(50, +1).join(' ')

say "\nFirst 50 Pierpont primes of the 2nd kind: "
say pierpont_primes(50, -1).join(' ')

for n in (250, 500, 1000) {
    var p = pierpont_primes(n, +1).last
    var q = pierpont_primes(n, -1).last
    say "\n#{n}th Pierpont prime of the 1st kind: #{p}"
    say "#{n}th Pierpont prime of the 2nd kind: #{q}"
}


import BigInt
import Foundation

public func pierpoint(n: Int) -> (first: [BigInt], second: [BigInt]) {
  var primes = (first: [BigInt](repeating: 0, count: n), second: [BigInt](repeating: 0, count: n))

  primes.first[0] = 2

  var count1 = 1, count2 = 0
  var s = [BigInt(1)]
  var i2 = 0, i3 = 0, k = 1
  var n2 = BigInt(0), n3 = BigInt(0), t = BigInt(0)

  while min(count1, count2) < n {
    n2 = s[i2] * 2
    n3 = s[i3] * 3

    if n2 < n3 {
      t = n2
      i2 += 1
    } else {
      t = n3
      i3 += 1
    }

    if t <= s[k - 1] {
      continue
    }

    s.append(t)
    k += 1
    t += 1

    if count1 < n && t.isPrime(rounds: 10) {
      primes.first[count1] = t
      count1 += 1
    }

    t -= 2

    if count2 < n && t.isPrime(rounds: 10) {
      primes.second[count2] = t
      count2 += 1
    }
  }

  return primes
}

let primes = pierpoint(n: 250)

print("First 50 Pierpoint primes of the first kind: \(Array(primes.first.prefix(50)))\n")
print("First 50 Pierpoint primes of the second kind: \(Array(primes.second.prefix(50)))")
print()
print("250th Pierpoint prime of the first kind: \(primes.first[249])")
print("250th Pierpoint prime of the second kind: \(primes.second[249])")


import "/big" for BigInt
import "/fmt" for Fmt

var pierpont = Fn.new { |n, first|
    var p = [ List.filled(n, null), List.filled(n, null) ]
    for (i in 0...n) {
        p[0][i] = BigInt.zero
        p[1][i] = BigInt.zero
    }
    p[0][0] = BigInt.two
    var count  = 0
    var count1 = 1
    var count2 = 0
    var s = [BigInt.one]
    var i2 = 0
    var i3 = 0
    var k  = 1
    while (count < n) {
        var n2 = s[i2] * 2
        var n3 = s[i3] * 3
        var t
        if (n2 < n3) {
            t = n2
            i2 = i2 + 1
        } else {
            t = n3
            i3 = i3 + 1
        }
        if (t > s[k-1]) {
            s.add(t.copy())
            k = k + 1
            t = t.inc
            if (count1 < n && t.isProbablePrime(5)) {
                p[0][count1] = t.copy()
                count1 = count1 + 1
            }
            t = t - 2
            if (count2 < n && t.isProbablePrime(5)) {
                p[1][count2] = t.copy()
                count2 = count2 + 1
            }
            count = count1.min(count2)
        }
    }
    return p
}

var p = pierpont.call(250, true)
System.print("First 50 Pierpont primes of the first kind:")
for (i in 0...50) {
    Fmt.write("$8i ", p[0][i])
    if ((i-9)%10 == 0) System.print()
}
System.print("\nFirst 50 Pierpont primes of the second kind:")
for (i in 0...50) {
    Fmt.write("$8i ", p[1][i])
    if ((i-9)%10 == 0) System.print()
}

System.print("\n250th Pierpont prime of the first kind: %(p[0][249])")
System.print("\n250th Pierpont prime of the second kind: %(p[1][249])")


var [const] BI=Import("zklBigNum");  // libGMP
var [const] one=BI(1), two=BI(2), three=BI(3);

fcn pierPonts(n){  //-->((bigInt first kind primes) (bigInt second))
   pps1,pps2 := List(BI(2)), List();
   count1, count2, s := 1, 0, List(BI(1));  // n==2_000, s-->266_379 elements
   i2,i3,k := 0, 0, 1;
   n2,n3,t := BI(0),BI(0),BI(0);
   while(count1.min(count2) < n){
      n2.set(s[i2]).mul(two);	// .mul, .add, .sub are in-place
      n3.set(s[i3]).mul(three);
      if(n2<n3){ t.set(n2); i2+=1; }
      else     { t.set(n3); i3+=1; }
      if(t > s[k-1]){
	 s.append(t.copy());
	 k+=1;
	 t.add(one);
	 if(count1<n and t.probablyPrime()){
	    pps1.append(t.copy());
	    count1+=1;
	 }
	 if(count2<n and t.sub(two).probablyPrime()){
	    pps2.append(t.copy());
	    count2+=1;
	 }
      }
   }
   return(pps1,pps2)
}


with Pig; with Ada.Text_IO; with Ada.Command_Line;

procedure automatic_Pig is

   use Pig;

   type Robot is new Actor with record
      Bound: Natural := 20;
      Final_Run: Natural := 0;
   end record;
   function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean;

   function Roll_More(A: Robot; Self, Opponent: Player'Class) return Boolean is
     ((Self.All_Recent < A.Bound) or
         else (Opponent.Score-100 > A.Final_Run));

   function Arg(Position: Positive; Default: Natural) return Natural is
      package ACL renames Ada.Command_Line;
   begin
      return Natural'Value(ACL.Argument(Position));
   exception
      when Constraint_Error => return Default;
   end Arg;

   T: Robot := (Bound => Arg(2, 35), Final_Run => Arg(3, 0));
   F: Robot := (Bound => Arg(4, 20), Final_Run => Arg(5, 30));

   T_Wins: Boolean;
   Win_Count: array(Boolean) of Natural := (True=> 0, False => 0);
begin
   for I in 1 .. Arg(1, 1000) loop
      Play(T, F, T_Wins);
      Win_Count(T_Wins) := Win_Count(T_Wins) + 1;
   end loop;
   Ada.Text_IO.Put_Line(Natural'Image(Win_Count(True)) &
                          Natural'Image(Win_Count(False)));
end Automatic_Pig;


#NoEnv
SetBatchLines, -1
#SingleInstance, Force
#Include Pig_the_dice_game_Optimal_Play.ahkl ; comment if you don't want to bother
Play:=10000 ; this is enough to give 2 digits of accuracy in win ratio
Wins0:=Wins1:=0
Player0(TurnSum, SumMe, SumOpp) {
	Return practical(TurnSum, SumMe, SumOpp) ; set first player function name
}
Player1(TurnSum, SumMe, SumOpp) {
	Return optimal(TurnSum, SumMe, SumOpp) ; set second player function name
}

Loop, % Play
{
	;Random, FirstPlayer, 0, 1 ; to remove advantage of going first
	CurrentPlayer := 0 ; set to FirstPlayer to compare same players with different N's
	Sum0:=Sum1:=0
	Loop
	{
		OtherPlayer:=!CurrentPlayer
		If (Sum%CurrentPlayer%+TurnSum < 100
			and Player%CurrentPlayer%(TurnSum, Sum%CurrentPlayer%, Sum%OtherPlayer%))
		{
		; Roll
			Random, LastRoll, 1, 6
			If (LastRoll != 1)
			{
				TurnSum += LastRoll
				Continue
			}
			TurnSum := 0
		}
		; Hold
		Sum%CurrentPlayer% += TurnSum
		TurnSum := 0
		If (Sum%CurrentPlayer% >= 100)
		{
			Wins%CurrentPlayer%++
			Break
		}
		CurrentPlayer := !CurrentPlayer
	}
}
Msgbox % "Player 0 won " Round(Wins0/Play*100,0) "%`nPlayer 1 won " Round(Wins1/Play*100,0) "%"

; Random; 1/N is ~ probablity of holding
Random(TurnSum, SumMe, SumOpp, N=9) {
	Random, Roll, 0, N ; increase this last number to increase probability of rolling
	Return Roll
}
; Always roll
Always(TurnSum, SumMe, SumOpp) {
	Return 1
}
; Roll N times; N=6 beats all other RollNx players
RollNx(TurnSum, SumMe, SumOpp, N=6) {
	Static Roll=0
	Return Roll := TurnSum = 0 ? 1 : mod(Roll+1,N+1)
}
; Roll if TurnSum < N; N=19 beats all other RollToN players
RollToN(TurnSum, SumMe, SumOpp, N=19) {
	Return Roll := TurnSum < N
}
; Roll if SumOpp > N or SumMe > N or TurnSum < 21 + (SumOpp - SumMe) / 8
Practical(TurnSum, SumMe, SumOpp, N=72) {
	Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8
}
; Optimal play per http://cs.gettysburg.edu/~tneller/nsf/pig/pig.pdf
Optimal(TurnSum, SumMe, SumOpp) {
	Global Optimal
	Roll := Optimal[SumMe,TurnSum,SumOpp+1]
	Return Roll = "" ? 1 : Roll
}


(defclass player ()
    ((score :initform 0 :accessor score)
     (name :initarg :name :accessor name)))
(defun make-player (name)
  (make-instance 'player :name name))
(defmethod has-won ((player player))
  (>= (score player) 100))

(defclass score-based (player)
  ((score-base :initarg :score-base :initform 25 :accessor score-base)))
(defun make-score-based (name &optional (base 25))
  (make-instance 'score-based :score-base base :name name))
(defmethod roll-again ((player score-based) other turn-score)
  (declare (ignorable other))
  (< turn-score (score-base player)))

(defclass neller (player) ())
(defun make-neller (name) (make-instance 'neller :name name))
(defmethod roll-again ((player neller) other turn-score)
  (let ((other-score (score other)) (my-score (score player)))
     (or
      (> other-score 71)
      (> my-score 71)
      (< turn-score (+ 21 (/ (- other-score my-score) 8))))))

(defun query-turn (player other roll added-score)
  (format t "~A: Rolled a ~A - Turn: ~A Current Score: ~A Keep rolling (Y, N or Q)?"
    (name player)
    roll
    added-score
    (+ added-score (score player)))
  (let ((ret (roll-again player other added-score)))
    (if ret (format t "Y~%") (format t "N~%"))
    ret))

(defun do-turns (player other)
  (do ((new-score 0)
       (take-turn t))
      ((not take-turn) (setf (score player) (+ (score player) new-score)))
    (let ((roll (+ 1 (random 6))))
      (cond
       ((>= (+ (score player) roll new-score) 100)
        (format t "~A rolls a ~A and WINS!~%" (name player) roll)
        (setf new-score (+ new-score roll))
        (setf take-turn nil))
       ((eql 1 roll)
        (format t "Ooh!  Sorry - ~A rolled a 1 and busted!~%" (name player))
        (setf new-score 0)
        (setf take-turn nil))
       (t
        (setf new-score (+ new-score roll))
        (setf take-turn (query-turn player other roll new-score)))))))

(defun play-pig-winner (p1 p2)
    (do* ((otherplayer p2 curplayer)
          (curplayer p1 (if (eql curplayer p1) p2 p1)))
         ((has-won otherplayer) otherplayer)
      (do-turns curplayer otherplayer)))

(defun play-pig-player (player1 player2)
  (catch 'quit (format t "Hooray! ~A won the game!"


import std.stdio, std.random;

enum nPlayers = 4, maxPoints = 100;

enum Moves { roll, hold }

abstract class Player {
  public:
    final void addCurrScore() pure nothrow {
        current_score += round_score;
    }
    final int getCurrScore() const pure nothrow {
        return current_score;
    }
    final int getRoundScore() const pure nothrow {
        return round_score;
    }
    final void addRoundScore(in int rs) pure nothrow {
        round_score += rs;
    }
    final void zeroRoundScore() pure nothrow {
        round_score = 0;
    }
    Moves getMove();

  protected int current_score, round_score;
}

final class PlayerRand: Player {
    override Moves getMove() {
        if (round_score + current_score >= maxPoints)
            return Moves.hold;

        if (uniform(0, 2) == 0)
            return Moves.roll;
        if (round_score > 0)
            return Moves.hold;
        return Moves.roll;
    }
}

final class PlayerQ2Win: Player {
    override Moves getMove() {
        if (round_score + current_score >= maxPoints)
            return Moves.hold;

        int q = maxPoints - current_score;
        if (q < 6)
            return Moves.roll;
        q /= 4;
        if (round_score < q)
            return Moves.roll;
        return Moves.hold;
    }
}

final class PlayerAL20: Player {
    override Moves getMove() {
        if (round_score + current_score >= maxPoints)
            return Moves.hold;
        if (round_score < 20)
            return Moves.roll;
        return Moves.hold;
    }
}

final class PlayerAL20T: Player {
    override Moves getMove() {
        if (round_score + current_score >= maxPoints)
            return Moves.hold;

        immutable d = (100 * round_score) / 20;
        if (round_score < 20 && d < uniform(0, 100))
            return Moves.roll;
        return Moves.hold;
    }
}

void main() {
    auto players = [new PlayerRand, new PlayerQ2Win,
                    new PlayerAL20, new PlayerAL20T];

    void nextTurn(ref uint p) nothrow {
        players[p].zeroRoundScore;
        p = (p + 1) % nPlayers;
    }

    uint p = 0;
    bool endGame = false;

    while (!endGame) {
        final switch (players[p].getMove) {
            case Moves.roll:
                immutable die = uniform(1, 7);

                if (die == 1) {
                    writeln("Player ", p + 1, " rolled ", die,
                            " - current score: ",
                            players[p].getCurrScore, "\n");
                    nextTurn(p);
                    continue;
                }
                players[p].addRoundScore(die);
                writeln("Player ", p + 1, " rolled ", die,
                        " - round score: ",
                        players[p].getRoundScore);
                break;

            case Moves.hold:
                players[p].addCurrScore;
                writeln("Player ", p + 1,
                        " holds - current score: ",
                        players[p].getCurrScore, "\n");
                if (players[p].getCurrScore >= maxPoints)
                    endGame = true;
                else
                    nextTurn(p);

        }
    }

    writeln;
    writeln("Player   I (Rand):  ", players[0].getCurrScore);
    writeln("Player  II (Q2Win): ", players[1].getCurrScore);
    writeln("Player III (AL20):  ", players[2].getCurrScore);
    writeln("Player  IV (AL20T): ", players[3].getCurrScore, "\n\n");
}


-module( pig_dice_player ).

-export( [task/0] ).

task() ->
    Goal = pig_dice:goal(),
    Players_holds = [{"Player"++ erlang:integer_to_list(X), X} || X <- [5, 10, 15, 20]],
    Fun = fun ({Player, Total}, Dict) when Total >= Goal -> dict:update_counter( Player, 1, Dict );
        (_Player_total, Dict) -> Dict
        end,
    Dict = lists:foldl( Fun, dict:new(), task_play(Players_holds, Goal, []) ),
    display( dict:to_list(Dict) ).

display( Results ) ->
        [{Name, Total} | Rest] = lists:reverse( lists:keysort(2, Results) ),
        io:fwrite( "Winner is ~p with total of ~p wins~n", [Name, Total] ),
        io:fwrite( "Then follows: " ),
        [io:fwrite("~p with ~p~n", [N, T]) || {N, T} <- Rest].

is_goal_reached( Score, Player, Goal, Player, Game ) ->
        Score + proplists:get_value(Player, pig_dice:players_totals(Game)) >= Goal;
is_goal_reached( _Score, _Other_player, _Goal, _Player, _Game ) -> false.

loop( Hold, Hold, Goal, Player, Game ) ->
    pig_dice:hold( Player, Game ),
    loop( 1, Hold, Goal, Player, Game );
loop( N, Hold, Goal, Player, Game ) ->
    loop_await_my_turn( pig_dice:player_name(Game), Player, Game ),
    pig_dice:roll( Player, Game ),
    Is_goal_reached = is_goal_reached( pig_dice:score(Game), pig_dice:player_name(Game), Goal, Player, Game ),
    loop_done( Is_goal_reached, N, Hold, Goal, Player, Game ).

loop_await_my_turn( Player, Player, _Game ) -> ok;
loop_await_my_turn( _Other, Player, Game ) -> loop_await_my_turn( pig_dice:player_name(Game), Player, Game ).

loop_done( true, _N, _Hold, _Goal, Player, Game ) -> pig_dice:hold( Player, Game );
loop_done( false, N, Hold, Goal, Player, Game ) -> loop( N + 1, Hold, Goal, Player, Game ).

rotate(	[H | T] ) -> T ++ [H].

task_play( Players_holds, _Goal, Acc ) when erlang:length(Players_holds) =:= erlang:length(Acc) -> lists:flatten( Acc );
task_play( Players_holds, Goal, Acc ) ->
    Results = [task_play_n(Players_holds, Goal) || _X <- lists:seq(1, 100)],
    task_play( rotate(Players_holds), Goal, [Results | Acc] ).

task_play_n( Players_holds, Goal ) ->
    Game = pig_dice:game( [X || {X, _Y} <- Players_holds] ),
    Pids = [erlang:spawn(fun() -> loop(1, Y, Goal, X, Game) end) || {X, Y} <- Players_holds],
    receive
    {pig, Result, Game} ->
	[erlang:exit(X, kill) || X <- [Game | Pids]],
        Result
    end.


package pig

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

type (
	PlayerID   int
	MessageID  int
	StrategyID int

	PigGameData struct {
		player        PlayerID
		turnCount     int
		turnRollCount int
		turnScore     int
		lastRoll      int
		scores        [2]int
		verbose       bool
	}
)

const (
	// Status messages
	gameOver = iota
	piggedOut
	rolls
	pointSpending
	holds
	turn
	gameOverSummary
	// Players
	player1  = PlayerID(0)
	player2  = PlayerID(1)
	noPlayer = PlayerID(-1)
	// Max score
	maxScore = 100
	// Strategies
	scoreChaseStrat = iota
	rollCountStrat
)

// Returns "s" if n != 1
func pluralS(n int) string {
	if n != 1 {
		return "s"
	}
	return ""
}

// Creates an intializes a new PigGameData structure, returns a *PigGameData
func New() *PigGameData {
	return &PigGameData{0, 0, 0, 0, 0, [2]int{0, 0}, false}
}

// Create a status message for a given message ID
func (pg *PigGameData) statusMessage(id MessageID) string {
	var msg string
	switch id {
	case gameOver:
		msg = fmt.Sprintf("Game is over after %d turns", pg.turnCount)
	case piggedOut:
		msg = fmt.Sprintf("    Pigged out after %d roll%s", pg.turnRollCount, pluralS(pg.turnRollCount))
	case rolls:
		msg = fmt.Sprintf("    Rolls %d", pg.lastRoll)
	case pointSpending:
		msg = fmt.Sprintf("    %d point%s pending", pg.turnScore, pluralS(pg.turnScore))
	case holds:
		msg = fmt.Sprintf("    Holds after %d turns, adding %d points for a total of %d", pg.turnRollCount, pg.turnScore, pg.PlayerScore(noPlayer))
	case turn:
		msg = fmt.Sprintf("Player %d's turn:", pg.player+1)
	case gameOverSummary:
		msg = fmt.Sprintf("Game over after %d turns\n player 1 %d\n player 2 %d\n", pg.turnCount, pg.PlayerScore(player1), pg.PlayerScore(player2))
	}
	return msg
}

// Print a status message, if pg.Verbose is true
func (pg *PigGameData) PrintStatus(id MessageID) {
	if pg.verbose {
		fmt.Println(pg.statusMessage(id))
	}
}

// Play a given strategy
func (pg *PigGameData) Play(id StrategyID) (keepPlaying bool) {
	if pg.GameOver() {
		pg.PrintStatus(gameOver)
		return false
	}

	if pg.turnCount == 0 {
		pg.player = player2
		pg.NextPlayer()
	}

	pg.lastRoll = rand.Intn(6) + 1
	pg.PrintStatus(rolls)
	pg.turnRollCount++
	if pg.lastRoll == 1 {
		pg.PrintStatus(piggedOut)
		pg.NextPlayer()
	} else {
		pg.turnScore += pg.lastRoll
		pg.PrintStatus(pointSpending)
		success := false
		switch id {
		case scoreChaseStrat:
			success = pg.scoreChaseStrategy()
		case rollCountStrat:
			success = pg.rollCountStrategy()
		}
		if success {
			pg.Hold()
			pg.NextPlayer()
		}
	}
	return true
}

// Get the score for a given player
func (pg *PigGameData) PlayerScore(id PlayerID) int {
	if id == noPlayer {
		return pg.scores[pg.player]
	}
	return pg.scores[id]
}

// Check if the game is over
func (pg *PigGameData) GameOver() bool {
	return pg.scores[player1] >= maxScore || pg.scores[player2] >= maxScore
}

// Returns the Player ID if there is a winner, or -1
func (pg *PigGameData) Winner() PlayerID {
	for index, score := range pg.scores {
		if score >= maxScore {
			return PlayerID(index)
		}
	}
	return noPlayer
}

// Get the ID of the other player
func (pg *PigGameData) otherPlayer() PlayerID {
	// 0 becomes 1, 1 becomes 0
	return 1 - pg.player
}

func (pg *PigGameData) Hold() {
	pg.scores[pg.player] += pg.turnScore
	pg.PrintStatus(holds)
	pg.turnRollCount, pg.turnScore = 0, 0
}

func (pg *PigGameData) NextPlayer() {
	pg.turnCount++
	pg.turnRollCount, pg.turnScore = 0, 0
	pg.player = pg.otherPlayer()
	pg.PrintStatus(turn)
}

func (pg *PigGameData) rollCountStrategy() bool {
	return pg.turnRollCount >= 3
}

func (pg *PigGameData) scoreChaseStrategy() bool {
	myScore := pg.PlayerScore(pg.player)
	otherScore := pg.PlayerScore(pg.otherPlayer())
	myPendingScore := pg.turnScore + myScore
	return myPendingScore >= maxScore || myPendingScore > otherScore || pg.turnRollCount >= 5
}

// Run the simulation
func main() {
	// Seed the random number generator
	rand.Seed(time.Now().UnixNano())

	// Start a new game
	pg := New()
	pg.verbose = true
	strategies := [2]StrategyID{scoreChaseStrat, rollCountStrat}

	// Play until game over
	for !pg.GameOver() {
		pg.Play(strategies[pg.player])
	}
	pg.PrintStatus(gameOverSummary)
}


- player1 always rolls until he gets 20 or more
- player2 always rolls four times
- player3 rolls three times until she gets more than 60 points, then she rolls until she gets 20 or more
- player4 rolls 3/4 of the time, 1/4 he holds, but if he gets a score more than 75 he goes for the win


import java.util.Scanner;

public class Pigdice {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int players = 0;

		//Validate the input
		while(true) {
			//Get the number of players
			System.out.println("Hello, welcome to Pig Dice the game! How many players? ");
			if(scan.hasNextInt()) {

				//Gotta be more than 0
				int nextInt = scan.nextInt();
				if(nextInt > 0) {
					players = nextInt;
					break;
				}
			}
			else {
				System.out.println("That wasn't an integer. Try again. \n");
				scan.next();
			}
		}
		System.out.println("Alright, starting with " + players + " players. \n");

		//Start the game
		play(players, scan);

		scan.close();
	}

	public static void play(int group, Scanner scan) {
		//Set the number of strategies available.
		final int STRATEGIES = 5;

		//Construct the dice- accepts an int as an arg for number of sides, but defaults to 6.
		Dice dice = new Dice();

		//Create an array of players and initialize them to defaults.
		Player[] players = new Player[group];
		for(int count = 0; count < group; count++) {
			players[count] = new Player(count);
			System.out.println("Player " + players[count].getNumber() + "  is alive! ");
		}

		/*****Print strategy options here. Modify Player.java to add strategies. *****/
		System.out.println("Each strategy is numbered 0 - " + (STRATEGIES - 1) + ". They are as follows: ");
		System.out.println(">> Enter '0' for a human player. ");
		System.out.println(">> Strategy 1 is a basic strategy where the AI rolls until 20+ points and holds unless the current max is 75+.");
		System.out.println(">> Strategy 2 is a basic strategy where the AI, after 3 successful rolls, will randomly decide to roll or hold. ");
		System.out.println(">> Strategy 3 is similar to strategy 2, except it's a little gutsier and will attempt 5 successful rolls. ");
		System.out.println(">> Strategy 4 is like a mix between strategies 1 and 3. After turn points are >= 20 and while max points are still less than 75, it will randomly hold or roll. ");

		//Get the strategy for each player
		for(Player player : players) {
			System.out.println("\nWhat strategy would you like player " + player.getNumber() + " to use? ");

			//Validate the strategy is a real strategy.
			while(true) {
				if(scan.hasNextInt()) {
					int nextInt = scan.nextInt();
					if (nextInt < Strategy.STRATEGIES.length) {
						player.setStrategy(Strategy.STRATEGIES[nextInt]);
						break;
					}
				}
				else {
					System.out.println("That wasn't an option. Try again. ");
					scan.next();
				}
			}
		}

		//Here is where the rules for the game are programmatically defined.
		int max = 0;
		while(max < 100) {

			//Begin the round
			for(Player player : players) {
				System.out.println(">> Beginning Player " + player.getNumber() + "'s turn. ");

				//Set the points for the turn to 0
				player.setTurnPoints(0);

				//Determine whether the player chooses to roll or hold.
				player.setMax(max);
				while(true) {
					Move choice = player.choose();
					if(choice == Move.ROLL) {
						int roll = dice.roll();
						System.out.println("   A " + roll + " was rolled. ");
						player.setTurnPoints(player.getTurnPoints() + roll);

						//Increment the player's built in iterator.
						player.incIter();

						//If the player rolls a 1, their turn is over and they gain 0 points this round.
						if(roll == 1) {
							player.setTurnPoints(0);
							break;
						}
					}
					//Check if the player held or not.
					else {
						System.out.println("   The player has held. ");
						break;
					}
				}

				//End the turn and add any accumulated points to the player's pool.
				player.addPoints(player.getTurnPoints());
				System.out.println("   Player " + player.getNumber() + "'s turn is now over. Their total is " + player.getPoints() + ". \n");

				//Reset the player's built in iterator.
				player.resetIter();

				//Update the max score if necessary.
				if(max < player.getPoints()) {
					max = player.getPoints();
				}

				//If someone won, stop the game and announce the winner.
				if(max >= 100) {
					System.out.println("Player " + player.getNumber() + " wins with " + max + " points! End scores: ");

					//Announce the final scores.
					for(Player p : players) {
						System.out.println("Player " + p.getNumber() + " had " + p.getPoints() + " points. ");
					}
					break;
				}
			}
		}

	}

}


mutable struct Player
    score::Int
    ante::Int
    wins::Int
    losses::Int
    strategy::Pair{String, Function}
end

randomchoicetostop(player, group) = rand(Bool)
variablerandtostop(player, group) = any(x -> x.score > player.score, group) ? rand() < 0.1 : rand(Bool)
overtwentystop(player, group) = player.ante > 20
over20unlesslosingstop(player, group) = player.ante > 20 && all(x -> x.score < 80, group)

const strategies = ("random choice to stop" => randomchoicetostop, "variable rand to stop" => variablerandtostop,
                  "roll to 20" => overtwentystop, "roll to 20 then if not losing stop" => over20unlesslosingstop)
const players = [Player(0, 0, 0, 0, s) for s in strategies]
const dice = collect(1:6)

function turn(player, verbose=false)
    playernum = findfirst(p -> p == player, players)
    scorewin() = for p in players if p == player p.wins += 1 else p.losses += 1 end; p.score = 0 end
    player.ante = 0
    while (r = rand(dice)) != 1
        player.ante += r
        verbose && println("Player $playernum rolls a $r.")
        if player.score + player.ante >= 100
            scorewin()
            verbose && println("Player $playernum wins.\n")
            return false
        elseif player.strategy[2](player, players)
            player.score += player.ante
            verbose && println("Player $playernum holds and has a new score of $(player.score).")
            return true
        end
    end
    verbose && println("Player $playernum rolls a 1, so turn is over.")
    true
end

function rungames(N)
    for i in 1:N
        verbose = (i == 3) ? true : false  # do verbose if it's game number 3
        curplayer = rand(collect(1:length(players)))
        while turn(players[curplayer], verbose)
            curplayer = curplayer >= length(players) ? 1 : curplayer + 1
        end
    end
    results = sort([(p.wins/(p.wins + p.losses), p.strategy[1]) for p in players], rev=true)
    println("             Strategy                % of wins (N = $N)")
    println("------------------------------------------------------------")
    for pair in results
        println(lpad(pair[2], 34), lpad(round(pair[1] * 100, digits=1), 18))
    end
end

rungames(1000000)


Module GamePig (games, strategy1, strategy2) {
      Print "Game of Pig"
      win1=0
      win2=0
      While games {
            games--
            dice=-1
            res$=""
            Player1points=0
            Player1sum=0
            Player2points=0
            Player2sum=0
            HaveWin=False
            score()
            \\ for simulation
            simulate$=String$("R", 500)
            Keyboard simulate$
            \\ end simulation
            while res$<>"Q" {
                  Print "Player 1 turn"
                  PlayerTurn(&Player1points, &player1sum, player2sum, ! strategy1)
                  if res$="Q" then exit
                  Player1sum+=Player1points
                  Score()
                  Print "Player 2 turn"
                  PlayerTurn(&Player2points,&player2sum, player1sum, ! strategy2)
                  if res$="Q" then exit
                  Player2sum+=Player2points
                  Score()
            }
            If HaveWin then {
                  Score()
                  If Player1Sum>Player2sum then {
                        Print "Player 1 Win"
                        win1++
                  } Else Print "Player 2 Win" : win2++
            }
      }
      \\ use stack as FIFO
      If win1>win2 Then {
            Data "Player 1 Win", win1,win2, array(strategy1,0), array(strategy1,1)
      } Else {
            Data "Player 2 Win",  win2,win1, array(strategy2,0), array(strategy2,1)
      }

      Sub Rolling()
            dice=random(1,6)
            Print "dice=";dice
      End Sub
      Sub PlayOrQuit()
            Print "R - Roling Q-Quit"
            Repeat {
                  res$=Ucase$(Key$)
            } Until Instr("RQ", res$)>0
      End Sub
      Sub PlayAgain()
            Print "R - Roling H - Hold Q-Quit"
            Repeat {
                  res$=Ucase$(Key$)
            } Until Instr("RHQ", res$)>0
      End Sub
      Sub PlayerTurn(&playerpoints, &sum, othersum, Max_Points, Min_difference)
            PlayOrQuit()
            If res$="Q" then Exit Sub
            playerpoints=0
            Rolling()
            While dice<>1 and res$="R" {
                  playerpoints+=dice
                  if dice>1 and playerpoints+sum>100 then {
                        sum+=playerpoints
                        HaveWin=True
                        res$="Q"
                  } Else {
                        if playerpoints>=Max_Points Then If 100-othersum>Min_difference Then res$="H" : exit
                        PlayAgain()
                        if res$="R" then Rolling()
                  }
            }
            if dice=1 then playerpoints=0
      End Sub
      Sub Score()
            Print "Player1 points="; Player1sum
            Print "Player2 points="; Player2sum
      End Sub
}
Flush
GamePig 20, (8,10), (12, 20)
GamePig 20, (12, 20), (8,10)
Print "Results"
While not Empty {
      Read WhoWin$, winA,winb, Max_Points, Min_difference
      Print WhoWin$, winA;">";winb, Max_Points, Min_difference
}


import random, strformat

const MaxPoints = 100

type

  Move {.pure.} = enum Roll, Hold
  Strategy {.pure.} = enum Rand, Q2Win, AL20, AL20T

  # Player description.
  Player = ref object
    num: Natural
    currentScore: Natural
    roundScore: Natural
    strategy: Strategy
    next: Player

  # Player list managed as a singly linked ring.
  PlayerList = object
    count: Natural
    head, tail: Player

proc addPlayer(playerList: var PlayerList; strategy: Strategy) =
  ## Add a player with given strategy.
  inc playerList.count
  let newPlayer = Player(num: playerList.count, strategy: strategy)
  if playerList.head.isNil:
    playerList.head = newPlayer
  else:
    playerList.tail.next = newPlayer
  playerList.tail = newPlayer
  newPlayer.next = playerList.head

iterator items(playerList: PlayerList): Player =
  ## Yield the successive players of a player list.
  var player = playerList.head
  yield player
  while player != playerList.tail:
    player = player.next
    yield player

proc getMove(player: Player): Move =
  ## Get the move for the given player.

  if player.roundScore + player.currentScore >= MaxPoints: return Hold

  case player.strategy

  of Strategy.Rand:
    result = if rand(1) == 0: Roll
             elif player.roundScore > 0: Hold
             else: Roll

  of Strategy.Q2Win:
    let q = MaxPoints - player.currentScore
    result = if q < 6 or player.roundScore < q div 4: Roll
             else: Hold

  of Strategy.AL20:
    result = if player.roundScore < 20: Roll
             else: Hold

  of Strategy.AL20T:
    let d = 5 * player.roundScore
    result = if player.roundScore < 20 and d < rand(99): Roll
             else: Hold

randomize()

# Create player list.
var playerList = PlayerList()
for strategy in Strategy.low..Strategy.high:
  playerList.addPlayer(strategy)

var endGame = false
var player = playerList.head

while not endGame:
  case player.getMove()

  of Roll:
    let die = rand(1..6)
    if die == 1:
      echo &"Player {player.num} rolled {die}  Current score: {player.currentScore:3}\n"
      player.roundScore = 0
      player = player.next
      continue
    inc player.roundScore, die
    echo &"Player {player.num} rolled {die}    Round score: {player.roundScore:3}"

  of Hold:
    inc player.currentScore, player.roundScore
    echo &"Player {player.num} holds     Current score: {player.currentScore:3}\n"
    if player.currentScore >= MaxPoints:
      endGame = true
    else:
      player.roundScore = 0
      player = player.next

for player in playerList:
  let stratStr = &"({player.strategy}):"
  echo &"Player {player.num} {stratStr:8} {player.currentScore:3}"


my $GOAL = 100;

package Player;

sub new {
    my ($class,$strategy) = @_;
    my $self = {
        score    => 0,
        rolls    => 0,
        ante     => 0,
        strategy => $strategy || sub { 0 } # as fallback, always roll again
    };
    return bless($self, $class);
}

sub turn {
    my ($P) = @_;
    $P->{rolls} = 0;
    $P->{ante}  = 0;
    my $done    = 0;
    do {
        my $v = 1 + int rand 6;
        $P->{rolls}++;
        if ($v == 1) {
            $P->{ante} = 0;
            $done = 1;
        } else {
            $P->{ante} += $v;
        }
        $done = 1 if $P->{score} + $P->{ante} >= $GOAL or $P->{strategy}();
    } until $done;
    $P->{score} += $P->{ante};
}

package Main;

# default, go-for-broke, always roll again
$players[0] = Player->new;

# try to roll 5 times but no more per turn
$players[1] = Player->new( sub { $players[1]->{rolls} >= 5 } );

# try to accumulate at least 20 points per turn
@players[2] = Player->new( sub { $players[2]->{ante} > 20 } );

# random but 90% chance of rolling again
$players[3] = Player->new( sub { rand() < 0.1 } );

# random but more conservative as approaches goal
$players[4] = Player->new( sub { rand() < ( $GOAL - $players[4]->{score} ) * .6 / $GOAL } );

for (1 .. shift || 100) {
    my $player = -1;
    do {
        $player++;
        @players[$player % @players]->turn;
    } until $players[$player % @players]->{score} >= $GOAL;

    $wins[$player % @players]++;

    printf "%5d", $players[$_]->{score} for 0..$#players; print "\n";
    $players[$_]->{score} = 0 for 0..$#players; # reset scores for next game
}

print ' ----' x @players, "\n";
printf "%5d", $_ for @wins; print "\n";


with javascript_semantics
constant maxScore = 100

function one_game(sequence strategies)
    integer numPlayers = length(strategies),
            points = 0, -- points accumulated in current turn, 0=swap turn
            rolls  = 0, -- number of rolls
            player = rand(numPlayers)   -- start with a random player
    sequence scores = repeat(0,numPlayers)
    while true do
        integer roll = rand(6)
        if roll=1 then
            points = 0 -- swap turn
        else
            points += roll
            if scores[player]+points>=maxScore then exit end if
            rolls += 1
            integer play = strategies[player]
            if not play(scores,player,points,rolls) then
                scores[player] += points
                points = 0 -- swap turn
            end if
        end if
        if points=0 then
            player = mod(player,numPlayers) + 1
            rolls = 0
        end if
    end while
    return player
end function

-- each strategy returns true to roll, false to hold.

function strategy1(sequence /*scores*/, integer /*player*/, points, /*rolls*/)
    return points<20    -- roll until 20 or more
end function

function strategy2(sequence /*scores*/, integer /*player*/, /*points*/, rolls)
    return rolls<4      -- roll 4 times
end function

function strategy3(sequence scores, integer player, points, /*rolls*/)
    -- roll until 20 or score>80
    return points<20 or scores[player]+points>80
end function

function strategy4(sequence scores, integer player, points, /*rolls*/)
    -- roll until 20 or any player has >71
    for i=1 to length(scores) do
        if scores[i]>71 then return true end if
    end for
    return points<20
end function

constant strategies = {strategy1,strategy2,strategy3,strategy4},
         numStrategies = length(strategies),
         numOpponents = numStrategies-1

-- play each strategy 1000 times against all combinations of other strategies
for s=1 to numStrategies do
    integer strategy = strategies[s],
            mask = power(2,numOpponents)-1,
            wins = 0
    sequence opponents = deep_copy(strategies)
             opponents[s..s] = {} -- (ie all others only)
    for m=1 to mask do -- (all possible bit settings, bar 0, eg/ie 1..7)
        sequence game = {strategy}
        for g=1 to numOpponents do
            if and_bits(m,power(2,g-1)) then
                game &= opponents[g]
            end if
        end for
        for n=1 to 1000 do
            wins += one_game(game)=1
        end for
    end for
    printf(1,"strategy %d: %d wins\n",{s,wins})
end for


#!/usr/bin/python3

'''
See: http://en.wikipedia.org/wiki/Pig_(dice)

This program scores, throws the dice, and plays for an N player game of Pig.

'''

from random import randint
from collections import namedtuple
import random
from pprint import pprint as pp
from collections import Counter

playercount = 2
maxscore = 100
maxgames = 100000

Game = namedtuple('Game', 'players, maxscore, rounds')
Round = namedtuple('Round', 'who, start, scores, safe')

class Player():
    def __init__(self, player_index):
        self.player_index = player_index

    def __repr__(self):
        return '%s(%i)' % (self.__class__.__name__, self.player_index)

    def __call__(self, safescore, scores, game):
        'Returns boolean True to roll again'
        pass

class RandPlay(Player):
    def __call__(self, safe, scores, game):
        'Returns random boolean choice of whether to roll again'
        return bool(random.randint(0, 1))

class RollTo20(Player):
    def __call__(self, safe, scores, game):
        'Roll again if this rounds score < 20'
        return (((sum(scores) + safe[self.player_index]) < maxscore)    # Haven't won yet
                and(sum(scores) < 20))                                  # Not at 20 this round

class Desparat(Player):
    def __call__(self, safe, scores, game):
        'Roll again if this rounds score < 20 or someone is within 20 of winning'
        return (((sum(scores) + safe[self.player_index]) < maxscore)    # Haven't won yet
                and( (sum(scores) < 20)                                 # Not at 20 this round
                     or max(safe) >= (maxscore - 20)))                  # Someone's close

def game__str__(self):
    'Pretty printer for Game class'
    return ("Game(players=%r, maxscore=%i,\n  rounds=[\n    %s\n  ])"
            % (self.players, self.maxscore,
               ',\n    '.join(repr(round) for round in self.rounds)))
Game.__str__ = game__str__

def winningorder(players, safescores):
    'Return (players in winning order, their scores)'
    return tuple(zip(*sorted(zip(players, safescores),
                            key=lambda x: x[1], reverse=True)))

def playpig(game):
    '''
    Plays the game of pig returning the players in winning order
    and their scores whilst updating argument game with the details of play.
    '''
    players, maxscore, rounds = game
    playercount = len(players)
    safescore = [0] * playercount   # Safe scores for each player
    player = 0                      # Who plays this round
    scores=[]                       # Individual scores this round

    while max(safescore) < maxscore:
        startscore = safescore[player]
        rolling = players[player](safescore, scores, game)
        if rolling:
            rolled = randint(1, 6)
            scores.append(rolled)
            if rolled == 1:
                # Bust!
                round = Round(who=players[player],
                              start=startscore,
                              scores=scores,
                              safe=safescore[player])
                rounds.append(round)
                scores, player = [], (player + 1) % playercount
        else:
            # Stick
            safescore[player] += sum(scores)
            round = Round(who=players[player],
                          start=startscore,
                          scores=scores,
                          safe=safescore[player])
            rounds.append(round)
            if safescore[player] >= maxscore:
                break
            scores, player = [], (player + 1) % playercount

    # return players in winning order and all scores
    return winningorder(players, safescore)

if __name__ == '__main__':
    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
                maxscore=20,
                rounds=[])
    print('ONE GAME')
    print('Winning order: %r; Respective scores: %r\n' % playpig(game))
    print(game)
    game = Game(players=tuple(RandPlay(i) for i in range(playercount)),
                maxscore=maxscore,
                rounds=[])
    algos = (RollTo20, RandPlay, Desparat)
    print('\n\nMULTIPLE STATISTICS using %r\n  for %i GAMES'
          % (', '.join(p.__name__ for p in algos), maxgames,))
    winners = Counter(repr(playpig(game._replace(players=tuple(random.choice(algos)(i)
                                                               for i in range(playercount)),
                                                 rounds=[]))[0])
                      for i in range(maxgames))
    print('  Players(position) winning on left; occurrences on right:\n    %s'
          % ',\n    '.join(str(w) for w in winners.most_common()))


#lang racket

(define (pig-the-dice #:print? [print? #t] . players)
  (define prn (if print? (λ xs (apply printf xs) (flush-output)) void))
  (define names (for/list ([p players] [n (in-naturals 1)]) n))
  (define points (for/list ([p players]) (box 0)))
  (with-handlers ([(negate exn?) identity])
    (for ([nm (in-cycle names)] [tp (in-cycle points)] [pl (in-cycle players)])
      (prn (string-join (for/list ([n names] [p points])
                          (format "Player ~a, ~a points" n (unbox p)))
                        "; " #:before-first "Status: " #:after-last ".\n"))
      (let turn ([p 0] [n 0])
        (prn "Player ~a, round #~a, [R]oll or [P]ass? " nm (+ 1 n))
        (define roll? (pl (unbox tp) p n))
        (unless (eq? pl human) (prn "~a\n" (if roll? 'R 'P)))
        (if (not roll?) (set-box! tp (+ (unbox tp) p))
            (let ([r (+ 1 (random 6))])
              (prn "  Dice roll: ~s => " r)
              (if (= r 1) (prn "turn lost\n")
                  (let ([p (+ p r)]) (prn "~a points\n" p) (turn p (+ 1 n)))))))
      (prn "--------------------\n")
      (when (<= 100 (unbox tp)) (prn "Player ~a wins!\n" nm) (raise nm)))))

(define (human total-points turn-points round#)
  (case (string->symbol (car (regexp-match #px"[A-Za-z]?" (read-line))))
    [(R r) #t] [(P p) #f] [else (human total-points turn-points round#)]))

;; Always do N rolls
(define ((n-rounds n) total-points turn-points round#) (< round# n))
;; Roll until a given number of points
(define ((n-points n) total-points turn-points round#) (< turn-points n))
;; Random decision
(define ((n-random n) total-points turn-points round#) (zero? (random n)))

(define (n-runs n . players)
  (define v (make-vector (length players) 0))
  (for ([i n])
    (define p (sub1 (apply pig-the-dice #:print? #f players)))
    (vector-set! v p (add1 (vector-ref v p))))
  (for ([wins v] [i (in-naturals 1)])
    (printf "Player ~a: ~a%\n" i (round (/ wins n 1/100)))))

;; Things to try
;; (n-runs 1000 (n-random 2) (n-random 3) (n-random 4))
;; (n-runs 1000 (n-rounds 5) (n-points 24))
;; (n-runs 1000 (n-rounds 5) (n-random 2))


 player 0 uses the default strategy, always roll if it can.
 player 1 will roll up to 5 times then lock in whatever it earned.
 player 2 will try to get at least 20 points per turn.
 player 3 randomly picks whether to roll again or not biased so that there is a 90% chance that it will.
 player 4 randomly chooses to roll again but gets more consrvative as its score get closer to the goal.


/*REXX program plays "pig the dice game"  (any number of CBLFs and/or silicons or HALs).*/
sw= linesize() - 1                               /*get the width of the terminal screen,*/
parse arg  hp  cp  win  die  _  .  '(' names ")" /*obtain optional arguments from the CL*/
                                                 /*names with blanks should use an  _   */
if _\==''  then  call  err  'too many arguments were specified: ' _
@nhp  = 'number of human players'   ;         hp = scrutinize( hp, @nhp , 0,  0,   0)
@ncp  = 'number of computer players';         cp = scrutinize( cp, @ncp , 0,  0,   2)
@sn2w = 'score needed to win'       ;         win= scrutinize(win, @sn2w, 1, 1e6, 60)
@nsid = 'number of sides in die'    ;         die= scrutinize(die, @nsid, 2, 999,  6)
if hp==0  &  cp==0   then cp= 2                  /*if both counts are zero, two HALs.   */
if hp==1  &  cp==0   then cp= 1                  /*if one human, then use   one HAL.    */
name.=                                           /*nullify all names  (to a blank).     */
L= 0                                             /*maximum length of a player name.     */
       do i=1  for hp+cp                         /*get the player's names,  ...  maybe. */
       if i>hp  then @= 'HAL_'i"_the_computer"   /*use this for default name.           */
                else @= 'player_'i               /* "    "   "     "      "             */
       name.i = translate( word( strip( word( names, i) ) @, 1), , '_')
       L= max(L, length( name.i) )               /*use   L   for nice name formatting.  */
       end   /*i*/                               /*underscores are changed ──► blanks.  */

hpn=hp;  if hpn==0   then hpn= 'no'              /*use normal English for the display.  */
cpn=cp;  if cpn==0   then cpn= 'no'              /* "     "      "     "   "     "      */

say 'Pig (the dice game) is being played with:'  /*the introduction to pig-the-dice-game*/

         if cpn\==0  then  say  right(cpn, 9)     'computer player's(cp)
         if hpn\==0  then  say  right(hpn, 9)     'human player's(hp)
!.=
say 'and the'         @sn2w         "is: "         win         '   (or greater).'
dieNames= 'ace deuce trey square nickle boxcar'  /*some slangy vernacular die─face names*/
!w=0                                             /*note:  snake eyes is for two aces.   */
               do i=1  for die                   /*assign the vernacular die─face names.*/
               !.i= ' ['word(dieNames,i)"]"      /*pick a word from die─face name lists.*/
               !w= max(!w, length(!.i) )         /*!w ──► maximum length die─face name. */
               end   /*i*/
s.= 0                                            /*set all player's scores to zero.     */
!w= !w + length(die) + 3                         /*pad the die number and die names.    */
@= copies('─', 9)                                /*eyecatcher (for the prompting text). */
@jra= 'just rolled a '                           /*a nice literal to have laying 'round.*/
@ati= 'and the inning'                           /*"   "     "     "   "     "      "   */
               /*═══════════════════════════════════════════════════let's play some pig.*/
   do game=1;     in.= 0;       call score       /*set each inning's score to 0; display*/

     do j=1  for hp+cp;         say              /*let each player roll their dice.     */
     say copies('─', sw)                         /*display a fence for da ole eyeballs. */
     it= name.j
     say it',  your total score (so far) in this pig game is: '        s.j"."

       do  until  stopped                        /*keep prompting/rolling 'til stopped. */
       r= random(1, die)                         /*get a random die face (number).      */
       != left(space(r !.r','),  !w)             /*for color, use a die─face name.      */
       in.j= in.j + r                            /*add die─face number to the inning.   */

       if r==1  then  do;  say it @jra ! || @ati "is a bust.";  leave;   end
                           say it @jra ! || @ati "total is: "    in.j

       stopped= what2do(j)                       /*determine or ask  to stop rolling.   */
       if j>hp & stopped  then say ' and'      name.j      "elected to stop rolling."
       end   /*until stopped*/

     if r\==1     then s.j= s.j + in.j           /*if not a bust, then add to the inning*/
     if s.j>=win  then leave game                /*we have a winner,  so the game ends. */
     end     /*j*/                               /*that's the end of the players.       */
   end       /*game*/

call score;    say;    say;    say;    say;          say center(''name.j "won! ", sw, '═')
               say;    say;            exit      /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
s: if arg(1)==1  then return arg(3);           return word(arg(2) 's',1)   /*pluralizer.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
score:  say;           say copies('█', sw)       /*display a fence for da ole eyeballs. */
          do k=1  for hp+cp                      /*display the scores  (as a recap).    */
          say 'The score for '    left(name.k, L)     " is "     right(s.k, length(win) ).
          end  /*k*/
        say copies('█', sw);           return    /*display a fence for da ole eyeballs. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
scrutinize: parse arg ?,what,min,max             /*?  is the number,  ... or maybe not. */
            if ?==''  |  ?==','   then return arg(5)
            if \datatype(?, 'N')  then call err what "isn't numeric: "    ?;         ?=?/1
            if \datatype(?, 'W')  then call err what "isn't an integer: " ?
            if ?==0  & min>0      then call err what "can't be zero."
            if ?<min              then call err what "can't be less than"     min': '  ?
            if ?==0  & max>0      then call err what "can't be zero."
            if ?>max & max\==0    then call err what "can't be greater than"  max': '  ?
            return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
what2do: parse arg who                                 /*"who" is a human or a computer.*/
         if j>hp & s.j+in.j>=win    then  return 1     /*an  easy  choice  for HAL.     */
         if j>hp &     in.j>=win%4  then  return 1     /*a simple strategy for HAL.     */
         if j>hp                    then  return 0     /*HAL says, keep truckin'!       */
         say @ name.who', what do you want to do?        (a QUIT will stop the game),'
         say @ 'press  ENTER  to roll again,  or anything else to STOP rolling.'
         pull action;      action=space(action)        /*remove any superfluous blanks. */
         if \abbrev('QUIT', action, 1)  then return action\==''
         say;    say;    say center(' quitting. ', sw, '─');    say;     say;      exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
err:     say;    say;    say center(' error! ', max(40, linesize() % 2), "*");     say
                      do j=1  for arg();    say arg(j);    say;    end;    say;    exit 13


def player1(sum,sm)
for i in 1..100
puts "player1 rolled"
a=gets.chomp().to_i
if (a>1 && a<7)
	sum+=a
	if sum>=100
	puts "player1 wins"
	break
	end
else

goto player2(sum,sm)
end
i+=1
end
end

def player2(sum,sm)
for j in 1..100
puts "player2 rolled"
b=gets.chomp().to_i
if(b>1 && b<7)
 sm+=b
	if sm>=100
	 puts "player2 wins"
	break
	end
else

player1(sum,sm)
end
j+=1
end
end
i=0
j=0
sum=0
sm=0
player1(sum,sm)
return


var (games=100) = ARGV.map{.to_i}...

define DIE = 1..6;
define GOAL = 100;

class Player(score=0, ante=0, rolls=0, strategy={false}) {
    method turn {
        rolls = 0;
        ante  = 0;
        loop {
            rolls++;
            given (var roll = DIE.rand) {
                when (1) {
                    ante = 0;
                    break;
                }
                case (roll > 1) {
                    ante += roll;
                }
            }
            ((score + ante >= GOAL) || strategy) && break;
        }
        score += ante;
    }
}

var players = [];

# default, go-for-broke, always roll again
players[0] = Player.new;

# try to roll 5 times but no more per turn
players[1] = Player.new( strategy: { players[1].rolls >= 5 } );

# try to accumulate at least 20 points per turn
players[2] = Player.new( strategy: { players[2].ante > 20 } );

# random but 90% chance of rolling again
players[3] = Player.new( strategy: { 1.rand < 0.1 } );

# random but more conservative as approaches goal
players[4] = Player.new( strategy: { 1.rand < ((GOAL - players[4].score) * 0.6 / GOAL) } );

var wins = [0]*players.len;

games.times {
    var player = -1;
    loop {
        player++;
        var p = players[player % players.len];
        p.turn;
        p.score >= GOAL && break;
    }
    wins[player % players.len]++;
    players.map{.score}.join("\t").say;
    players.each { |p| p.score = 0 };
}

say "\nSCORES: for #{games} games";
say wins.join("\t");


package require TclOO

oo::class create Player {
    variable me
    constructor {name} {
	set me $name
    }
    method name {} {
	return $me
    }

    method wantToRoll {safeScore roundScore} {}

    method rolled {who what} {
	if {$who ne [self]} {
	    #puts "[$who name] rolled a $what"
	}
    }
    method turnend {who score} {
	if {$who ne [self]} {
	    #puts "End of turn for [$who name] on $score"
	}
    }
    method winner {who score} {
	if {$who ne [self]} {
	    #puts "[$who name] is a winner, on $score"
	}
    }
}

oo::class create HumanPlayer {
    variable me
    superclass Player
    method wantToRoll {safeScore roundScore} {
	while 1 {
	    puts -nonewline "$me (on $safeScore+$roundScore) do you want to roll? (Y/n)"
	    flush stdout
	    if {[gets stdin line] < 0} {
		# EOF detected
		puts ""
		exit
	    }
	    if {$line eq "" || $line eq "y" || $line eq "Y"} {
		return 1
	    }
	    if {$line eq "n" || $line eq "N"} {
		return 0
	    }
	}
    }
    method stuck {score} {
	puts "$me sticks with score $score"
    }
    method busted {score} {
	puts "Busted! ($me still on score $score)"
    }
    method won {score} {
	puts "$me has won! (Score: $score)"
    }
}

proc rollDie {} {
    expr {1+int(rand() * 6)}
}
proc rotateList {var} {
    upvar 1 $var l
    set l [list {*}[lrange $l 1 end] [lindex $l 0]]
}
proc broadcast {players message score} {
    set p0 [lindex $players 0]
    foreach p $players {
	$p $message $p0 $score
    }
}

proc pig {args} {
    set players $args
    set scores [lrepeat [llength $args] 0]
    while 1 {
	set player [lindex $players 0]
	set safe [lindex $scores 0]
	set s 0
	while 1 {
	    if {$safe + $s >= 100} {
		incr safe $s
		$player won $safe
		broadcast $players winner $safe
		return $player
	    }
	    if {![$player wantToRoll $safe $s]} {
		lset scores 0 [incr safe $s]
		$player stuck $safe
		break
	    }
	    set roll [rollDie]
	    broadcast $players rolled $roll
	    if {$roll == 1} {
		$player busted $safe
		break
	    }
	    incr s $roll
	}
	broadcast $players turnend $safe
	rotateList players
	rotateList scores
    }
}


import "random" for Random
import "os" for Process

var args = Process.arguments
var games = (args.count == 0) ? 100 : Num.fromString(args[0])

var Rand = Random.new()
var Die  = 1..6
var Goal = 100

class Player {
    construct new(strategy) {
        _score = 0
        _ante  = 0
        _rolls = 0
        _strategy = strategy
    }

    score { _score  }
    rolls { _rolls  }
    ante  { _ante   }

    score=(s) { _score = s }

    turn() {
        _rolls = 0
        _ante = 0
        while (true) {
            _rolls = _rolls + 1
            var roll = Rand.int(Die.from, Die.to + 1)
            if (roll == 1) {
                _ante = 0
                break
            }
            _ante = _ante + roll
            if (_score + _ante >= Goal || _strategy.call()) break
         }
         _score = _score + _ante
    }
}

var numPlayers = 5
var players = List.filled(numPlayers, null)

// default, go-for-broke, always roll again
players[0] = Player.new { false }

// try to roll 5 times but no more per turn
players[1] = Player.new { players[1].rolls >= 5 }

// try to accumulate at least 20 points per turn
players[2] = Player.new { players[2].ante > 20 }

// random but 90% chance of rolling again
players[3] = Player.new { Rand.float() < 0.1 }

// random but more conservative as approaches goal
players[4] = Player.new { Rand.float() < (Goal - players[4].score) * 0.6 / Goal }

var wins = List.filled(numPlayers, 0)

for (i in 0...games) {
    var player = -1
    while (true) {
        player = player + 1
        var p = players[player % numPlayers]
        p.turn()
        if (p.score >= Goal) break
    }
    wins[player % numPlayers] = wins[player % numPlayers] + 1
    System.print(players.map { |p| p.score }.join("\t"))
    players.each { |p| p.score = 0 }
}

System.print("\nSCORES: for %(games) games")
System.print(wins.join("\t"))


    .model small
    .stack 1024

    .data
TestList byte 00h,05h,10h,15h,20h,25h,30h,35h

    .code

start:
	mov ax,@data
	mov ds,ax

	mov ax,@code
	mov es,ax

	call seedXorshift32				;seeds the xorshift rng using the computer's date and time

	call doXorshift32
	mov ax,word ptr [ds:xorshift32_state_lo]	;retrieve the rng output
	and al,00000111b				;constrain the rng to values 0-7

	mov bx,offset TestList
	XLAT						;translate AL according to [DS:BX]

	call PrintHex					;display AL to the terminal

	mov ax,4C00h
	int 21h						;exit program and return to MS-DOS
        end start


:set-state-ok t

(defun pick-random-element (xs state)
   (mv-let (idx state)
           (random$ (len xs) state)
      (mv (nth idx xs) state)))


PROC Main()
  DEFINE PTR="CARD"
  PTR ARRAY a(7)
  BYTE i,index

  a(0)="Monday"
  a(1)="Tuesday"
  a(2)="Wednesday"
  a(3)="Thursday"
  a(4)="Friday"
  a(5)="Saturday"
  a(6)="Sunday"

  FOR i=1 TO 20
  DO
    index=Rand(7)
    PrintE(a(index))
  OD
RETURN


with Ada.Text_IO, Ada.Numerics.Float_Random;

procedure Pick_Random_Element is

   package Rnd renames Ada.Numerics.Float_Random;
   Gen: Rnd.Generator; -- used globally

   type Char_Arr is array (Natural range <>) of Character;

   function Pick_Random(A: Char_Arr) return Character is
      -- Chooses one of the characters of A (uniformly distributed)
   begin
      return A(A'First + Natural(Rnd.Random(Gen) * Float(A'Last)));
   end Pick_Random;

   Vowels    : Char_Arr := ('a', 'e', 'i', 'o', 'u');
   Consonants: Char_Arr := ('t', 'n', 's', 'h', 'r', 'd', 'l');
   Specials  : Char_Arr := (',', '.', '?', '!');

begin
   Rnd.Reset(Gen);
   for J in 1 .. 3 loop
      for I in 1 .. 10 loop
         Ada.Text_IO.Put(Pick_Random(Consonants));
         Ada.Text_IO.Put(Pick_Random(Vowels));
      end loop;
      Ada.Text_IO.Put(Pick_Random(Specials) & " ");
   end loop;
   Ada.Text_IO.New_Line;
end Pick_Random_Element;


list l;

l_append(l, 'a');
l_append(l, 'b');
l_append(l, 'c');
l_append(l, 'd');
l_append(l, 'e');
l_append(l, 'f');

o_byte(l[drand(5)]);
o_byte('\n');


# pick a random element from an array of strings #

OP PICKRANDOM = ( []STRING list )STRING:
BEGIN

    INT number of elements = ( UPB list - LWB list ) + 1;
    INT random element     =
        ENTIER ( next random * ( number of elements ) );

    list[ LWB list + random element ]
END; # PICKRANDOM #
# can define additional operators for other types of array #

main: (

    []STRING days = ( "Sunday",   "Monday", "Tuesday", "Wednesday"
                    , "Thursday", "Friday", "Saturday"
                    );

    print( ( PICKRANDOM days, newline ) )

)


get some item of [1, "two", pi, "4", 5 > 4, 5 + 1, Sunday]


fruit: ["apple" "banana" "pineapple" "apricot" "watermelon"]

print sample fruit


list := ["abc", "def", "gh", "ijklmnop", "hello", "world"]
Random, randint, 1, % list.MaxIndex()
MsgBox % List[randint]


# syntax: GAWK -f PICK_RANDOM_ELEMENT.AWK
BEGIN {
    n = split("Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",day_of_week,",")
    srand()
    x = int(n*rand()) + 1
    printf("%s\n",day_of_week[x])
    exit(0)
}


' Pick random element
OPTION BASE 1
DECLARE words$[6]
FOR i = 1 TO 6 : READ words$[i] : NEXT
DATA "Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"

element = RANDOM(6) + 1
PRINT "Chose ", element, ": ", words$[element]


# borrowed from github.com/search?q=bashnative

rand() {
	printf $((  $1 *  RANDOM  / 32767   ))
}
rand_element () {
    local -a th=("[email protected]")
    unset th[0]
    printf $'%s\n' "${th[$(($(rand "${#th[*]}")+1))]}"
}

echo "You feel like a $(rand_element pig donkey unicorn eagle) today"


'setup
DIM foo(10) AS LONG
DIM n AS LONG, x AS LONG
FOR n = LBOUND(foo) TO UBOUND(foo)
    foo(n) = INT(RND*99999)
NEXT
RANDOMIZE TIMER

'random selection
x = INT(RND * ((UBOUND(foo) - LBOUND(foo)) + 1))

'output
PRINT x, foo(x)


@echo off
setlocal enabledelayedexpansion

	::Initializing the pseudo-array...
set "pseudo=Alpha Beta Gamma Delta Epsilon"
set cnt=0 & for %%P in (!pseudo!) do (
	set /a cnt+=1
	set "pseudo[!cnt!]=%%P"
)
	::Do the random thing...
set /a rndInt=%random% %% cnt +1

	::Print the element corresponding to rndint...
echo.!pseudo[%rndInt%]!
pause
exit /b


      DIM list$(5)
      list$() = "The", "five", "boxing", "wizards", "jump", "quickly"
      chosen% = RND(6)
      PRINT "Item " ; chosen% " was chosen which is '" list$(chosen%-1) "'"


PR ← {𝕩⊑˜•rand.Range ≠𝕩}
PR1 ← •rand.Range∘≠⊸⊑


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(){
   char array[] = { 'a', 'b', 'c','d','e','f','g','h','i','j' };
   int i;
   time_t t;
   srand((unsigned)time(&t));

   for(i=0;i<30;i++){
		printf("%c\n", array[rand()%10]);
   }

   return 0;
}


using System;
using System.Collections.Generic;

class RandomElementPicker {
  static void Main() {
    var list = new List<int>(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9});
    var rng = new Random();
    var randomElement = list[rng.Next(list.Count)];
    Console.WriteLine("I picked element {0}", randomElement);
  }
}


#include <iostream>
#include <random>
#include <vector>

int main( ) {
   std::vector<int> numbers { 11 , 88 , -5 , 13 , 4 , 121 , 77 , 2 } ;
   std::random_device seed ;
   // generator
   std::mt19937 engine( seed( ) ) ;
   // number distribution
   std::uniform_int_distribution<int> choose( 0 , numbers.size( ) - 1 ) ;
   std::cout << "random element picked : " << numbers[ choose( engine ) ]
      << " !\n" ;
   return 0 ;
}


import ceylon.random {

	DefaultRandom
}

shared void run() {
    value random = DefaultRandom();
    value element = random.nextElement([1, 2, 3, 4, 5, 6]);
    print(element);
}


random_element = proc [T: type] (a: array[T]) returns (T)
    return(a[array[T]$low(a) + random$next(array[T]$size(a))])
end random_element

start_up = proc ()
    po: stream := stream$primary_output()
    d: date := now()
    random$seed(d.second + 60*(d.minute + 60*d.hour))

    arr: array[string] := array[string]$["foo", "bar", "baz", "qux"]

    for i: int in int$from_to(1,5) do
        stream$putl(po, random_element[string](arr))
    end
end start_up


       >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. random-element.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  nums-area                           VALUE "123456789".
    03  nums                            PIC 9 OCCURS 9 TIMES.

01  random-idx                          PIC 9 COMP.

PROCEDURE DIVISION.
    COMPUTE random-idx = FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:7)) * 9 + 1
    DISPLAY nums (random-idx)
    .
END PROGRAM random-element.


array = [1,2,3]
console.log array[Math.floor(Math.random() * array.length)]


(defvar *list* '(one two three four five))

(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*))
(print (nth (random (length *list*)) *list*))


import std.stdio, std.random;

void main() {
    const items = ["foo", "bar", "baz"];
    items[uniform(0, $)].writeln;
}


ar$[] = [ "spring" "summer" "autumn" "winter" ]
print ar$[random len ar$[]]


(define (pick-random list)
    (list-ref list (random (length list))))
(pick-random (iota 1000)) → 667
(pick-random (iota 1000)) → 179


import extensions;

extension listOp
{
    randomItem()
        = self[randomGenerator.eval(self.Length)];
}

public program()
{
    var item := new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

    console.printLine("I picked element ",item.randomItem())
}


(defun random-choice (items)
  (nth (random (length items)) items))

(random-choice '("a" "b" "c"))
;; => "a"


% Implemented by Arjun Sunel
-module(pick_random).
-export([main/0]).

main() ->
	List =[1,2,3,4,5],
	Index = rand:uniform(length(List)),
	lists:nth(Index,List).


constant s = {'a', 'b', 'c'}
puts(1,s[rand($)])


let list = ["a"; "b"; "c"; "d"; "e"]
let rand = new System.Random()
printfn "%s" list.[rand.Next(list.Length)]


( scratchpad ) { "a" "b" "c" "d" "e" "f" } random .
"a"


lst = [1, 3, 5, 8, 10]
> randomPick(lst)


program pick_random
  implicit none

  integer :: i
  integer :: a(10) = (/ (i, i = 1, 10) /)
  real :: r

  call random_seed
  call random_number(r)
  write(*,*) a(int(r*size(a)) + 1)
end program


' FB 1.05.0 Win64

Dim a(0 To 9) As String = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}

Randomize
Dim randInt As Integer

For i As Integer = 1 To 5
  randInt = Int(Rnd * 10)
  Print a(randInt)
Next
Sleep


a = ["one", "two", "three"]
println[random[a]]


Public Sub Main()
Dim sList As String[] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

Print sList[Rand(0, 11)]

End


package main

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

var list = []string{"bleen", "fuligin", "garrow", "grue", "hooloovoo"}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(list[rand.Intn(len(list))])
}


def list = [25, 30, 1, 450, 3, 78]
def random = new Random();

(0..3).each {
    def i = random.nextInt(list.size())
    println "list[${i}] == ${list[i]}"
}


10 RANDOMIZE TIMER       :   REM set random number seed to something arbitrary
20 DIM ARR(10)           :   REM initialise array
30 FOR I = 1 TO 10
40 ARR(I) = I*I          :   REM squares of the integers is OK as a demo
50 NEXT I
60 C = 1 + INT(RND*10)   :   REM  get a random index from 1 to 10 inclusive
70 PRINT ARR(C)


use fmt;
use math::random;
use datetime;

export fn main() void = {
	const array = ["one", "two", "three", "four", "five"];
	const seed = datetime::now();
	const seed = datetime::nsec(&seed);
	let r = math::random::init(seed: u32);

	fmt::printfln("{}", array[math::random::u32n(&r, len(array): u32)])!;
};


import System.Random (randomRIO)

pick :: [a] -> IO a
pick xs = fmap (xs !!) $ randomRIO (0, length xs - 1)

x <- pick [1, 2, 3]


procedure main()
   L := [1,2,3]  # a list
   x := ?L       # random element
end


import java.util.Random;
...
int[] array = {1,2,3};
return array[new Random().nextInt(array.length)]; // if done multiple times, the Random object should be re-used


var array = [1,2,3];
return array[Math.floor(Math.random() * array.length)];


< /dev/urandom tr -cd '0-9' | fold -w 1 | jq -MRcnr -f program.jq


include ..\Utilitys.tlhy

:pickran len rand * 1 + get ;

( 1 3.1415 "Hello world" ( "nest" "list" ) )

10 [drop pickran ?] for

" " input


// version 1.2.10

import java.util.Random

/**
 * Extension function on any list that will return a random element from index 0
 * to the last index
 */
fun <E> List<E>.getRandomElement() = this[Random().nextInt(this.size)]

/**
 * Extension function on any list that will return a list of unique random picks
 * from the list. If the specified number of elements you want is larger than the
 * number of elements in the list it returns null
 */
fun <E> List<E>.getRandomElements(numberOfElements: Int): List<E>? {
    if (numberOfElements > this.size) {
        return null
    }
    return this.shuffled().take(numberOfElements)
}

fun main(args: Array<String>) {
    val list = listOf(1, 16, 3, 7, 17, 24, 34, 23, 11, 2)
    println("The list consists of the following numbers:\n${list}")

    // notice we can call our extension functions as if they were regular member functions of List
    println("\nA randomly selected element from the list is ${list.getRandomElement()}")
    println("\nA random sequence of 5 elements from the list is ${list.getRandomElements(5)}")
}


local(
	my array = array('one', 'two', 3)
)

#myarray -> get(integer_random(#myarray -> size, 1))


list$ ="John Paul George Ringo Peter Paul Mary Obama Putin"
wantedTerm =int( 10 *rnd( 1))
print "Selecting term "; wantedTerm; " in the list, which was "; word$( list$, wantedTerm, " ")


put "Apple,Banana,Peach,Apricot,Pear" into fruits
put item (random(the number of items of fruits)) of fruits


math.randomseed(os.time())
local a = {1,2,3}
print(a[math.random(1,#a)])


a := [bear, giraffe, dog, rabbit, koala, lion, fox, deer, pony]:
randomNum := rand(1 ..numelems(a)):
a[randomNum()];


        list = {'a','b','c'};
	list{ceil(rand(1)*length(list))}


random_element(l):= part(l, 1+random(length(l)));
/*  (%i1) random_element(['a, 'b, 'c]);
    (%o1)                                  c
*/


0 П0 1 П1 2 П2 3 П3 4 П4 5

^ СЧ * [x] ПE КИПE С/П


;; from list containnig only literals and literal constants
user-message one-of [ 1 3 "rooster" blue ]
;; from list containing variables and reporters
user-message one-of (list (red + 2) turtles (patch 0 0) )


/* NetRexx */
options replace format comments java crossref savelog symbols nobinary

iArray = [ 1, 2, 3, 4, 5 ]     -- a traditional array
iList = Arrays.asList(iArray)  -- a Java Collection "List" object
iWords = '1 2 3 4 5'           -- a list as a string of space delimited words

v1 = iArray[Random().nextInt(iArray.length)]
v2 = iList.get(Random().nextInt(iList.size()))
v3 = iWords.word(Random().nextInt(iWords.words()) + 1) -- the index for word() starts at one

say v1 v2 v3


(define (pick-random-element R)
	(nth (rand (length R)) R))


import random
randomize()

let ls = @["foo", "bar", "baz"]
echo sample(ls)


values := [1, 2, 3];
value := values[(Float->Random() * 100.0)->As(Int) % values->Size()];


let list_rand lst =
  let len = List.length lst in
  List.nth lst (Random.int len)


(import (otus random!))

(define x '("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday"))
(print (list-ref x (rand! (length x))))


Program PickRandomElement (output);

const
  s: array [1..5] of string = ('1234', 'ABCDE', 'Charlie', 'XB56ds', 'lala');

begin
  randomize;
  writeln(s[low(s) + random(length(s))]);
end.


my @array = qw(a b c);
print $array[ rand @array ];


with javascript_semantics
constant s = {1,2.5,"three",{4,{"4 as well"}}}
pp(s[rand(length(s))])


$arr = array('foo', 'bar', 'baz');
$x = $arr[array_rand($arr)];


go =>

  % single element
  println(choice=choice(10)), % single element

  % From a list of numbers
  L = 1..10,
  println([choice(L) : _ in 1..10]),

  % From a string
  S = "pickrandomelement",
  println([choice(S) : _ in 1..10]),
  nl.

% Pick a random number from 1..N
choice(N) = random(1,N), integer(N) => true.

% Pick a random element from a list L.
choice(List) = List[choice(List.length)], list(List) => true.


   declare t(0:9) character (1) static initial
      ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j');
   put ( t(10*random()) );


?- random_member(M, [a, b, c, d, e, f, g, h, i, j]).
M = i.


Procedure.s pickRandomElement(List source.s())
  Protected x = ListSize(source())

  If x > 0
    SelectElement(source(), Random(x - 1)) ;element numbering is zero - based
    ProcedureReturn source()
  EndIf
EndProcedure

;initialize list elements
DataSection
  elements:
  Data.s "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"
EndDataSection

#elementCount = 10
NewList item.s()

Restore elements
Define i
For i = 1 To #elementCount
  AddElement(item())
  Read.s item()
Next

If OpenConsole()
  Print("Source list:  ")
  ForEach item()
    Print(item() + " ")
  Next
  PrintN(#CRLF$)

  Print("Random picks from list:  ")
  For i = 1 To 10
    Print(pickRandomElement(item()) + " ")
  Next

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


>>> import random
>>> random.choice(['foo', 'bar', 'baz'])
'baz'


  [ dup size random peek ]      is pick ( [ --> x )

  randomise
  ' [ 20 33 -15 7 0 ] pick echo cr
  ' pick pick echo


# a vector (letters are builtin)
letters
#  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
# [20] "t" "u" "v" "w" "x" "y" "z"

# picking one element
sample(letters, 1)
# [1] "n"

# picking some elements with repetition, and concatenating to get a word
paste(sample(letters, 10, rep=T), collapse="")
# [1] "episxgcgmt"


#lang racket
(define (pick-item l)
  (list-ref l (random (length l))))


>> random/only collect [repeat i 10 [keep i]]


let fruits = ["apple", "banana", "coconut", "orange", "lychee"]

let pickRand = arr => {
  let len = Js.Array.length(arr)
  let i = Js.Math.random_int(0, len)
  arr[i]
}

Js.log(pickRand(fruits))


/*REXX program picks a   random element   from a list   (tongue in cheek, a visual pun).*/
_=  'hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium'
_=_ 'magnesium aluminum silicon phosphorous sulfur chlorine argon potassium calcium'
_=_ 'scandium titanium vanadium chromium manganese iron cobalt nickel copper zinc gallium'
_=_ 'germanium arsenic selenium bromine krypton rubidium strontium yttrium zirconium'
_=_ 'niobium molybdenum technetium ruthenium rhodium palladium silver cadmium indium tin'
_=_ 'antimony tellurium iodine xenon cesium barium lanthanum cerium praseodymium'
_=_ 'neodymium promethium samarium europium gadolinium terbium dysprosium holmium erbium'
_=_ 'thulium ytterbium lutetium hafnium tantalum tungsten rhenium osmium iridium platinum'
_=_ 'gold mercury thallium lead bismuth polonium astatine radon francium radium actinium'
_=_ 'thorium protactinium uranium neptunium plutonium americium curium berkelium'
_=_ 'californium einsteinium fermium mendelevium nobelium lawrencium rutherfordium dubnium'
_=_ 'seaborgium bohrium hassium meitnerium darmstadtium roentgenium copernicium nihonium'
_=_ 'flerovium moscovium livermorium tennessine oganesson ununenniym unbinvlium umbiunium'

                                                 /*─────  You can't trust atoms,   ─────*/
                                                 /*─────  they make everything up. ─────*/

#= words(_)                                      /*obtain the number of words in list.  */
item= word(_, random(1, #) )                     /*pick a random word (element) in list.*/
say 'random element: '    item                   /*stick a fork in it,  we're all done. */


aList  = "abcdefghij"
for i = 1 to 10
    letter = random(9) + 1
    if letter > 0
       see aList[letter] + nl
    ok
next


%w(north east south west).sample   # => "west"
(1..100).to_a.sample(2)            # => [17, 79]


list$  = "a,b,c,d,e,f,g,h,i,j"
letter = rnd(1) * 10
print "Selected letter:"; word$(list$,letter,",")


extern crate rand;

use rand::Rng;

fn main() {
    let array = [5,1,2,5,6,7,8,1,2,4,5];
    let mut rng = rand::thread_rng();

    println!("{}", rng.choose(&array).unwrap());
}


val a = (1 to 10).toList

println(scala.util.Random.shuffle(a).head)


$ include "seed7_05.s7i";

const proc: main is func
  begin
    writeln(rand([] ("foo", "bar", "baz")));
  end func;


var arr = %w(north east south west);
say arr.rand;
say arr.rand(2).dump;


import Darwin

let myList = [1, 2, 4, 5, 62, 234, 1, -1]
print(myList[Int(arc4random_uniform(UInt32(myList.count)))])


proc randelem {list} {
    lindex $list [expr {int(rand()*[llength $list])}]
}
set x [randelem {1 2 3 4 5}]


$$ MODE TUSCRIPT
list="John'Paul'George'Ringo'Peter'Paul'Mary'Obama'Putin"
sizeList=SIZE(list)
selectedNr=RANDOM_NUMBERS (1,sizeList,1)
selectedItem=SELECT(list,#selectednr)
PRINT "Selecting term ",selectedNr,"  in the list, which was ",selectedItem


@(do (defun randelem (seq)
       [seq (random nil (length seq))]))
@(bind x @(randelem #("a" "b" "c" "d")))


list=(these are some words)
printf '%s\n' "${list[RANDOM%${#list[@]}]}"


# generate a stream (ursa equivalent of a list)
decl string<> str
append "these" "are" "some" "values" str

decl ursa.util.random r
out str<(r.getint (size str))> endl console


Option Explicit

Sub Main_Pick_Random_Element()
    Debug.Print Pick_Random_Element(Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty"))
End Sub

Function Pick_Random_Element(myArray)
    Randomize Timer
    Pick_Random_Element = myArray(Int((Rnd * (UBound(myArray) - LBound(myArray) + 1) + LBound(myArray))))
End Function


Function pick_random(arr)
	Set objRandom = CreateObject("System.Random")
	pick_random = arr(objRandom.Next_2(0,UBound(arr)+1))
End Function

WScript.Echo pick_random(Array("a","b","c","d","e","f"))


Module Program
    Sub Main()
        Dim list As New List(Of Integer)({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
        Dim rng As New Random()
        Dim randomElement = list(rng.Next(list.Count)) ' Upper bound is exclusive.
        Console.WriteLine("I picked element {0}", randomElement)
    End Sub
End Module


import "random" for Random

var rand = Random.new()
var colors = ["red", "green", "blue", "yellow", "pink"]
for (i in 0..4) System.print(colors[rand.int(colors.count)])


set Array = ["Hello","World",1,2,3];
log(Array[rnd(0,?Array-1)]);


code Ran=1, Text=12;
int  List;
[List:= ["hydrogen", "helium", "lithium", "beryllium", "boron"];  \(Thanks REXX)
Text(0, List(Ran(5)));
]