' FB 1.05.0 Win64

Const pi As Double = 3.141592653589793
Randomize

' Generates normally distributed random numbers with mean 0 and standard deviation 1
Function randomNormal() As Double
  Return Cos(2.0 * pi * Rnd) * Sqr(-2.0 * Log(Rnd))
End Function

Dim r(0 To 999) As Double
Dim sum As Double = 0.0

' Generate 1000 normally distributed random numbers
' with mean 1 and standard deviation 0.5
' and calculate their sum
For i As Integer = 0 To 999
   r(i) = 1.0 + randomNormal/2.0
   sum += r(i)
Next

Dim mean As Double = sum / 1000.0

Dim sd As Double
sum = 0.0
' Now calculate their standard deviation
For i As Integer = 0 To 999
  sum += (r(i) - mean) ^ 2.0
Next
sd  = Sqr(sum/1000.0)

Print "Mean is              "; mean
Print "Standard Deviation is"; sd
Print
Print "Press any key to quit"
Sleep


a = new array[[1000], {|x| randomGaussian[1, 0.5]}]


#!/usr/bin/bash

range_contract () (
    add_range () {
        case $(( current - range_start )) in
            0) ranges+=( $range_start )          ;;
            1) ranges+=( $range_start $current ) ;;
            *) ranges+=("$range_start-$current") ;;
        esac
    }

    ranges=()
    range_start=$1
    current=$1
    shift

    for number; do
        if (( number > current+1 )); then
            add_range
            range_start=$number
        fi
        current=$number
    done
    add_range

    x="${ranges[@]}"
    echo ${x// /,}
)

range_contract 0 1 2 4 6 7 8 11 12 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 35 36 37 38 39


window 1

local fn RandomZeroToOne as double
  double result
  cln result = (double)( (rand() % 100000 ) * 0.00001 );
end fn = result

local fn RandomGaussian as double
  double r = fn RandomZeroToOne
end fn = 1 + .5 * ( sqr( -2 * log(r) ) * cos( 2 * pi * r ) )

long i
double mean, std, a(1000)

for i = 1 to 1000
  a(i) = fn RandomGaussian
  mean += a(i)
next
mean = mean / 1000

for i = 1 to 1000
  std += ( a(i) - mean )^2
next
std = std / 1000

print "           Average:  "; mean
print "Standard Deviation:  "; std

HandleEvents


package main

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

const mean = 1.0
const stdv = .5
const n = 1000

func main() {
    var list [n]float64
    rand.Seed(time.Now().UnixNano())
    for i := range list {
        list[i] = mean + stdv*rand.NormFloat64()
    }
    // show computed mean and stdv of list
    var s, sq float64
    for _, v := range list {
        s += v
    }
    cm := s / n
    for _, v := range list {
        d := v - cm
        sq += d * d
    }
    fmt.Printf("mean %.3f, stdv %.3f\n", cm, math.Sqrt(sq/(n-1)))
    // show histogram by hdiv divisions per stdv over +/-hrange stdv
    const hdiv = 3
    const hrange = 2
    var h [1 + 2*hrange*hdiv]int
    for _, v := range list {
        bin := hrange*hdiv + int(math.Floor((v-mean)/stdv*hdiv+.5))
        if bin >= 0 && bin < len(h) {
            h[bin]++
        }
    }
    const hscale = 10
    for _, c := range h {
        fmt.Println(strings.Repeat("*", (c+hscale/2)/hscale))
    }
}


Public Function RangeExtraction(AList) As String
'AList is a variant that is an array, assumed filled with numbers in ascending order
Const RangeDelim = "-"          'range delimiter
Dim result As String
Dim InRange As Boolean
Dim Posn, ub, lb, rangestart, rangelen As Integer

result = ""
'find dimensions of AList
ub = UBound(AList)
lb = LBound(AList)
Posn = lb
While Posn < ub
  rangestart = Posn
  rangelen = 0
  InRange = True
  'try to extend the range
  While InRange
    rangelen = rangelen + 1
    If Posn = ub Then
      InRange = False
    Else
      InRange = (AList(Posn + 1) = AList(Posn) + 1)
      Posn = Posn + 1
    End If
  Wend
  If rangelen > 2 Then 'output the range if it has more than 2 elements
    result = result & "," & Format$(AList(rangestart)) & RangeDelim & Format$(AList(rangestart + rangelen - 1))
  Else 'output the separate elements
    For i = rangestart To rangestart + rangelen - 1
      result = result & "," & Format$(AList(i))
    Next
  End If
  Posn = rangestart + rangelen
Wend
RangeExtraction = Mid$(result, 2) 'get rid of first comma!
End Function

Public Sub RangeTest()
'test function RangeExtraction
'first test with a Variant array
Dim MyList As Variant
MyList = Array(0, 1, 2, 4, 6, 7, 8, 11, 12, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39)
Debug.Print "a) "; RangeExtraction(MyList)

'next test with an array of integers
Dim MyOtherList(1 To 20) As Integer
MyOtherList(1) = -6
MyOtherList(2) = -3
MyOtherList(3) = -2
MyOtherList(4) = -1
MyOtherList(5) = 0
MyOtherList(6) = 1
MyOtherList(7) = 3
MyOtherList(8) = 4
MyOtherList(9) = 5
MyOtherList(10) = 7
MyOtherList(11) = 8
MyOtherList(12) = 9
MyOtherList(13) = 10
MyOtherList(14) = 11
MyOtherList(15) = 14
MyOtherList(16) = 15
MyOtherList(17) = 17
MyOtherList(18) = 18
MyOtherList(19) = 19
MyOtherList(20) = 20
Debug.Print "b) "; RangeExtraction(MyOtherList)
End Sub


Function Range_Extraction(list)
	num = Split(list,",")
	For i = 0 To UBound(num)
		startnum = CInt(num(i))
		sum = startnum
		Do While i <= UBound(num)
			If sum = CInt(num(i)) Then
				If i = UBound(num) Then
					If startnum <> CInt(num(i)) Then
						If startnum + 1 = CInt(num(i)) Then
							Range_Extraction = Range_Extraction & startnum & "," & num(i) & ","
						Else
							Range_Extraction = Range_Extraction & startnum & "-" & num(i) & ","
						End If
					Else
						Range_Extraction = Range_Extraction & startnum & ","
					End If
                                        Exit Do
				Else
					i = i + 1
					sum = sum + 1
				End If
			Else
				If startnum = CInt(num(i-1)) Then
					Range_Extraction = Range_Extraction & startnum & ","
				Else
					If startnum + 1 = CInt(num(i-1)) Then
						Range_Extraction = Range_Extraction & startnum & "," & num(i-1) & ","
					Else
						Range_Extraction = Range_Extraction & startnum & "-" & num(i-1) & ","
					End If
				End If
				i = i - 1
				Exit Do
			End If
		Loop
	Next
	Range_Extraction = Left(Range_Extraction,Len(Range_Extraction)-1)
End Function

WScript.StdOut.Write Range_Extraction("0,1,2,4,6,7,8,11,12,14,15,16,17,18,19,20,21,22,23,24,25,27,28,29,30,31,32,33,35,36,37,38,39")


rnd = new Random()
result = (1..1000).inject([]) { r, i -> r << rnd.nextGaussian() }


import System.Random

pairs :: [a] -> [(a,a)]
pairs (x:y:zs) = (x,y):pairs zs
pairs _        = []

gauss mu sigma (r1,r2) =
  mu + sigma * sqrt (-2 * log r1) * cos (2 * pi * r2)

gaussians :: (RandomGen g, Random a, Floating a) => Int -> g -> [a]
gaussians n g = take n $ map (gauss 1.0 0.5) $ pairs $ randoms g

result :: IO [Double]
result = getStdGen >>= \g -> return $ gaussians 1000 g


var extractRange  = Fn.new { |list|
    if (list.isEmpty) return ""
    var sb = ""
    var first = list[0]
    var prev = first

    var append = Fn.new { |index|
        if (first == prev) {
            sb = sb + prev.toString
        } else if (first == prev - 1) {
            sb = sb + first.toString + "," + prev.toString
        } else {
            sb = sb + first.toString + "-" + prev.toString
        }
        if (index < list.count - 1) sb = sb + ","
    }

    for (i in 1...list.count) {
        if (list[i] == prev + 1) {
            prev = prev + 1
        } else {
            append.call(i)
            first = list[i]
            prev = first
        }
    }
    append.call(list.count - 1)
    return sb
}

var list1 = [-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]
System.print(extractRange.call(list1))
var list2 = [0,  1,  2,  4,  6,  7,  8, 11, 12, 14,
            15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
            25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
            37, 38, 39]
System.print(extractRange.call(list2))


procedure main()
    local L
    L := list(1000)
    every L[1 to 1000] := 1.0 + 0.5 * sqrt(-2.0 * log(?0)) * cos(2.0 * &pi * ?0)

    every write(!L)
end


urand=: [email protected]$ 0:
zrand=: (2 o. 2p1 * urand) * [: %: _2 * [: ^. urand

1 + 0.5 * zrand 100


double[] list = new double[1000];
double mean = 1.0, std = 0.5;
Random rng = new Random();
for(int i = 0;i<list.length;i++) {
  list[i] = mean + std * rng.nextGaussian();
}


fcn range(ns){
   fcn(w){
      if (w.atEnd) return(Void.Stop);
      a:=b:=w.next(); n:=0;
      while(b+1 == (c:=w.peekN(n))){ n+=1; b=c }
      if(n>1){do(n){w.next()}; return("%d-%d".fmt(a,b)); }
      a
   } :
   (0).pump(*,List,_.fp(ns.walker().tweak(Void,Void))).concat(",");
}


function randomNormal() {
  return Math.cos(2 * Math.PI * Math.random()) * Math.sqrt(-2 * Math.log(Math.random()))
}

var a = []
for (var i=0; i < 1000; i++){
  a[i] = randomNormal() / 2 + 1
}


# 15-bit integers generated using the same formula as rand() from the Microsoft C Runtime.
# The random numbers are in [0 -- 32767] inclusive.
# Input: an array of length at least 2 interpreted as [count, state, ...]
# Output: [count+1, newstate, r] where r is the next pseudo-random number.
def next_rand_Microsoft:
  .[0] as $count | .[1] as $state
  | ( (214013 * $state) + 2531011) % 2147483648 # mod 2^31
  | [$count+1 , ., (. / 65536 | floor) ] ;


// version 1.0.6

import java.util.Random

fun main(args: Array<String>) {
    val r = Random()
    val da = DoubleArray(1000)
    for (i in 0 until 1000)  da[i] = 1.0 + 0.5 * r.nextGaussian()
    // now check actual mean and SD
    val mean = da.average()
    val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())
    println("Mean is $mean")
    println("S.D. is $sd")
}


dim a(1000)
mean =1
sd =0.5
for i = 1 to 1000   '   throw 1000 normal variates
   a( i)  =mean +sd *( sqr( -2 * log( rnd( 0))) * cos( 2 * pi * rnd( 0)))
next i


-- Returns a random float value in range 0..1
on randf ()
    n = random(the maxinteger)-1
    return n / float(the maxinteger-1)
end


let mean = 1.0
let stdv = 0.5
let count = 1000

// stats computes a running mean and variance
// See Knuth TAOCP vol 2, 3rd edition, page 232

def stats(xs: [float]) -> float, float: // variance, mean
    var M = xs[0]
    var S = 0.0
    var n = 1.0
    for(xs.length - 1) i:
        let x = xs[i + 1]
        n = n + 1.0
        let mm = (x - M)
        M += mm / n
        S += mm * (x - M)
    return (if n > 0.0: S / n else: 0.0), M

def test_random_normal() -> [float]:
    rnd_seed(floor(seconds_elapsed() * 1000000))
    let r = vector_reserve(typeof return, count)
    for (count):
        r.push(rnd_gaussian() * stdv + mean)
    let cvar, cmean = stats(r)
    let cstdv = sqrt(cvar)
    print concat_string(["Mean: ", string(cmean), ", Std.Deviation: ", string(cstdv)], "")

test_random_normal()


to random.float   ; 0..1
  localmake "max.int lshift -1 -1
  output quotient random :max.int :max.int
end

to random.gaussian
  output product cos random 360  sqrt -2 / ln random.float
end

make "randoms cascade 1000 [fput random.gaussian / 2 + 1 ?] []


local list = {}
for i = 1, 1000 do
  list[i] = 1 + math.sqrt(-2 * math.log(math.random())) * math.cos(2 * math.pi * math.random()) / 2
end


Module CheckIt {
      Function StdDev (A()) {
          \\ A()  has a copy of values
            N=Len(A())
            if N<1 then Error "Empty Array"
            M=Each(A())
            k=0
            \\ make sum, dev same type as A(k)
            sum=A(k)-A(k)
            dev=sum
            \\ find mean
            While M {
                  sum+=Array(M)
            }
            Mean=sum/N
            \\ make a pointet to A()
            P=A()
            \\ subtruct from each item
            P-=Mean

            M=Each(P)
            While M {
                  dev+=Array(M)*Array(M)
            }
            \\ as pointer to arrray
             =(if(dev>0->Sqrt(dev/N), 0), Mean)
      }
      Function randomNormal {
            \\ by default all numbers are double
            \\ cos() get degrees
          =1+Cos(360 * rnd) * Sqrt(-2 * Ln(rnd)) /2
      }
      \\ fill array calling  randomNormal() for each item
      Dim A(1000)<<randomNormal()
      \\ we can pass a pointer to array and place it to stack of values
      DisplayMeanAndStdDeviation(A())  ' mean ~ 1 std deviation ~0.5
      \\ check M2000 rnd only
      Dim B(1000)<<rnd
      DisplayMeanAndStdDeviation(B())  ' mean ~ 0.5 std deviation ~0.28

      DisplayMeanAndStdDeviation((0,0,14,14))  ' mean = 7 std deviation = 7
      DisplayMeanAndStdDeviation((0,6,8,14))  ' mean = 7 std deviation = 5
      DisplayMeanAndStdDeviation((6,6,8,8))  ' mean = 7 std deviation = 1

      Sub DisplayMeanAndStdDeviation(A)
            \\ push to stack all items of an array (need an array pointer)
            Push  ! StdDev(A)
            \\ read from strack two numbers
            Print "Mean is               "; Number
            Print "Standard Deviation is "; Number
      End Sub
}
Checkit


with(Statistics):
Sample(Normal(1, 0.5), 1000);


load(distrib)$

random_normal(1.0, 0.5, 1000);


arr = #()
for i in 1 to 1000 do
(
    a = random 0.0 1.0
    b = random 0.0 1.0
    c = 1.0 + 0.5 * sqrt (-2*log a) * cos (360*b) -- Maxscript cos takes degrees
    append arr c
)


numeric col[];

m := 0;               % m holds the mean, for testing purposes
for i = 1 upto 1000:
  col[i] := 1 + .5normaldeviate;
  m := m + col[i];
endfor

% testing
m := m / 1000;       % finalize the computation of the mean

s := 0;              % in s we compute the standard deviation
for i = 1 upto 1000:
  s := s + (col[i] - m)**2;
endfor
s := sqrt(s / 1000);

show m, s;    % and let's show that really they get what we wanted
end


randNormal = function(mean=0, stddev=1)
    return mean + sqrt(-2 * log(rnd,2.7182818284)) * cos(2*pi*rnd) * stddev
end function

x = []
for i in range(1,1000)
    x.push randNormal(1, 0.5)
end for


import java.util.Random

list = double[999]
mean = 1.0
std = 0.5
rng = Random.new
0.upto(998) do | i |
    list[i] = mean + std * rng.nextGaussian
end


П7	<->	П8	1/x	П6	ИП6	П9	СЧ	П6	1/x
ln	ИП8	*	2	*	КвКор	ИП9	2	*	пи
*	sin	*	ИП7	+	С/П	БП	05


MODULE Rand EXPORTS Main;

IMPORT Random;
FROM Math IMPORT log, cos, sqrt, Pi;

VAR rands: ARRAY [1..1000] OF LONGREAL;

(* Normal distribution. *)
PROCEDURE RandNorm(): LONGREAL =
  BEGIN
    WITH rand = NEW(Random.Default).init() DO
      RETURN
        sqrt(-2.0D0 * log(rand.longreal())) * cos(2.0D0 * Pi * rand.longreal());
    END;
  END RandNorm;

BEGIN
  FOR i := FIRST(rands) TO LAST(rands) DO
    rands[i] := 1.0D0 + 0.5D0 * RandNorm();
  END;
END Rand.


list = {0} * 1000
mean = 1.0; std = 0.5
rng  = new(Nanoquery.Util.Random)

for i in range(0, len(list) - 1)
        list[i] = mean + std * rng.getGaussian()
end


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

import java.math.BigDecimal
import java.math.MathContext

-- prologue
numeric digits 20

-- get input, set defaults
parse arg dp mu sigma ec .
if mu    = '' | mu    = '.' then mean             =  1.0; else mean             = mu
if sigma = '' | sigma = '.' then stdDeviation     =  0.5; else stdDeviation     = sigma
if dp    = '' | dp    = '.' then displayPrecision =    1; else displayPrecision = dp
if ec    = '' | ec    = '.' then elements         = 1000; else elements         = ec

-- set up
RNG = Random()
numberList = java.util.List
numberList = ArrayList()

-- generate list of random numbers
loop for elements
  rn = mean + stdDeviation * RNG.nextGaussian()
  numberList.add(BigDecimal(rn, MathContext.DECIMAL128))
  end

-- report
say "Mean:              " mean
say "Standard Deviation:" stdDeviation
say "Precision:         " displayPrecision
say
drawBellCurve(numberList, displayPrecision)

return

-- -----------------------------------------------------------------------------
method drawBellCurve(numberList = java.util.List, precision) static
  Collections.sort(numberList)
  val = BigDecimal
  lastN = ''
  nextN = ''
  loop val over numberList
    nextN = Rexx(val.toPlainString()).format(5, precision)
    select
      when lastN = '' then nop
      when lastN \= nextN then say lastN
      otherwise nop
      end
    say '*\-'
    lastN = nextN
    end val
  say lastN

  return


import random, stats, strformat

var rs: RunningStat

randomize()

for _ in 1..5:
  for _ in 1..1000: rs.push gauss(1.0, 0.5)
  echo &"mean: {rs.mean:.5f}    stdDev: {rs.standardDeviation:.5f}"


bundle Default {
  class RandomNumbers {
    function : Main(args : String[]) ~ Nil {
      rands := Float->New[1000];
      for(i := 0; i < rands->Size(); i += 1;) {
        rands[i] := 1.0 + 0.5 * RandomNormal();
      };

      each(i : rands) {
        rands[i]->PrintLine();
      };
    }

    function : native : RandomNormal() ~ Float {
      return (2 * Float->Pi() * Float->Random())->Cos() * (-2 * (Float->Random()->Log()))->SquareRoot();
    }
  }
}


let pi = 4. *. atan 1.;;
let random_gaussian () =
  1. +. sqrt (-2. *. log (Random.float 1.)) *. cos (2. *. pi *. Random.float 1.);;
let a = Array.init 1000 (fun _ -> random_gaussian ());;


/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=0.5*/
  pi=RxCalcPi()                     /* get value of pi                */
  Parse Arg n seed .                /* allow specification of N & seed*/
  If n==''|n==',' Then
    n=1000                          /* N  is the size of the array.   */
  If seed\=='' Then
    Call random,,seed               /* use seed for repeatable RANDOM#*/
  mean=1                            /* desired new mean (arith. avg.) */
  sd=1/2                            /* desired new standard deviation.*/
  Do g=1 For n                      /* generate N uniform random nums.*/
    n.g=random(0,1e5)/1e5           /* REXX gens uniform rand integers*/
    End

  Say '              old mean=' mean()
  Say 'old standard deviation=' stddev()
  Say
  Do j=1 To n-1 By 2
    m=j+1
                                    /*use Box-Muller method           */
    _=sd*RxCalcPower(-2*RxCalcLog(n.j),.5)*RxCalcCos(2*pi*n.m,,'R')+mean
    n.m=sd*RxCalcpower(-2*RxCalcLog(n.j),.5)*RxCalcSin(2*pi*n.m,,'R')+,
  mean                              /* rand # must be 0???1.          */
    n.j=_
    End                             /* j                              */
  Say '              new mean=' mean()
  Say 'new standard deviation=' stddev()
  Exit
mean:
  _=0
  Do k=1 For n
    _=_+n.k
    End
  Return _/n
stddev:
  _avg=mean()
  _=0
  Do k=1 For n
    _=_+(n.k-_avg)**2
    End
  Return RxCalcPower(_/n,.5)

:: requires rxmath library


rnormal()={
	my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296)),u1=random(2^pr)*1.>>pr,u2=random(2^pr)*1.>>pr);
	sqrt(-2*log(u1))*cos(2*Pi*u2)  \\ in previous version "u1" instead of "u2" was used --> has given crap distribution
	\\ Could easily be extended with a second normal at very little cost.
};
vector(1000,unused,rnormal()/2+1)


function rnorm (mean, sd: real): real;
 {Calculates Gaussian random numbers according to the Box-Müller approach}
var
  u1, u2: real;
begin
  u1 := random;
  u2 := random;
  rnorm := mean * abs(1 + sqrt(-2 * (ln(u1))) * cos(2 * pi * u2) * sd);
       /* error !?! Shouldn't it be "mean +" instead of "mean *" ? */
end;


function RandomNormal()
    return sqrt(-2*log(rnd())) * cos(2*PI*rnd())
end function

sequence s = repeat(0,1000)
for i=1 to length(s) do
    s[i] = 1 + 0.5 * RandomNormal()
end for


include ..\Utilitys.pmt

def RandomNormal
    drop rand log -2 * sqrt 2 pi * rand * cos * 0.5 * 1 +
enddef

1000 var n
0 n repeat

getid RandomNormal map

dup
sum n / var mean
"Mean: " print mean print nl

0 swap n for
    get mean - 2 power rot + swap
endfor
swap n / sqrt "Standard deviation: " print print


function random() {
    return mt_rand() / mt_getrandmax();
}

$pi 	= pi();          // Set PI

$a = array();
for ($i = 0; $i < 1000; $i++) {
    $a[$i] = 1.0 + ((sqrt(-2 * log(random())) * cos(2 * $pi * random())) * 0.5);

}


main =>
   _ = random2(), % random seed
   G = [gaussian_dist(1,0.5) : _ in 1..1000],
   println(first_10=G[1..10]),
   println([mean=avg(G),stdev=stdev(G)]),
   nl.

% Gaussian (Normal) distribution, Box-Muller algorithm
gaussian01() = Y =>
    U = frand(0,1),
    V = frand(0,1),
    Y = sqrt(-2*log(U))*sin(2*math.pi*V).

gaussian_dist(Mean,Stdev) = Mean + (gaussian01() * Stdev).

% Variance of Xs
variance(Xs) = Variance =>
    Mu = avg(Xs),
    N  = Xs.len,
    Variance = sum([ (X-Mu)**2 : X in Xs ]) / N.

% Standard deviation
stdev(Xs) = sqrt(variance(Xs)).


(load "@lib/math.l")

(de randomNormal ()  # Normal distribution, centered on 0, std dev 1
   (*/
      (sqrt (* -2.0 (log (rand 0 1.0))))
      (cos (*/ 2.0 pi (rand 0 1.0) `(* 1.0 1.0)))
      1.0 ) )

(seed (time))                                      # Randomize

(let Result
   (make                                           # Build list
      (do 1000                                     # of 1000 elements
         (link (+ 1.0 (/ (randomNormal) 2))) ) )
   (for N (head 7 Result)                          # Print first 7 results
      (prin (format N *Scl) " ") ) )


/* CONVERTED FROM WIKI FORTRAN */
Normal_Random: procedure options (main);
   declare (array(1000), pi, temp,
            mean initial (1.0), sd initial (0.5)) float (18);
   declare (i, n) fixed binary;

   n = hbound(array, 1);
   pi = 4.0*ATAN(1.0);
   array = random(); /* Uniform distribution */
   /* Now convert to normal distribution */
   DO i = 1 to n-1 by 2;
      temp = sd * SQRT(-2.0*LOG(array(i))) * COS(2*pi*array(i+1)) + mean;
      array(i+1) = sd * SQRT(-2.0*LOG(array(i))) * SIN(2*pi*array(i+1)) + mean;
      array(i) = temp;
   END;
   /* Check mean and standard deviation */
   mean = SUM(array)/n;
   sd = SQRT(SUM((array - mean)**2)/n);
   put skip edit ( "Mean = ", mean ) (a, F(18,16) );
   put skip edit ( "Standard Deviation = ", sd) (a, F(18,16));
END Normal_Random;


DECLARE
  --The desired collection
  type t_coll is table of number index by binary_integer;
  l_coll t_coll;

  c_max pls_integer := 1000;
BEGIN
   FOR l_counter IN 1 .. c_max
   LOOP
      -- dbms_random.normal delivers normal distributed random numbers with a mean of 0 and a variance of 1
      -- We just adjust the values and get the desired result:
      l_coll(l_counter) := DBMS_RANDOM.normal * 0.5 + 1;
      DBMS_OUTPUT.put_line (l_coll(l_counter));
   END LOOP;
END;


;;; Choose radians as arguments to trigonometic functions
true -> popradians;

;;; procedure generating standard normal distribution
define random_normal() -> result;
lvars r1 = random0(1.0), r2 = random0(1.0);
     cos(2*pi*r1)*sqrt(-2*log(r2)) -> result
enddefine;

lvars array, i;

;;; Put numbers on the stack
for i from 1 to 1000 do 1.0+0.5*random_normal() endfor;
;;; collect them into array
consvector(1000) -> array;


function Get-RandomNormal
    {
    [CmdletBinding()]
    Param ( [double]$Mean, [double]$StandardDeviation )

    $RandomNormal = $Mean + $StandardDeviation * [math]::Sqrt( -2 * [math]::Log( ( Get-Random -Minimum 0.0 -Maximum 1.0 ) ) ) * [math]::Cos( 2 * [math]::PI * ( Get-Random -Minimum 0.0 -Maximum 1.0 ) )

    return $RandomNormal
    }

#  Standard deviation function for testing
function Get-StandardDeviation
    {
    [CmdletBinding()]
    param ( [double[]]$Numbers )

    $Measure = $Numbers | Measure-Object -Average
    $PopulationDeviation = 0
    ForEach ($Number in $Numbers) { $PopulationDeviation += [math]::Pow( ( $Number - $Measure.Average ), 2 ) }
    $StandardDeviation = [math]::Sqrt( $PopulationDeviation / ( $Measure.Count - 1 ) )
    return $StandardDeviation
    }

#  Test
$RandomNormalNumbers = 1..1000 | ForEach { Get-RandomNormal -Mean 1 -StandardDeviation 0.5 }

$Measure = $RandomNormalNumbers | Measure-Object -Average

$Stats = [PSCustomObject]@{
    Count             = $Measure.Count
    Average           = $Measure.Average
    StandardDeviation = Get-StandardDeviation -Numbers $RandomNormalNumbers
}

$Stats | Format-List


Procedure.f RandomNormal()
   ; This procedure can return any real number.
   Protected.f x1, x2

   ; random numbers from the open interval ]0, 1[
   x1 = (Random(999998)+1) / 1000000       ; must be > 0 because of Log(x1)
   x2 = (Random(999998)+1) / 1000000

   ProcedureReturn Sqr(-2*Log(x1)) * Cos(2*#PI*x2)
EndProcedure

Define i, n=1000

Dim a.q(n-1)
For i = 0 To n-1
   a(i) = 1 + 0.5 * RandomNormal()
Next


>>> import random
>>> values = [random.gauss(1, .5) for i in range(1000)]
>>>


# For reproducibility, set the seed:
set.seed(12345L)

result <- rnorm(1000, mean = 1, sd = 0.5)


#lang racket
(for/list ([i 1000])
  (add1 (* (sqrt (* -2 (log (random)))) (cos (* 2 pi (random))) 0.5)))


sub randnorm ($mean, $stddev) {
    $mean + $stddev * sqrt(-2 * log rand) * cos(2 * pi * rand)
}

my @nums = randnorm(1, 0.5) xx 1000;

# Checking
say my $mean = @nums R/ [+] @nums;
say my $stddev = sqrt $mean**2 R- @nums R/ [+] @nums X** 2;


define PI
   -1 acos

define rand1
   9999999 choose 1 + 10000000.0 /

define randNormal
   rand1 PI * 2 * cos
   rand1 log -2 * sqrt
   *
   2 / 1 +

1000 each drop randNormal "%f\n" print


/*REXX pgm generates 1,000 normally distributed numbers:  mean=1,  standard deviation=½.*/
numeric digits 20                                /*the default decimal digit precision=9*/
parse arg n seed .                               /*allow specification of N and the seed*/
if n==''  |  n==","    then n=1000               /*N:    is the size of the array.      */
if datatype(seed,'W')  then call random ,,seed   /*SEED: for repeatable random numbers. */
newMean=1                                        /*the desired new mean (arithmetic avg)*/
sd=1/2                                           /*the desired new standard deviation.  */
       do g=1  for n                             /*generate  N uniform random #'s (0,1].*/
       #.g = random(1, 1e5)  /  1e5              /*REXX's RANDOM BIF generates integers.*/
       end   /*g*/                               /* [↑]  random integers ──► fractions. */
say '              old mean='   mean()
say 'old standard deviation='   stdDev()
call pi;       pi2=pi * 2                        /*define   pi    and also    2 * pi.   */
say
       do j=1  to n-1  by 2;    m=j+1            /*step through the iterations by two.  */
           _=sd *  sqrt(ln(#.j) * -2)            /*calculate the  used-twice expression.*/
       #.j=_ * cos(pi2 * #.m)  +  newMean        /*utilize the  Box─Muller method.      */
       #.m=_ * sin(pi2 * #.m)  +  newMean        /*random number must be:      (0,1]    */
       end   /*j*/
say '              new mean='     mean()
say 'new standard deviation='     stdDev()
exit                                             /*stick a fork in it,  we're all done. */
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
mean:   _=0;                   do k=1  for n;  _=_ + #.k;              end;                return      _/n
stdDev: _avg=mean();  _=0;     do k=1  for n;  _=_ + (#.k - _avg)**2;  end;                return sqrt(_/n)
e:      e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e   /*digs overkill*/
pi:     pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi  /*  "      "   */
r2r:    return arg(1)  //  (pi() * 2)                                                                 /*normalize ang*/
sin:    procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1)
.sincos:parse arg z,_,i; x=x*x; p=z;    do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end;     return z
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
ln:     procedure; parse arg x,f;   call e;   ig= x>1.5;     is=1 - 2 * (ig\==1);           ii=0;             xx=x
          do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end
        xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
cos:    procedure; parse arg x;       x=r2r(x);        a=abs(x);               hpi=pi * .5
            numeric fuzz min(6, digits() - 3);      if a=pi    then return -1
            if a=hpi | a=hpi*3  then return 0;      if a=pi/3  then return .5
            if a=pi * 2/3       then return -.5;                    return .sinCos(1,1,-1)
/*───────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
sqrt:   procedure; parse arg x; if x=0  then return 0;  d=digits();  numeric digits; h=d+6
        numeric form; parse value format(x,2,1,,0) 'E0'  with  g 'E' _ .;  g=g * .5'e'_ %2
        m.=9;     do j=0  while h>9;       m.j=h;                h=h%2 + 1;      end /*j*/
                  do k=j+5  to 0  by -1;   numeric digits m.k;   g=(g+x/g)*.5;   end /*k*/
        numeric digits d;     return g/1


for i = 1 to 10
    see random(i) + nl
next i


Array.new(1000) { 1 + Math.sqrt(-2 * Math.log(rand)) * Math.cos(2 * Math::PI * rand) }


extern crate rand;
use rand::distributions::{Normal, IndependentSample};

fn main() {
    let mut rands = [0.0; 1000];
    let normal = Normal::new(1.0, 0.5);
    let mut rng = rand::thread_rng();
    for num in rands.iter_mut() {
        *num = normal.ind_sample(&mut rng);
    }
}


/* Generate 1000 random numbers with mean 1 and standard deviation 0.5.
  SAS version 9.2 was used to create this code.*/

data norm1000;
  call streaminit(123456);
/* Set the starting point, so we can replicate results.
   If you want different results each time, comment the above line. */
  do i=1 to 1000;
    r=rand('normal',1,0.5);
    output;
  end;
run;


class MAIN is
  main is
    a:ARRAY{FLTD} := #(1000);
    i:INT;

    RND::seed(2010);
    loop i := 1.upto!(1000) - 1;
      a[i] := 1.0d + 0.5d * RND::standard_normal;
    end;

    -- testing the distribution
    mean ::= a.reduce(bind(_.plus(_))) / a.size.fltd;
    #OUT + "mean " + mean + "\n";
    a.map(bind(_.minus(mean)));
    a.map(bind(_.pow(2.0d)));
    dev ::= (a.reduce(bind(_.plus(_))) / a.size.fltd).sqrt;
    #OUT + "dev  " + dev + "\n";
  end;
end;


List.fill(1000)(1.0 + 0.5 * scala.util.Random.nextGaussian)


; linear congruential generator given in C99 section 7.20.2.1
(define ((c-rand seed)) (set! seed (remainder (+ (* 1103515245 seed) 12345) 2147483648)) (quotient seed 65536))

; uniform real numbers in open interval (0, 1)
(define (unif-rand seed) (let ((r (c-rand seed))) (lambda () (/ (+ (r) 1) 32769.0))))

; Box-Muller method to generate normal distribution
(define (normal-rand unif m s)
(let ((? #t) (! 0.0) (twopi (* 2.0 (acos -1.0))))
(lambda ()
   (set! ? (not ?))
   (if ? !
         (let ((a (sqrt (* -2.0 (log (unif))))) (b (* twopi (unif))))
              (set! ! (+ m (* s a (sin b))))
              (+ m (* s a (cos b))))))))

(define rnorm (normal-rand (unif-rand 0) 1.0 0.5))

; auxiliary function to get a list of 'n random numbers from generator 'r
(define (rand-list r n) = (if (zero? n) '() (cons (r) (rand-list r (- n 1)))))

(define v (rand-list rnorm 1000))

v
#|
(-0.27965824722565835
 -0.8870860825789542
 0.6499618744638194
 0.31336141955110863
 ...
 0.5648743998193049
 0.8282656735558756
 0.6399951934564637
 0.7699535302478072)
|#

; check mean and standard deviation
(define (mean-sdev v)
(let loop ((v v) (a 0) (b 0) (n 0))
(if (null? v)
    (let ((mean (/ a n)))
         (list mean (sqrt (/ (- b (* n mean mean)) (- n 1)))))
    (let ((x (car v)))
         (loop (cdr v) (+ a x) (+ b (* x x)) (+ n 1))))))

(mean-sdev v)
; (0.9562156817697293 0.5097087109575911)


$ include "seed7_05.s7i";
  include "float.s7i";
  include "math.s7i";

const func float: frand is func  # Uniform distribution, (0..1]
  result
    var float: frand is 0.0;
  begin
    repeat
      frand := rand(0.0, 1.0);
    until frand <> 0.0;
  end func;

const func float: randomNormal is  # Normal distribution, centered on 0, std dev 1
  return sqrt(-2.0 * log(frand)) * cos(2.0 * PI * frand);

const proc: main is func
  local
    var integer: i is 0;
    var array float: rands is 1000 times 0.0;
  begin
    for i range 1 to length(rands) do
      rands[i] := 1.0 + 0.5 * randomNormal;
    end for;
  end func;


var arr = 1000.of { 1 + (0.5 * sqrt(-2 * 1.rand.log) * cos(Num.tau * 1.rand)) }
arr.each { .say }


val seed = 0w42;
val gen = Rand.mkRandom seed;
fun random_gaussian () =
  1.0 + Math.sqrt (~2.0 * Math.ln (Rand.norm (gen ()))) * Math.cos (2.0 * Math.pi * Rand.norm (gen ()));
val a = List.tabulate (1000, fn _ => random_gaussian ());


clear all
set obs 1000
gen x=rnormal(1,0.5)


package require Tcl 8.5
variable ::pi [expr acos(0)]
proc ::tcl::mathfunc::nrand {} {
    expr {sqrt(-2*log(rand())) * cos(2*$::pi*rand())}
}

set mean 1.0
set stddev 0.5
for {set i 0} {$i < 1000} {incr i} {
    lappend result [expr {$mean + $stddev*nrand()}]
}


for (%i = 0; %i < 1000; %i++)
	%list[%i] = 1 + mSqrt(-2 * mLog(getRandom())) * mCos(2 * $pi * getRandom());


#import nat
#import flo

pop_stats("mu","sigma") = plus/*"mu"+ times/*"sigma"+ Z*+ iota

sample_stats("mu","sigma") = plus^*D(minus/"mu"+ mean,~&)+ vid^*D(div\"sigma"+ stdev,~&)+ Z*+ iota

#cast %eWL

test =

^(mean,stdev)* <
   pop_stats(1.,0.5) 1000,
   sample_stats(1.,0.5) 1000>


LOCAL i As Integer, m As Double, n As Integer, sd As Double
py = PI()
SET TALK OFF
SET DECIMALS TO 6
CREATE CURSOR gdev (deviate B(6))
RAND(-1)
n = 1000
m = 1
sd = 0.5
CLEAR
FOR i = 1 TO n
	INSERT INTO gdev VALUES (GaussDev(m, 1/sd))
ENDFOR
CALCULATE AVG(deviate), STD(deviate) TO m, sd
? "Mean", m, "Std Dev", sd
SET TALK ON
SET DECIMALS TO

FUNCTION GaussDev(mean As Double, sdev As Double) As Double
LOCAL z As Double
z = SQRT(-2*LOG(RAND()))*COS(py*RAND())
IF sdev # 0
	z = mean + z/sdev
ENDIF
RETURN z
ENDFUNC


import "random" for Random

var rand = Random.new()

var randNormal = Fn.new { (-2 * rand.float().log).sqrt * (2 * Num.pi * rand.float()).cos }

var stdDev = Fn.new { |a, m|
    var c = a.count
    return ((a.reduce(0) { |acc, x| acc + x*x } - m*m*c) / c).sqrt
}

var n = 1000
var numbers = List.filled(n, 0)
var mu = 1
var sigma = 0.5
var sum = 0
for (i in 0...n) {
    numbers[i] = mu + sigma*randNormal.call()
    sum = sum + numbers[i]
}
var mean = sum / n
System.print("Actual mean   : %(mean)")
System.print("Actual std dev: %(stdDev.call(numbers, mean))")


func random_normal(count) {
   return sqrt(-2*log(random(count))) * cos(2*pi*random(count));
}


fcn mkRand(mean,sd){ //normally distributed random w/mean & standard deviation
   pi:=(0.0).pi;    // using the Box–Muller transform
   rz1:=fcn{1.0-(0.0).random(1)}  // from [0,1) to (0,1]
   return('wrap(){((-2.0*rz1().log()).sqrt() * (2.0*pi*rz1()).cos())*sd + mean })
}


10 RANDOMIZE 0 : REM seeds random number generator based on uptime
20 DIM a(1000)
30 CLS
40 FOR i = 1 TO 1000
50 LET a(i) = 1 + SQR(-2 * LN(RND)) * COS(2 * PI * RND)
60 NEXT i


LookUpTable: db $00,$03,$06,$09,$12             ;a sequence of pre-defined bytes

MyString: db "Hello World!",0                   ;a null-terminated string

GraphicsData: incbin "C:\game\gfx\tilemap.chr"  ;a file containing the game's graphics


ByteData:
DC.B $01,$02,$03,$04,$05
even
WordData:
DC.W $01,$02
DC.W $03,$04
;the above was the same as DC.W $0001,$0002,$0003,$0004
LongData:
DC.L $00000001,$00000002,$00000004,$00000008

MyString:
DC.B "Hello World!",0 ;a null terminator will not be automatically placed.
even


? 0 : ? -326.12E-5 : ? HELLO : ? "HELLO" : ? "HELLO


'In FB there is no substr function, then
'Function taken fron the https://www.freebasic.net/forum/index.php

Function substr(Byref soriginal As String, Byref spattern As Const String, Byref sreplacement As Const String) As String
    ' in <soriginal> replace all occurrences of <spattern> by <sreplacement>
    Dim As Uinteger p, q

    If sreplacement <> spattern Then
        p = Instr(soriginal, spattern)
        If p Then
            q = Len(sreplacement)
            If q = 0 Then q = 1
            Do
                soriginal = Left(soriginal, p - 1) + sreplacement + Mid(soriginal, p + Len(spattern))
                p = Instr(p + q, soriginal, spattern)
            Loop Until p = 0
        End If
    End If
    Return soriginal
End Function

Dim As String text(1 To 3)
text(1) = "This is 'first' example for quoting"
text(2) = "This is second 'example' for quoting"
text(3) = "This is third example 'for' quoting"

For n As Integer = 1 To Ubound(text)
    Print !"text for quoting:\n"; text(n)
    Print !"quoted text:\n"; substr(text(n),"'",""); !"\n"
Next n
Sleep


package main

import (
    "fmt"
    "os"
    "regexp"
    "strconv"
)

/* Quoting constructs in Go. */

// In Go a Unicode codepoint, expressed as a 32-bit integer, is referred to as a 'rune'
// but the more familiar term 'character' will be used instead here.

// Character literal (single quotes).
// Can contain any single character including an escaped character.
var (
    rl1 = 'a'
    rl2 = '\'' // single quote can only be included in escaped form
)

// Interpreted string literal (double quotes).
// A sequence of characters including escaped characters.
var (
    is1 = "abc"
    is2 = "\"ab\tc\"" // double quote can only be included in escaped form
)

// Raw string literal(single back quotes).
// Can contain any character including a 'physical' new line but excluding back quote.
// Escaped characters are interpreted literally i.e. `\n` is backslash followed by n.
// Raw strings are typically used for hard-coding pieces of text perhaps
// including single and/or double quotes without the need to escape them.
// They are particularly useful for regular expressions.
var (
    rs1 = `
first"
second'
third"
`
    rs2 = `This is one way of including a ` + "`" + ` in a raw string literal.`
    rs3 = `\d+` // a sequence of one or more digits in a regular expression
)

func main() {
    fmt.Println(rl1, rl2) // prints the code point value not the character itself
    fmt.Println(is1, is2)
    fmt.Println(rs1)
    fmt.Println(rs2)
    re := regexp.MustCompile(rs3)
    fmt.Println(re.FindString("abcd1234efgh"))

    /* None of the above quoting constructs can deal directly with interpolation.
       This is done instead using library functions.
    */

    // C-style using %d, %f, %s etc. within a 'printf' type function.
    n := 3
    fmt.Printf("\nThere are %d quoting constructs in Go.\n", n)

    // Using a function such as fmt.Println which can take a variable
    // number of arguments, of any type, and print then out separated by spaces.
    s := "constructs"
    fmt.Println("There are", n, "quoting", s, "in Go.")

    // Using the function os.Expand which requires a mapper function to fill placeholders
    // denoted by ${...} within a string.
    mapper := func(placeholder string) string {
        switch placeholder {
        case "NUMBER":
            return strconv.Itoa(n)
        case "TYPES":
            return s
        }
        return ""
    }
    fmt.Println(os.Expand("There are ${NUMBER} quoting ${TYPES} in Go.", mapper))
}


NB. no trailing linefeed
A=: '1 2 3'

NB. removing linefeed
A=: 0 : 0-.LF
1 2 3
)

NB. removing linefeed
A=: {{)n
1 2 3
}}-.LF


julia> str = "Hello, world.\n"
"Hello, world.\n"

julia> """Contains "quote" characters and
a newline"""
"Contains \"quote\" characters and \na newline"


s1 = "This is a double-quoted 'string' with embedded single-quotes."
s2 = 'This is a single-quoted "string" with embedded double-quotes.'
s3 = "this is a double-quoted \"string\" with escaped double-quotes."
s4 = 'this is a single-quoted \'string\' with escaped single-quotes.'
s5 = [[This is a long-bracket "'string'" with embedded single- and double-quotes.]]
s6 = [=[This is a level 1 long-bracket ]]string[[ with [[embedded]] long-brackets.]=]
s7 = [==[This is a level 2 long-bracket ]=]string[=[ with [=[embedded]=] level 1 long-brackets, etc.]==]
s8 = [[This is
a long-bracket string
with embedded
line feeds]]
s9 = "any \0 form \1 of \2 string \3 may \4 contain \5 raw \6 binary \7 data \xDB"
print(s1)
print(s2)
print(s3)
print(s4)
print(s5)
print(s6)
print(s7)
print(s8)
print(s9) -- with audible "bell" from \7 if supported by os
print("some raw binary:", #s9, s9:byte(5), s9:byte(12), s9:byte(17))


echo "A simple string."
echo "A simple string including tabulation special character \\t: \t."

echo """
First part of a multiple string,
followed by second part
and third part.
"""

echo r"A raw string containing a \."

# Interpolation in strings.
import strformat
const C = "constant"
const S = fmt"A string with interpolation of a {C}."
echo S
var x = 3
echo fmt"A string with interpolation of expression “2 * x + 3”: {2 * x + 3}."
echo fmt"Displaying “x” with an embedded format: {x:05}."

# Regular expression string.
import re
let r = re"\d+"

# Pegs string.
import pegs
let e = peg"\d+"

# Array literal.
echo [1, 2, 3]        # Element type if implicit ("int" here).
echo [byte(1), 2, 3]  # Element type is specified by the first element type.
echo [byte 1, 2, 3]   # An equivalent way to specify the type.

echo @[1, 2, 3]       # Sequence of ints.

# Tuples.
echo ('a', 1, true)   # Tuple without explicit field names.
echo (x: 1, y: 2)     # Tuple with two int fields "x" and "y".


/*REXX program demonstrates various ways to express a string of characters  or  numbers.*/
a= 'This is one method of including a '' (an apostrophe) within a string.'
b= "This is one method of including a ' (an apostrophe) within a string."

                                                 /*sometimes,  an apostrophe is called  */
                                                 /*a quote.                             */
/*──────────────────────────────────────────────────────────────────────────────────────*/
c= "This is one method of including a "" (a double quote) within a string."
d= 'This is one method of including a " (a double quote) within a string.'

                                                 /*sometimes,  a double quote is also   */
                                                 /*called a quote,  which can make for  */
                                                 /*some confusion and bewilderment.     */
/*──────────────────────────────────────────────────────────────────────────────────────*/
f= 'This is one method of expressing a long literal by concatenations,  the '     ||  ,
   'trailing character of the above clause must contain a trailing '              ||  ,
   'comma (,)  === note the embedded trailing blank in the above 2 statements.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
g= 'This is another method of expressing a long literal by '         ,
   "abutments,  the trailing character of the above clause must "    ,
   'contain a trailing comma (,)'
/*──────────────────────────────────────────────────────────────────────────────────────*/
h= 'This is another method of expressing a long literal by '       ,  /*still continued.*/
   "abutments,  the trailing character of the above clause must "                  ,
   'contain a trailing comma (,)  ---  in this case, the comment  /* ... */  is '   ,
   'essentially is not considered to be "part of" the REXX clause.'
/*──────────────────────────────────────────────────────────────────────────────────────*/
i= 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

                                                 /*This is one way to express a list of */
                                                 /*numbers that don't have a sign.      */
/*──────────────────────────────────────────────────────────────────────────────────────*/
j= 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,
   71 73 79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181

                                                 /*This is one way to express a long    */
                                                 /*list of numbers that don't have a    */
                                                 /*sign.                                */
                                                 /*Note that this form of continuation  */
                                                 /*implies a blank is abutted to first  */
                                                 /*part of the REXX statement.          */
                                                 /*Also note that some REXXs have a     */
                                                 /*maximum clause length.               */
/*──────────────────────────────────────────────────────────────────────────────────────*/
k= 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,
   71 73   79 83 89 97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181

                                                 /*The  J  and  K  values are identical,*/
                                                 /*superfluous and extraneous blanks are*/
                                                 /*ignored.                             */
/*──────────────────────────────────────────────────────────────────────────────────────*/
l= '-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'

                                                 /*This is one way to express a list of */
                                                 /*numbers that have a sign.            */
/*──────────────────────────────────────────────────────────────────────────────────────*/
m= a b c d f g h i j k l                         /*this will create a list of all the   */
                                                 /*listed strings used  (so far)  into  */
                                                 /*the variable     L      (with an     */
                                                 /*intervening blank between each       */
                                                 /*variable's value.                    */


text = list(3)

text[1] = "This is 'first' example for quoting"
text[2] = "This is second 'example' for quoting"
text[3] = "This is third example 'for' quoting"

for n = 1 to len(text)
    see "text for quoting: " + nl + text[n] + nl
    str = substr(text[n],"'","")
    see "quoted text:" + nl + str + nl + nl
next


import "/fmt" for Fmt

// simple string literal
System.print("Hello world!")

// string literal including an escape sequence
System.print("Hello tabbed\tworld!")

// interpolated string literal
var w = "world"
System.print("Hello interpolated %(w)!")

// 'printf' style
Fmt.print("Hello 'printf' style $s!", w)

// more complicated interpolated string literal
var h = "Hello"
System.print("%(Fmt.s(-8, h)) more complicated interpolated %(w.map { |c| "%(c + "\%")" }.join())!")

// more complicated 'printf' style
Fmt.print("$-8s more complicated 'printf' style $s\%!", h, w.join("\%"))

// raw string literal
var r = """
Hello, raw string literal which interpets a control code such as "\n" and an
interpolation such as %(h) as verbatim text.
Single (") or dual ("") double-quotes can be included without problem.
"""
System.print(r)


MyString:
     byte "Hello World",0              ;a null-terminated string
LookupTable:
     byte &03,&06,&09,&0C              ;a pre-defined sequence of bytes (similar in concept to enum in C)
TileGfx:
     incbin "Z:\game\gfx\tilemap.bmp"  ;a file containing bitmap graphics data


F _transpose(matrix)
   assert(matrix.len == matrix[0].len)
   V r = [[0] * matrix.len] * matrix.len
   L(i) 0 .< matrix.len
      L(j) 0 .< matrix.len
         r[i][j] = matrix[j][i]
   R r

F _shuffle_transpose_shuffle(matrix)
   V square = copy(matrix)
   random:shuffle(&square)
   V trans = _transpose(square)
   random:shuffle(&trans)
   R trans

F _rls(&symbols)
   V n = symbols.len
   I n == 1
      R [symbols]
   E
      V sym = random:choice(symbols)
      symbols.remove(sym)
      V square = _rls(&symbols)
      square.append(copy(square[0]))
      L(i) 0 .< n
         square[i].insert(i, sym)
      R square

F rls(n)
   V symbols = Array(0 .< n)
   V square = _rls(&symbols)
   R _shuffle_transpose_shuffle(square)

F _check_rows(square)
   V set_row0 = Set(square[0])
   R all(square.map(row -> row.len == Set(row).len & Set(row) == @set_row0))

F _check(square)
   V transpose = _transpose(square)
   assert(_check_rows(square) & _check_rows(transpose), ‘Not a Latin square’)

L(i) [3, 3, 5, 5]
   V square = rls(i)
   print(square.map(row -> row.join(‘ ’)).join("\n"))
   _check(square)
   print()


DEFINE PTR="CARD"
DEFINE DIMENSION="5"

TYPE Matrix=[
  PTR data ;BYTE ARRAY
  BYTE dim]

PTR FUNC GetPtr(Matrix POINTER mat BYTE x,y)
RETURN (mat.data+x+y*mat.dim)

PROC PrintMatrix(Matrix POINTER mat)
  BYTE x,y
  BYTE POINTER d

  d=GetPtr(mat,0,0)
  FOR y=0 TO mat.dim-1
  DO
    FOR x=0 TO mat.dim-1
    DO
      PrintB(d^) Put(32)
      d==+1
    OD
    PutE()
  OD
RETURN

PROC KnuthShuffle(BYTE ARRAY tab BYTE size)
  BYTE i,j,tmp

  i=size-1
  WHILE i>0
  DO
    j=Rand(i+1)
    tmp=tab(i)
    tab(i)=tab(j)
    tab(j)=tmp
    i==-1
  OD
RETURN

PROC LatinSquare(Matrix POINTER mat)
  BYTE x,y,yy,shuffled
  BYTE POINTER ptr1,ptr2
  BYTE ARRAY used(DIMENSION)

  ptr1=GetPtr(mat,0,0)
  FOR y=0 TO mat.dim-1
  DO
    FOR x=0 TO mat.dim-1
    DO
      ptr1^=x
      ptr1==+1
    OD
  OD

  ;first row
  ptr1=GetPtr(mat,0,0)
  KnuthShuffle(ptr1,mat.dim)

  ;middle rows
  FOR y=1 TO mat.dim-2
  DO
    shuffled=0
    WHILE shuffled=0
    DO
      ptr1=GetPtr(mat,0,y)
      KnuthShuffle(ptr1,mat.dim)

      shuffled=1
      yy=0
      WHILE shuffled=1 AND yy<y
      DO
        x=0
        WHILE shuffled=1 AND x<mat.dim
        DO
          ptr1=GetPtr(mat,x,yy)
          ptr2=GetPtr(mat,x,y)
          IF ptr1^=ptr2^ THEN
            shuffled=0
          FI
          x==+1
        OD
        yy==+1
      OD
    OD
  OD

  ;last row
  FOR x=0 TO mat.dim-1
  DO
    Zero(used,mat.dim)

    FOR y=0 TO mat.dim-2
    DO
      ptr1=GetPtr(mat,x,y)
      yy=ptr1^ used(yy)=1
    OD

    FOR y=0 TO mat.dim-1
    DO
      IF used(y)=0 THEN
        ptr1=GetPtr(mat,x,mat.dim-1)
        ptr1^=y
        EXIT
      FI
    OD
  OD
RETURN

PROC Main()
  BYTE ARRAY d(25)
  BYTE i
  Matrix mat

  mat.data=d
  mat.dim=DIMENSION

  FOR i=1 TO 2
  DO
    LatinSquare(mat)
    PrintMatrix(mat)
    PutE()
  OD
RETURN


latinSquare: function [n][
    square: new []
    variants: shuffle permutate 0..n-1
    while -> n > size square [
        row: sample variants
        'square ++ @[row]
        filter 'variants 'variant [
            reject: false
            loop.with:'i variant 'col [
                if col = row\[i] ->
                    reject: true
            ]
            reject
        ]
    ]
    return square
]

loop 2 'x [
    ls: latinSquare 5
    loop ls 'row ->
        print row
    print "---------"
]


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

// low <= num < high
int randInt(int low, int high) {
    return (rand() % (high - low)) + low;
}

// shuffle an array of n elements
void shuffle(int *const array, const int n) {
    if (n > 1) {
        int i;
        for (i = 0; i < n - 1; i++) {
            int j = randInt(i, n);

            int t = array[i];
            array[i] = array[j];
            array[j] = t;
        }
    }
}

// print an n * n array
void printSquare(const int *const latin, const int n) {
    int i, j;
    for (i = 0; i < n; i++) {
        printf("[");
        for (j = 0; j < n; j++) {
            if (j > 0) {
                printf(", ");
            }
            printf("%d", latin[i * n + j]);
        }
        printf("]\n");
    }
    printf("\n");
}

void latinSquare(const int n) {
    int *latin, *used;
    int i, j, k;

    if (n <= 0) {
        printf("[]\n");
        return;
    }

    // allocate
    latin = (int *)malloc(n * n * sizeof(int));
    if (!latin) {
        printf("Failed to allocate memory.");
        return;
    }

    // initialize
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            latin[i * n + j] = j;
        }
    }

    // first row
    shuffle(latin, n);

    // middle row(s)
    for (i = 1; i < n - 1; i++) {
        bool shuffled = false;

        while (!shuffled) {
            shuffle(&latin[i * n], n);

            for (k = 0; k < i; k++) {
                for (j = 0; j < n; j++) {
                    if (latin[k * n + j] == latin[i * n + j]) {
                        goto shuffling;
                    }
                }
            }
            shuffled = true;

        shuffling: {}
        }
    }

    //last row
    used = (int *)malloc(n * sizeof(int));
    for (j = 0; j < n; j++) {
        memset(used, 0, n * sizeof(int));
        for (i = 0; i < n - 1; i++) {
            used[latin[i * n + j]] = 1;
        }
        for (k = 0; k < n; k++) {
            if (used[k] == 0) {
                latin[(n - 1) * n + j] = k;
                break;
            }
        }
    }
    free(used);

    // print the result
    printSquare(latin, n);
    free(latin);
}

int main() {
    // initialze the random number generator
    srand((unsigned int)time((time_t)0));

    latinSquare(5);
    latinSquare(5);
    latinSquare(10);

    return 0;
}


#include <algorithm>
#include <chrono>
#include <iostream>
#include <random>
#include <vector>

template <typename T>
std::ostream &operator<<(std::ostream &os, const std::vector<T> &v) {
    auto it = v.cbegin();
    auto end = v.cend();

    os << '[';
    if (it != end) {
        os << *it;
        it = std::next(it);
    }
    while (it != end) {
        os << ", ";
        os << *it;
        it = std::next(it);
    }
    return os << ']';
}

void printSquare(const std::vector<std::vector<int>> &latin) {
    for (auto &row : latin) {
        std::cout << row << '\n';
    }
    std::cout << '\n';
}

void latinSquare(int n) {
    if (n <= 0) {
        std::cout << "[]\n";
        return;
    }

    // obtain a time-based seed:
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    auto g = std::default_random_engine(seed);

    std::vector<std::vector<int>> latin;
    for (int i = 0; i < n; ++i) {
        std::vector<int> inner;
        for (int j = 0; j < n; ++j) {
            inner.push_back(j);
        }
        latin.push_back(inner);
    }
    // first row
    std::shuffle(latin[0].begin(), latin[0].end(), g);

    // middle row(s)
    for (int i = 1; i < n - 1; ++i) {
        bool shuffled = false;

        while (!shuffled) {
            std::shuffle(latin[i].begin(), latin[i].end(), g);
            for (int k = 0; k < i; ++k) {
                for (int j = 0; j < n; ++j) {
                    if (latin[k][j] == latin[i][j]) {
                        goto shuffling;
                    }
                }
            }
            shuffled = true;

        shuffling: {}
        }
    }

    // last row
    for (int j = 0; j < n; ++j) {
        std::vector<bool> used(n, false);
        for (int i = 0; i < n - 1; ++i) {
            used[latin[i][j]] = true;
        }
        for (int k = 0; k < n; ++k) {
            if (!used[k]) {
                latin[n - 1][j] = k;
                break;
            }
        }
    }

    printSquare(latin);
}

int main() {
    latinSquare(5);
    latinSquare(5);
    latinSquare(10);
    return 0;
}


using System;
using System.Collections.Generic;

namespace RandomLatinSquares {
    using Matrix = List<List<int>>;

    // Taken from https://stackoverflow.com/a/1262619
    static class Helper {
        private static readonly Random rng = new Random();

        public static void Shuffle<T>(this IList<T> list) {
            int n = list.Count;
            while (n > 1) {
                n--;
                int k = rng.Next(n + 1);
                T value = list[k];
                list[k] = list[n];
                list[n] = value;
            }
        }
    }

    class Program {
        static void PrintSquare(Matrix latin) {
            foreach (var row in latin) {
                Console.Write('[');

                var it = row.GetEnumerator();
                if (it.MoveNext()) {
                    Console.Write(it.Current);
                }
                while (it.MoveNext()) {
                    Console.Write(", ");
                    Console.Write(it.Current);
                }

                Console.WriteLine(']');
            }
            Console.WriteLine();
        }

        static void LatinSquare(int n) {
            if (n <= 0) {
                Console.WriteLine("[]");
                return;
            }

            var latin = new Matrix();
            for (int i = 0; i < n; i++) {
                List<int> temp = new List<int>();
                for (int j = 0; j < n; j++) {
                    temp.Add(j);
                }
                latin.Add(temp);
            }
            // first row
            latin[0].Shuffle();

            // middle row(s)
            for (int i = 1; i < n - 1; i++) {
                bool shuffled = false;

                while (!shuffled) {
                    latin[i].Shuffle();
                    for (int k = 0; k < i; k++) {
                        for (int j = 0; j < n; j++) {
                            if (latin[k][j] == latin[i][j]) {
                                goto shuffling;
                            }
                        }
                    }
                    shuffled = true;

                shuffling: { }
                }
            }

            // last row
            for (int j = 0; j < n; j++) {
                List<bool> used = new List<bool>();
                for (int i = 0; i < n; i++) {
                    used.Add(false);
                }

                for (int i = 0; i < n-1; i++) {
                    used[latin[i][j]] = true;
                }
                for (int k = 0; k < n; k++) {
                    if (!used[k]) {
                        latin[n - 1][j] = k;
                        break;
                    }
                }
            }

            PrintSquare(latin);
        }

        static void Main() {
            LatinSquare(5);
            LatinSquare(5);
            LatinSquare(10); // for good measure
        }
    }
}


import std.array;
import std.random;
import std.stdio;

alias Matrix = int[][];

void latinSquare(int n) {
    if (n <= 0) {
        writeln("[]");
        return;
    }

    Matrix latin = uninitializedArray!Matrix(n, n);
    foreach (row; latin) {
        for (int i = 0; i < n; i++) {
            row[i] = i;
        }
    }
    // first row
    latin[0].randomShuffle;

    // middle row(s)
    for (int i = 1; i < n - 1; i++) {
        bool shuffled = false;

        shuffling:
        while (!shuffled) {
            latin[i].randomShuffle;
            for (int k = 0; k < i; k++) {
                for (int j = 0; j < n; j++) {
                    if (latin[k][j] == latin[i][j]) {
                        continue shuffling;
                    }
                }
            }
            shuffled = true;
        }
    }

    // last row
    for (int j = 0; j < n; j++) {
        bool[] used = uninitializedArray!(bool[])(n);
        used[] = false;

        for (int i = 0; i < n - 1; i++) {
            used[latin[i][j]] = true;
        }
        for (int k = 0; k < n; k++) {
            if (!used[k]) {
                latin[n - 1][j] = k;
                break;
            }
        }
    }

    printSquare(latin);
}

void printSquare(Matrix latin) {
    foreach (row; latin) {
        writeln(row);
    }
}

void main() {
    latinSquare(5);
    writeln;

    latinSquare(5);
    writeln;

    latinSquare(10);
}


// Generate 2 Random Latin Squares of order 5. Nigel Galloway: July 136th., 2019
let N=let N=System.Random() in (fun n->N.Next(n))
let rc()=let β=lN2p [|0;N 4;N 3;N 2|] [|0..4|] in Seq.item (N 56) (normLS 5) |> List.map(lN2p [|N 5;N 4;N 3;N 2|]) |> List.permute(fun n->β.[n]) |> List.iter(printfn "%A")
rc(); printfn ""; rc()


USING: arrays combinators.extras fry io kernel math.matrices
prettyprint random sequences sets ;
IN: rosetta-code.random-latin-squares

: rand-permutation ( n -- seq ) <iota> >array randomize ;
: ls? ( n -- ? ) [ all-unique? ] column-map t [ and ] reduce ;
: (ls) ( n -- m ) dup '[ _ rand-permutation ] replicate ;
: ls ( n -- m ) dup (ls) dup ls? [ nip ] [ drop ls ] if ;
: random-latin-squares ( -- ) [ 5 ls simple-table. nl ] twice ;

MAIN: random-latin-squares


package main

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

type matrix [][]int

func shuffle(row []int, n int) {
    rand.Shuffle(n, func(i, j int) {
        row[i], row[j] = row[j], row[i]
    })
}

func latinSquare(n int) {
    if n <= 0 {
        fmt.Println("[]\n")
        return
    }
    latin := make(matrix, n)
    for i := 0; i < n; i++ {
        latin[i] = make([]int, n)
        if i == n-1 {
            break
        }
        for j := 0; j < n; j++ {
            latin[i][j] = j
        }
    }
    // first row
    shuffle(latin[0], n)

    // middle row(s)
    for i := 1; i < n-1; i++ {
        shuffled := false
    shuffling:
        for !shuffled {
            shuffle(latin[i], n)
            for k := 0; k < i; k++ {
                for j := 0; j < n; j++ {
                    if latin[k][j] == latin[i][j] {
                        continue shuffling
                    }
                }
            }
            shuffled = true
        }
    }

    // last row
    for j := 0; j < n; j++ {
        used := make([]bool, n)
        for i := 0; i < n-1; i++ {
            used[latin[i][j]] = true
        }
        for k := 0; k < n; k++ {
            if !used[k] {
                latin[n-1][j] = k
                break
            }
        }
    }
    printSquare(latin, n)
}

func printSquare(latin matrix, n int) {
    for i := 0; i < n; i++ {
        fmt.Println(latin[i])
    }
    fmt.Println()
}

func main() {
    rand.Seed(time.Now().UnixNano())
    latinSquare(5)
    latinSquare(5)
    latinSquare(10) // for good measure
}


import Data.List (permutations, (\\))

latinSquare :: Eq a => [a] -> [a] -> [[a]]
latinSquare [] [] = []
latinSquare c r
  | head r /= head c = []
  | otherwise = reverse <$> foldl addRow firstRow perms
  where
    -- permutations grouped by the first element
    perms =
      tail $
        fmap
          (fmap . (:) <*> (permutations . (r \\) . return))
          c
    firstRow = pure <$> r
    addRow tbl rows =
      head
        [ zipWith (:) row tbl
          | row <- rows,
            and $ different (tail row) (tail tbl)
        ]
    different = zipWith $ (not .) . elem

printTable :: Show a => [[a]] -> IO ()
printTable tbl =
  putStrLn $
    unlines $
      unwords . map show <$> tbl


rls=: 3 : 0
  s=. ?~ y             NB. "deal" y unique integers from 0 to y
  for_ijk. i.<:y do.
    NB. deal a new row. subtract it from all previous rows
    NB. if you get a 0, some column has a matching integer, deal again
    whilst. 0 = */ */ s -"1 r do.
      r=. ?~ y
    end.
    s=. s ,,: r        NB. "laminate" successful row to the square
  end.
)


import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class RandomLatinSquares {
    private static void printSquare(List<List<Integer>> latin) {
        for (List<Integer> row : latin) {
            Iterator<Integer> it = row.iterator();

            System.out.print("[");
            if (it.hasNext()) {
                Integer col = it.next();
                System.out.print(col);
            }
            while (it.hasNext()) {
                Integer col = it.next();
                System.out.print(", ");
                System.out.print(col);
            }
            System.out.println("]");
        }
        System.out.println();
    }

    private static void latinSquare(int n) {
        if (n <= 0) {
            System.out.println("[]");
            return;
        }

        List<List<Integer>> latin = new ArrayList<>(n);
        for (int i = 0; i < n; ++i) {
            List<Integer> inner = new ArrayList<>(n);
            for (int j = 0; j < n; ++j) {
                inner.add(j);
            }
            latin.add(inner);
        }
        // first row
        Collections.shuffle(latin.get(0));

        // middle row(s)
        for (int i = 1; i < n - 1; ++i) {
            boolean shuffled = false;
            shuffling:
            while (!shuffled) {
                Collections.shuffle(latin.get(i));
                for (int k = 0; k < i; ++k) {
                    for (int j = 0; j < n; ++j) {
                        if (Objects.equals(latin.get(k).get(j), latin.get(i).get(j))) {
                            continue shuffling;
                        }
                    }
                }
                shuffled = true;
            }
        }

        // last row
        for (int j = 0; j < n; ++j) {
            List<Boolean> used = new ArrayList<>(n);
            for (int i = 0; i < n; ++i) {
                used.add(false);
            }
            for (int i = 0; i < n - 1; ++i) {
                used.set(latin.get(i).get(j), true);
            }
            for (int k = 0; k < n; ++k) {
                if (!used.get(k)) {
                    latin.get(n - 1).set(j, k);
                    break;
                }
            }
        }

        printSquare(latin);
    }

    public static void main(String[] args) {
        latinSquare(5);
        latinSquare(5);
        latinSquare(10);
    }
}


class Latin {
  constructor(size = 3) {
    this.size = size;
    this.mst = [...Array(this.size)].map((v, i) => i + 1);
    this.square = Array(this.size).fill(0).map(() => Array(this.size).fill(0));

    if (this.create(0, 0)) {
      console.table(this.square);
    }
  }

  create(c, r) {
    const d = [...this.mst];
    let s;
    while (true) {
      do {
        s = d.splice(Math.floor(Math.random() * d.length), 1)[0];
        if (!s) return false;
      } while (this.check(s, c, r));

      this.square[c][r] = s;
      if (++c >= this.size) {
        c = 0;
        if (++r >= this.size) {
          return true;
        }
      }
      if (this.create(c, r)) return true;
      if (--c < 0) {
        c = this.size - 1;
        if (--r < 0) {
          return false;
        }
      }
    }
  }

  check(d, c, r) {
    for (let a = 0; a < this.size; a++) {
      if (c - a > -1) {
        if (this.square[c - a][r] === d)
          return true;
      }
      if (r - a > -1) {
        if (this.square[c][r - a] === d)
          return true;
      }
    }
    return false;
  }
}
new Latin(5);


using Random

shufflerows(mat) = mat[shuffle(1:end), :]
shufflecols(mat) = mat[:, shuffle(1:end)]

function addatdiagonal(mat)
    n = size(mat)[1] + 1
    newmat = similar(mat, size(mat) .+ 1)
    for j in 1:n, i in 1:n
        newmat[i, j] = (i == n && j < n) ? mat[1, j] : (i == j) ? n - 1 :
            (i < j) ? mat[i, j - 1] : mat[i, j]
    end
    newmat
end

function makelatinsquare(N)
    mat = [0 1; 1 0]
    for i in 3:N
        mat = addatdiagonal(mat)
    end
    shufflecols(shufflerows(mat))
end

function printlatinsquare(N)
    mat = makelatinsquare(N)
    for i in 1:N, j in 1:N
        print(rpad(mat[i, j], 3), j == N ? "\n" : "")
    end
end

printlatinsquare(5), println("\n"), printlatinsquare(5)


typealias matrix = MutableList<MutableList<Int>>

fun printSquare(latin: matrix) {
    for (row in latin) {
        println(row)
    }
    println()
}

fun latinSquare(n: Int) {
    if (n <= 0) {
        println("[]")
        return
    }

    val latin = MutableList(n) { MutableList(n) { it } }
    // first row
    latin[0].shuffle()

    // middle row(s)
    for (i in 1 until n - 1) {
        var shuffled = false
        shuffling@
        while (!shuffled) {
            latin[i].shuffle()
            for (k in 0 until i) {
                for (j in 0 until n) {
                    if (latin[k][j] == latin[i][j]) {
                        continue@shuffling
                    }
                }
            }
            shuffled = true
        }
    }

    // last row
    for (j in 0 until n) {
        val used = MutableList(n) { false }
        for (i in 0 until n - 1) {
            used[latin[i][j]] = true
        }
        for (k in 0 until n) {
            if (!used[k]) {
                latin[n - 1][j] = k
                break
            }
        }
    }

    printSquare(latin)
}

fun main() {
    latinSquare(5)
    latinSquare(5)
    latinSquare(10) // for good measure
}


Module FastLatinSquare {
	n=5
	For k=1 To 2
		latin()
	Next
	n=40
	latin()
	Sub latin()
		Local i,a, a(1 To n), b, k
		Profiler
		flush
		Print "latin square ";n;" by ";n
		For i=1 To n
			Push i
		Next i
		For i=1 To n div 2
			Shiftback random(2, n)
		Next i
		a=[]
		Push ! stack(a)
		a=array(a)  ' change a from stack to array
		For i=1 To n*10
			Shiftback random(2, n)
		Next i
		For i=0 To n-1
			Data number  ' rotate by one the stack items
			b=[]    ' move stack To b, leave empty stack
			a(a#val(i))=b
			Push ! stack(b)  ' Push from a copy of b all items To stack
		Next i
		flush
		For k=1 To  n div 2
			z=random(2, n)
			For i=1 To n
				a=a(i)
				stack a {
					shift z
				}
			Next
		Next
		For i=1 To n
			a=a(i)
			a(i)=array(a)  ' change To array from stack
		Next i
		For i=1 To n
			Print a(i)
		Next i
		Print TimeCount
	End Sub
}
FastLatinSquare


Clear[RandomLatinSquare]
RandomLatinSquare[n_] := Module[{out, ord},
  out = Table[RotateLeft[Range[n], i], {i, n}];
  out = RandomSample[out];
  ord = RandomSample[Range[n]];
  out = out[[All, ord]];
  out
  ]
RandomLatinSquare[5] // Grid


import random, sequtils, strutils

type LatinSquare = seq[seq[char]]

proc get[T](s: set[T]): T =
  ## Return the first element of a set.
  for n in s:
    return n

proc letterAt(n: Natural): char {.inline.} = chr(ord('A') - 1 + n)

proc latinSquare(n: Positive): LatinSquare =
  result = newSeqWith(n, toSeq(letterAt(1)..letterAt(n)))
  result[0].shuffle()

  for row in 1..(n - 2):
    var ok = false
    while not ok:
      block shuffling:
        result[row].shuffle()
        for prev in 0..<row:
          for col in 0..<n:
            if result[row][col] == result[prev][col]:
              break shuffling
        ok = true

  for col in 0..<n:
    var s = {letterAt(1)..letterAt(n)}
    for row in 0..(n - 2):
      s.excl result[row][col]
    result[^1][col] = s.get()

proc `$`(s: LatinSquare): string =
  let n = s.len
  for row in 0..<n:
    result.add s[row].join(" ") & '\n'

randomize()
echo latinSquare(5)
echo latinSquare(5)
echo latinSquare(10)


use strict;
use warnings;
use feature 'say';
use List::Util 'shuffle';

sub random_ls {
    my($n) = @_;
    my(@cols,@symbols,@ls_sym);

    # build n-sized latin square
    my @ls = [0,];
    for my $i (1..$n-1) {
        @{$ls[$i]} = @{$ls[0]};
        splice(@{$ls[$_]}, $_, 0, $i) for 0..$i;
    }

    # shuffle rows and columns
    @cols = shuffle 0..$n-1;
    @ls = map [ @{$_}[@cols] ], @ls[shuffle 0..$n-1];

    # replace numbers with symbols
    @symbols = shuffle( ('A'..'Z')[0..$n-1] );
    push @ls_sym, [@symbols[@$_]] for @ls;
    @ls_sym
}

sub display {
    my $str;
    $str .= join(' ', @$_) . "\n" for @_;
    $str
}

say display random_ls($_) for 2..5, 5;


with javascript_semantics
string aleph = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

function ls(integer n)
    if n>length(aleph) then ?9/0 end if -- too big...
    atom t1 = time()+1
    sequence tn = tagset(n),     -- {1..n}
             vcs = repeat(tn,n), -- valid for cols
             res = {}
    integer clashes = 0
    while length(res)<n do
        sequence rn = {},               -- next row
                 vr = tagset(n),        -- valid for row (ie all)
                 vc = deep_copy(vcs)    -- copy (in case of clash)
        bool clash = false
        for c=1 to n do
            sequence v = {}
            for k=1 to n do
                -- collect all still valid options
                if vr[k] and vc[c][k] then v &= k end if
            end for
            if v={} then
                clash = true
                exit
            end if
            integer z = v[rand(length(v))]
            rn &= z
            vr[z] = 0           -- no longer valid
            vc[c][z] = 0        --      ""
        end for
        if not clash then
            res = append(res,rn)
            vcs = vc
        else
            clashes += 1
            if time()>t1 then
                printf(1,"rows completed:%d/%d, clashes:%d\n",
                         {length(res),n,clashes})
                t1 = time()+1
            end if
        end if
    end while
    for i=1 to n do
        string line = ""
        for j=1 to n do
            line &= aleph[res[i][j]]
        end for
        res[i] = line
    end for
    return res
end function

procedure latin_square(integer n)
    atom t0 = time()
    string res = join(ls(n),"\n"),
           e = elapsed(time()-t0)
    printf(1,"Latin square of order %d (%s):\n%s\n",{n,e,res})
end procedure
latin_square(3)
latin_square(5)
latin_square(5)
latin_square(10)
if platform()!=JS then
    latin_square(42)
end if


main =>
  _ = random2(), % random seed
  N = 5,
  foreach(_ in 1..2)
    latin_square(N, X),
    pretty_print(X)
  end,
  % A larger random instance
  latin_square(62,X),
  pretty_print(X).

% Latin square
latin_square(N, X) =>
  X = new_array(N,N),
  X :: 1..N,
  foreach(I in 1..N)
    all_different([X[I,J] : J in 1..N]),
    all_different([X[J,I] : J in 1..N])
  end,
  % rand_val for randomness
  solve($[ff,rand_val],X).

pretty_print(X) =>
  N = X.len,
  Alpha = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
  foreach(I in 1..N)
    foreach(J in 1..N)
      if N > 20 then
        printf("%w",Alpha[X[I,J]])
      else
        printf("%2w ",X[I,J])
      end
    end,
    nl
  end,
  nl.


from random import choice, shuffle
from copy import deepcopy

def rls(n):
    if n <= 0:
        return []
    else:
        symbols = list(range(n))
        square = _rls(symbols)
        return _shuffle_transpose_shuffle(square)

def _shuffle_transpose_shuffle(matrix):
    square = deepcopy(matrix)
    shuffle(square)
    trans = list(zip(*square))
    shuffle(trans)
    return trans

def _rls(symbols):
    n = len(symbols)
    if n == 1:
        return [symbols]
    else:
        sym = choice(symbols)
        symbols.remove(sym)
        square = _rls(symbols)
        square.append(square[0].copy())
        for i in range(n):
            square[i].insert(i, sym)
        return square

def _to_text(square):
    if square:
        width = max(len(str(sym)) for row in square for sym in row)
        txt = '\n'.join(' '.join(f"{sym:>{width}}" for sym in row)
                        for row in square)
    else:
        txt = ''
    return txt

def _check(square):
    transpose = list(zip(*square))
    assert _check_rows(square) and _check_rows(transpose), \
        "Not a Latin square"

def _check_rows(square):
    if not square:
        return True
    set_row0 = set(square[0])
    return all(len(row) == len(set(row)) and set(row) == set_row0
               for row in square)

if __name__ == '__main__':
    for i in [3, 3,  5, 5, 12]:
        square = rls(i)
        print(_to_text(square))
        _check(square)
        print()


sub latin-square { [[0],] };

sub random ( @ls, :$size = 5 ) {

    # Build
    for 1 ..^ $size -> $i {
        @ls[$i] = @ls[0].clone;
        @ls[$_].splice($_, 0, $i) for 0 .. $i;
    }

    # Shuffle
    @ls = @ls[^$size .pick(*)];
    my @cols = ^$size .pick(*);
    @ls[$_] = @ls[$_][@cols] for ^@ls;

    # Some random Latin glyphs
    my @symbols = ('A' .. 'Z').pick($size);

    @ls.deepmap: { $_ = @symbols[$_] };

}

sub display ( @array ) { $_.fmt("%2s ").put for |@array, '' }

# The Task

# Default size 5
display random latin-square;

# Specified size
display random :size($_), latin-square for 5, 3, 9;

# Or, if you'd prefer:
display random latin-square, :size($_) for 12, 2, 1;


/*REXX program generates and displays a randomized Latin square.                        */
parse arg N seed .                               /*obtain the optional argument from CL.*/
if N=='' | N==","  then N= 5                     /*Not specified?  Then use the default.*/
if datatype(seed, 'W')  then call random ,,seed  /*Seed numeric?   Then use it for seed.*/
w= length(N - 1)                                 /*get the length of the largest number.*/
$=                                               /*initialize  $  string to null.       */
         do i=0  for N;    $= $ right(i, w, '_') /*build a string of numbers (from zero)*/
         end   /*i*/                             /* [↑]  $ string is (so far)  in order.*/
z=                                               /*Z:  will be the 1st row of the square*/
         do N;             ?= random(1,words($)) /*gen a random number from the $ string*/
         z= z word($, ?);  $= delword($, ?, 1)   /*add the number to string; del from $.*/
         end   /*r*/
zz= z||z                                         /*build a double-length string of  Z.  */
         do j=1  for N                           /* [↓]  display rows of random Latin sq*/
         say translate(subword(zz, j, N), , '_') /*translate leading underbar to blank. */
         end   /*j*/                             /*stick a fork in it,  we're all done. */


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

###====================================================================================

size      = 10

time1     = 0
bwidth    = 0
bheight   = 0

a2DSquare = newlist(size,size)
a2DFinal  = newlist(size,size)

aList  = 1:size
aList2 = RandomList(aList)

GenerateRows(aList2)
ShuffleCols(a2DSquare, a2DFinal)

C_SPACING           = 1
Button              = newlist(size,size)
LayoutButtonRow     = list(size)
C_ButtonOrangeStyle = 'border-radius:1x;color:black; background-color: orange'

###====================================================================================

MyApp = New qApp {

	StyleFusion()

	win = new qWidget() {

		workHeight = win.height()
		fontSize = 8 + (300/size)

	    wwidth = win.width()
	    wheight = win.height()
	    bwidth = wwidth/size
	    bheight = wheight/size

		setwindowtitle("Random Latin Squares")
		move(555,0)
		setfixedsize(1000,1000)

		myfilter = new qallevents(win)
		myfilter.setResizeEvent("resizeBoard()")
		installeventfilter(myfilter)

		LayoutButtonMain = new QVBoxLayout() {
			setSpacing(C_SPACING)
			setContentsmargins(50,50,50,50)
		}

		LayoutButtonStart = new QHBoxLayout() {
			setSpacing(C_SPACING)
			setContentsmargins(0,0,0,0)
		}

		btnStart = new qPushButton(win) {
			setFont(new qFont("Calibri",fontsize,2100,0))
			resize(bwidth,bheight)
			settext(" Start ")
			setstylesheet(C_ButtonOrangeStyle)
			setclickevent("gameSolution()")
		}

		sizeBtn = new qlabel(win)
		{
			setFont(new qFont("Calibri",fontsize,2100,0))
			resize(bwidth,bheight)
			setStyleSheet("background-color:rgb(255,255,204)")
			setText(" Size: ")
		}

		lineSize = new qLineEdit(win)
		{
			setFont(new qFont("Calibri",fontsize,2100,0))
			resize(bwidth,bheight)
			setStyleSheet("background-color:rgb(255,255,204)")
			setAlignment( Qt_AlignHCenter)
			setAlignment( Qt_AlignVCenter)
			setreturnPressedEvent("newBoardSize()")
			setText(string(size))
		}

		btnExit = new qPushButton(win) {
			setFont(new qFont("Calibri",fontsize,2100,0))
			resize(bwidth,bheight)
			settext(" Exit ")
			setstylesheet(C_ButtonOrangeStyle)
			setclickevent("pExit()")
		}

		LayoutButtonStart.AddWidget(btnStart)
		LayoutButtonStart.AddWidget(sizeBtn)
		LayoutButtonStart.AddWidget(lineSize)
		LayoutButtonStart.AddWidget(btnExit)

		LayoutButtonMain.AddLayout(LayoutButtonStart)

		for Row = 1 to size

			LayoutButtonRow[Row] = new QHBoxLayout() {
				setSpacing(C_SPACING)
				setContentsmargins(0,0,0,0)
			}

			for Col = 1 to size
				Button[Row][Col] = new qlabel(win) {
					setFont(new qFont("Calibri",fontsize,2100,0))
					resize(bwidth,bheight)
				}
				LayoutButtonRow[Row].AddWidget(Button[Row][Col])
			next
			LayoutButtonMain.AddLayout(LayoutButtonRow[Row])

		next

		setLayout(LayoutButtonMain)

		 show()

	}

	exec()
}

###====================================================================================

func newBoardSize()

	nrSize = number(lineSize.text())

	if nrSize = 1
		? "Enter: Size > 1"
		return
	ok

	for Row = 1 to size
		for Col = 1 to size
			Button[Row][Col].settext("")
		next
	next

	newWindow(nrSize)

###====================================================================================

func newWindow(newSize)

	time1 = clock()

	for Row = 1 to size
		for Col = 1 to size
			Button[Row][Col].delete()
		next
	next

	size = newSize

	bwidth  = ceil((win.width() - 8) / size)
	bheight = ceil((win.height() - 32) / size)

	fontSize = 8 + (300/size)

	if size > 16
		fontSize = 8 + (150/size)
	ok

	if size < 8
		fontSize = 30 + (150/size)
	ok

	if size = 2
		fontSize = 10 + (100/size)
	ok

	btnStart.setFont(new qFont("Calibri",fontsize,2100,0))
	sizeBtn.setFont(new qFont("Calibri",fontsize,2100,0))
	lineSize.setFont(new qFont("Calibri",fontsize,2100,0))
	btnExit.setFont(new qFont("Calibri",fontsize,2100,0))

	LayoutButtonStart = new QHBoxLayout() {
		setSpacing(C_SPACING)
		setContentsmargins(0,0,0,0)
	}

	Button = newlist(size,size)
	LayoutButtonRow = list(size)

	for Row = 1 to size

		LayoutButtonRow[Row] = new QHBoxLayout() {
			setSpacing(C_SPACING)
			setContentsmargins(0,0,0,0)
		}

		for Col = 1 to size

			Button[Row][Col] = new qlabel(win) {
				setFont(new qFont("Calibri",fontsize,2100,0))
				resize(bwidth,bheight)
			}
			LayoutButtonRow[Row].AddWidget(Button[Row][Col])

		next

		LayoutButtonMain.AddLayout(LayoutButtonRow[Row])

	next

	win.setLayout(LayoutButtonMain)

	return

###====================================================================================

func resizeBoard

	bwidth  = ceil((win.width() - 8) / size)
	bheight = ceil((win.height() - 32) / size)

	for Row = 1 to size
		for Col = 1 to size
			Button[Row][Col].resize(bwidth,bheight)
		next
	next

###====================================================================================

Func pExit

	MyApp.quit()

###====================================================================================

func gameSolution()

	a2DSquare = newlist(size,size)
	a2DFinal  = newlist(size,size)

	aList  = 1:size
	aList2 = RandomList(aList)

	GenerateRows(aList2)
	ShuffleCols(a2DSquare, a2DFinal)

	for nRow = 1 to size
		for nCol = 1 to size
			Button[nRow][nCol].settext("-")
		next
	next

	for nRow = 1 to size
		for nCol = 1 to size
			Button[nRow][nCol].resize(bwidth,bheight)
			Button[nRow][nCol].settext(string(a2DSquare[nRow][nCol]))
		next
	next

	time2 = clock()
	time3 = (time2 - time1)/1000
	? "Elapsed time: " + time3 + " ms at size = " + size + nl

###====================================================================================

// Scramble the numbers in the List
// Uniq random picks, then shorten list by each pick

Func RandomList(aInput)

    aOutput = []

    while len(aInput) > 1
        nIndex = random(len(aInput)-1)
        nIndex++

        aOutput + aInput[nIndex]
        del(aInput,nIndex)
    end

    aOutput + aInput[1]

return aOutput

###====================================================================================
// Generate Rows of data. Put them in the 2DArray

Func GenerateRows(aInput)

	aOutput = []
	size  = len(aInput)
    shift = 1

	for k = 1 to size									// Make 8 Rows of lists
		aOutput = []

		for i = 1 to size           					// make a list
			   pick = i + shift     					// shift every Row by +1 more
			if pick > size   pick = pick - size  ok

			aOutput + aInput[pick]
		next

		a2DSquare[k] = aOutput							// Row of Output to a2DSquare

		shift++                    						// shift next line by +1 more
		if shift > size  shift = 1 ok
	next

	return

###====================================================================================
// Shift random Rows into a2DFinal, then random Cols

Func ShuffleCols(a2DSquare, a2DFinal)

	aSuffle  = 1:size
    aSuffle2 = RandomList(aSuffle)	// Pick random Col to insert in a2DFinal

	for i = 1 to size           	// Row
		pick = aSuffle2[i]

        for j = 1 to size			// Col
			a2DFinal[i][j] =  a2DSquare[pick][j]  // i-Row-Col j-Horz-Vert
		next
	next

	a2DSquare = a2DFinal			// Now do the verticals
	aSuffle  = 1:size
	aSuffle2 = RandomList(aSuffle)

	for i = 1 to size           	// Row
		pick = aSuffle2[i]

        for j = 1 to size			// Col
			a2DFinal[j][i] =  a2DSquare[j][pick]  //Reverse i-j , i-Row-Col j-Horz-Vert
		next
	next

	return

###====================================================================================


N = 5

def generate_square
  perms  =  (1..N).to_a.permutation(N).to_a.shuffle
  square = []
  N.times do
    square << perms.pop
    perms.reject!{|perm| perm.zip(square.last).any?{|el1, el2| el1 == el2} }
  end
  square
end

def print_square(square)
  cell_size = N.digits.size + 1
  strings = square.map!{|row| row.map!{|el| el.to_s.rjust(cell_size)}.join }
  puts strings, "\n"
end

2.times{print_square( generate_square)}


import "random" for Random

var rand = Random.new()

var printSquare = Fn.new { |latin|
    for (row in latin) System.print(row)
    System.print()
}

var latinSquare = Fn.new { |n|
    if (n <= 0) {
        System.print("[]\n")
        return
    }
    var latin = List.filled(n, null)
    for (i in 0...n) {
        latin[i] = List.filled(n, 0)
        if (i == n - 1) break
        for (j in 0...n) latin[i][j] = j
    }

    // first row
    rand.shuffle(latin[0])

    // middle row(s)
    for (i in 1...n-1) {
        var shuffled = false
        while (!shuffled) {
            rand.shuffle(latin[i])
            var shuffling = false
            for (k in 0...i) {
                for (j in 0...n) {
                    if (latin[k][j] == latin[i][j]) {
                        shuffling = true
                        break
                    }
                }
                if (shuffling) break
            }
            if (!shuffling) shuffled = true
        }
    }

    // last row
    for (j in 0...n) {
        var used = List.filled(n, false)
        for (i in 0...n-1) used[latin[i][j]] = true
        for (k in 0...n) {
            if (!used[k]) {
                latin[n-1][j] = k
                break
            }
        }
    }
    printSquare.call(latin)
}

latinSquare.call(5)
latinSquare.call(5)
latinSquare.call(10) // for good measure


fcn randomLatinSquare(n,symbols=[1..]){  //--> list of lists
   if(n<=0) return(T);
   square,syms := List(), symbols.walker().walk(n);
   do(n){ syms=syms.copy(); square.append(syms.append(syms.pop(0))) }
   // shuffle rows, transpose & shuffle columns
   T.zip(square.shuffle().xplode()).shuffle();
}
fcn rls2String(square){ square.apply("concat"," ").concat("\n") }


Deque[String] my_queue

my_queue.append(‘foo’)
my_queue.append(‘bar’)
my_queue.append(‘baz’)

print(my_queue.pop_left())
print(my_queue.pop_left())
print(my_queue.pop_left())


queuePointerStart equ #$FD
queuePointerMinus1 equ #$FC     ;make this equal whatever "queuePointerStart" is, minus 1.
pushQueue:
STA 0,x
DEX
RTS

popQueue:
STX temp
LDX #queuePointerStart
LDA 0,x ;get the item that's first in line
PHA
    LDX #queuePointerMinus1
loop_popQueue:
    LDA 0,X
    STA 1,X
    DEX
    CPX temp
    BNE loop_popQueue
    LDX temp
    INX
PLA ;return the item that just left the queue
RTS

isQueueEmpty:
LDA #1
CPX #queuePointerStart
BEQ yes  ;return 1

SEC
SBC #1   ;return 0

yes:
RTS


10 q:new  \ create a new queue 10 deep
123 q:push
341 q:push  \ push 123, 341 onto the queue
q:pop . cr  \ displays 123
q:len . cr  \ displays 1
q:pop . cr  \ displays 341
q:len . cr  \ displays 0


with FIFO;
with Ada.Text_Io; use Ada.Text_Io;

procedure Queue_Test is
   package Int_FIFO is new FIFO (Integer);
   use Int_FIFO;
   Queue : FIFO_Type;
   Value : Integer;
begin
   Push (Queue, 1);
   Push (Queue, 2);
   Push (Queue, 3);
   Pop (Queue, Value);
   Pop (Queue, Value);
   Push (Queue, 4);
   Pop (Queue, Value);
   Pop (Queue, Value);
   Push (Queue, 5);
   Pop (Queue, Value);
   Put_Line ("Is_Empty " & Boolean'Image (Is_Empty (Queue)));
end Queue_Test;


# -*- coding: utf-8 -*- #
MODE DIETITEM = STRUCT(
  STRING food, annual quantity, units, REAL cost
);

# Stigler's 1939 Diet ... #
FORMAT diet item fmt = $g": "g" "g" = $"zd.dd$;
[]DIETITEM stigler diet = (
  ("Cabbage",           "111","lb.",  4.11),
  ("Dried Navy Beans",  "285","lb.", 16.80),
  ("Evaporated Milk",    "57","cans", 3.84),
  ("Spinach",            "23","lb.",  1.85),
  ("Wheat Flour",       "370","lb.", 13.33),
  ("Total Annual Cost",    "","",    39.93)
)


on push(StackRef, value)
    set StackRef's contents to {value} & StackRef's contents
    return StackRef
end push

on pop(StackRef)
    set R to missing value
    if StackRef's contents ≠ {} then
        set R to StackRef's contents's item 1
        set StackRef's contents to {} & rest of StackRef's contents
    end if
    return R
end pop

on isStackEmpty(StackRef)
    if StackRef's contents = {} then return true
    return false
end isStackEmpty

set theStack to {}
repeat with i from 1 to 5
    push(a reference to theStack, i)
    log result
end repeat
repeat until isStackEmpty(theStack) = true
    pop(a reference to theStack)
    log result
end repeat


let my_queue = Queue()

my_queue.push!('foo')
my_queue.push!('bar')
my_queue.push!('baz')

print my_queue.pop!() # 'foo'
print my_queue.pop!() # 'bar'
print my_queue.pop!() # 'baz'


push("qu", 2), push("qu", 44), push("qu", "xyz") ; TEST

MsgBox % "Len = " len("qu") ; Number of entries
While !empty("qu")          ; Repeat until queue is not empty
    MsgBox % pop("qu")      ; Print popped values (2, 44, xyz)
MsgBox Error = %ErrorLevel% ; ErrorLevel =  0: OK
MsgBox % pop("qu")          ; Empty
MsgBox Error = %ErrorLevel% ; ErrorLevel = -1: popped too much
MsgBox % "Len = " len("qu") ; Number of entries

push(queue,_) {             ; push _ onto queue named "queue" (!=_), _ string not containing |
    Global
    %queue% .= %queue% = "" ? _ : "|" _
}

pop(queue) {                ; pop value from queue named "queue" (!=_,_1,_2)
    Global
    RegExMatch(%queue%, "([^\|]*)\|?(.*)", _)
    Return _1, ErrorLevel := -(%queue%=""), %queue% := _2
}

empty(queue) {              ; check if queue named "queue" is empty
    Global
    Return %queue% = ""
}

len(queue) {                ; number of entries in "queue"
    Global
    StringReplace %queue%, %queue%, |, |, UseErrorLevel
    Return %queue% = "" ? 0 : ErrorLevel+1
}


function deque(arr) {
    arr["start"] = 0
    arr["end"] = 0
}

function dequelen(arr) {
    return arr["end"] - arr["start"]
}

function empty(arr) {
    return dequelen(arr) == 0
}

function push(arr, elem) {
    arr[++arr["end"]] = elem
}

function pop(arr) {
    if (empty(arr)) {
        return
    }
    return arr[arr["end"]--]
}

function unshift(arr, elem) {
    arr[arr["start"]--] = elem
}

function shift(arr) {
    if (empty(arr)) {
        return
    }
    return arr[++arr["start"]]
}

function printdeque(arr,    i, sep) {
    printf("[")
    for (i = arr["start"] + 1; i <= arr["end"]; i++) {
        printf("%s%s", sep, arr[i])
        sep = ", "
    }
    printf("]\n")
}

BEGIN {
    deque(q)
    for (i = 1; i <= 10; i++) {
        push(q, i)
    }
    printdeque(q)
    for (i = 1; i <= 10; i++) {
        print shift(q)
    }
    printdeque(q)
}


      FIFOSIZE = 1000

      FOR n = 3 TO 5
        PRINT "Push ";n : PROCenqueue(n)
      NEXT
      PRINT "Pop " ; FNdequeue
      PRINT "Push 6" : PROCenqueue(6)
      REPEAT
        PRINT "Pop " ; FNdequeue
      UNTIL FNisempty
      PRINT "Pop " ; FNdequeue
      END

      DEF PROCenqueue(n) : LOCAL f%
      DEF FNdequeue : LOCAL f% : f% = 1
      DEF FNisempty : LOCAL f% : f% = 2
      PRIVATE fifo(), rptr%, wptr%
      DIM fifo(FIFOSIZE-1)
      CASE f% OF
        WHEN 0:
          wptr% = (wptr% + 1) MOD FIFOSIZE
          IF rptr% = wptr% ERROR 100, "Error: queue overflowed"
          fifo(wptr%) = n
        WHEN 1:
          IF rptr% = wptr% ERROR 101, "Error: queue empty"
          rptr% = (rptr% + 1) MOD FIFOSIZE
          = fifo(rptr%)
        WHEN 2:
          = (rptr% = wptr%)
      ENDCASE
      ENDPROC


  ( queue
  =   (list=)
      (enqueue=.(.!arg) !(its.list):?(its.list))
      ( dequeue
      =   x
        .   !(its.list):?(its.list) (.?x)
          & !x
      )
      (empty=.!(its.list):)
  )
& new$queue:?Q
& (   (Q..enqueue)$1
    & (Q..enqueue)$2
    & (Q..enqueue)$3
    & out$((Q..dequeue)$)
    & (Q..enqueue)$4
    & out$((Q..dequeue)$)
    & out$((Q..dequeue)$)
    &   out
      $ ( The
          queue
          is
          ((Q..empty)$&|not)
          empty
        )
    & out$((Q..dequeue)$)
    &   out
      $ ( The
          queue
          is
          ((Q..empty)$&|not)
          empty
        )
    & out$((Q..dequeue)$)
    & out$Success!
  | out$"Attempt to dequeue failed"
  )
;


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

#include <sys/queue.h>

/* #include "fifolist.h" */

int main()
{
  int i;
  FIFOList head;

  TAILQ_INIT(&head);

  /* insert 20 integer values */
  for(i=0; i < 20; i++) {
    m_enqueue(i, &head);
  }

  /* dequeue and print */
  while( m_dequeue(&i, &head) )
    printf("%d\n", i);

  fprintf(stderr, "FIFO list %s\n",
      ( m_dequeue(&i, &head) ) ?
      "had still an element" :
      "is void!");

  exit(0);
}


using System;
using System.Collections.Generic;

namespace RosettaCode
{
    class Program
    {
        static void Main()
        {
            // Create a queue and "push" items into it
            Queue<int> queue  = new Queue<int>();
            queue.Enqueue(1);
            queue.Enqueue(3);
            queue.Enqueue(5);

            // "Pop" items from the queue in FIFO order
            Console.WriteLine(queue.Dequeue()); // 1
            Console.WriteLine(queue.Dequeue()); // 3
            Console.WriteLine(queue.Dequeue()); // 5

            // To tell if the queue is empty, we check the count
            bool empty = queue.Count == 0;
            Console.WriteLine(empty); // "True"

            // If we try to pop from an empty queue, an exception
            // is thrown.
            try
            {
                queue.Dequeue();
            }
            catch (InvalidOperationException exception)
            {
                Console.WriteLine(exception.Message); // "Queue empty."
            }
        }
    }
}


#include <queue>
#include <cassert> // for run time assertions

int main()
{
  std::queue<int> q;
  assert( q.empty() );        // initially the queue is empty

  q.push(1);                  // add an element
  assert( !q.empty() );       // now the queue isn't empty any more
  assert( q.front() == 1 );   // the first element is, of course, 1

  q.push(2);                  // add another element
  assert( !q.empty() );       // it's of course not empty again
  assert( q.front() == 1 );   // the first element didn't change

  q.push(3);                  // add yet an other element
  assert( !q.empty() );       // the queue is still not empty
  assert( q.front() == 1 );   // and the first element is still 1

  q.pop();                    // remove the first element
  assert( !q.empty() );       // the queue is not yet empty
  assert( q.front() == 2);    // the first element is now 2 (the 1 is gone)

  q.pop();
  assert( !q.empty() );
  assert( q.front() == 3);

  q.push(4);
  assert( !q.empty() );
  assert( q.front() == 3);

  q.pop();
  assert( !q.empty() );
  assert( q.front() == 4);

  q.pop();
  assert( q.empty() );

  q.push(5);
  assert( !q.empty() );
  assert( q.front() == 5);

  q.pop();
  assert( q.empty() );
}


(def q (make-queue))

(enqueue q 1)
(enqueue q 2)
(enqueue q 3)

(dequeue q) ; 1
(dequeue q) ; 2
(dequeue q) ; 3

(queue-empty? q) ; true


# We build a Queue on top of an ordinary JS array, which supports push
# and shift.  For simple queues, it might make sense to just use arrays
# directly, but this code shows how to encapsulate the array behind a restricted
# API.  For very large queues, you might want a more specialized data
# structure to implement the queue, in case arr.shift works in O(N) time, which
# is common for array implementations.  On my laptop I start noticing delay
# after about 100,000 elements, using node.js.
Queue = ->
  arr = []
  enqueue: (elem) ->
    arr.push elem
  dequeue: (elem) ->
    throw Error("queue is empty") if arr.length == 0
    arr.shift elem
  is_empty: (elem) ->
    arr.length == 0

# test
do ->
  q = Queue()
  for i in [1..100000]
    q.enqueue i

  console.log q.dequeue() # 1
  while !q.is_empty()
    v = q.dequeue()
  console.log v # 1000

  try
    q.dequeue() # throws Error
  catch e
    console.log "#{e}"


(let ((queue (make-queue)))
  (enqueue 38 queue)
  (assert (not (queue-empty-p queue)))
  (enqueue 23 queue)
  (assert (eql 38 (dequeue queue)))
  (assert (eql 23 (dequeue queue)))
  (assert (queue-empty-p queue)))


MODULE UseQueue;
IMPORT
  Queue,
  Boxes,
  StdLog;

PROCEDURE Do*;
VAR
  q: Queue.Instance;
  b: Boxes.Box;
BEGIN
  q := Queue.New(10);
  q.Push(Boxes.NewInteger(1));
  q.Push(Boxes.NewInteger(2));
  q.Push(Boxes.NewInteger(3));
  b := q.Pop();
  b := q.Pop();
  q.Push(Boxes.NewInteger(4));
  b := q.Pop();
  b := q.Pop();
  StdLog.String("Is empty:> ");StdLog.Bool(q.IsEmpty());StdLog.Ln
END Do;
END UseQueue.


include "cowgol.coh";

typedef QueueData is uint8; # the queue will contain bytes
include "queue.coh"; # from the Queue/Definition task

var queue := MakeQueue();

# enqueue bytes 0 to 20
print("Enqueueing: ");
var n: uint8 := 0;
while n < 20 loop
    print_i8(n);
    print_char(' ');
    Enqueue(queue, n);
    n := n + 1;
end loop;
print_nl();

# dequeue and print everything in the queue
print("Dequeueing: ");
while QueueEmpty(queue) == 0 loop
    print_i8(Dequeue(queue));
    print_char(' ');
end loop;
print_nl();

# free the queue
FreeQueue(queue);


class LinkedQueue(T) {
    private static struct Node {
        T data;
        Node* next;
    }

    private Node* head, tail;

    bool empty() { return head is null; }

    void push(T item) {
        if (empty())
            head = tail = new Node(item);
        else {
            tail.next = new Node(item);
            tail = tail.next;
        }
    }

    T pop() {
        if (empty())
            throw new Exception("Empty LinkedQueue.");
        auto item = head.data;
        head = head.next;
        if (head is tail) // Is last one?
            // Release tail reference so that GC can collect.
            tail = null;
        return item;
    }

    alias push enqueue;
    alias pop dequeue;
}

void main() {
    auto q = new LinkedQueue!int();
    q.push(10);
    q.push(20);
    q.push(30);
    assert(q.pop() == 10);
    assert(q.pop() == 20);
    assert(q.pop() == 30);
    assert(q.empty());
}


program QueueUsage;

{$APPTYPE CONSOLE}

uses Generics.Collections;

var
  lStringQueue: TQueue<string>;
begin
  lStringQueue := TQueue<string>.Create;
  try
    lStringQueue.Enqueue('First');
    lStringQueue.Enqueue('Second');
    lStringQueue.Enqueue('Third');

    Writeln(lStringQueue.Dequeue);
    Writeln(lStringQueue.Dequeue);
    Writeln(lStringQueue.Dequeue);

    if lStringQueue.Count = 0 then
      Writeln('Queue is empty.');
  finally
    lStringQueue.Free;
  end
end.