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

size = 8
newSize = size
count = 0
sizeBoard = 0
Queens = list(size)
Board = []
badBoard = []

win = null
nMoves = 0
oldx = 0
oldy = 0
bWidth = 0
bHeight = 0

moveX = 550 moveY = 140		### Open Window on Screen Position
sizeX = 800 sizeY = 800		### Size of Window

Button	= null
cmbSize = null
Pink = newlist(size,size)

Tiles = newlist(size,size)
TitleMoves = null
lineSize = null
LayoutButtonRow = list(size)
LayoutButtonMain = null

WQueen = "WQueen.png"
oPic = new QPixmap("WQueen.png")
oPicGray = new QPixmap("Gray.png")
oPicGreen = new QPixmap("Green.png")

nMoves = 0

wwidth = 0
wheight = 0
WinWidth = 0
WinHeight = 0

C_Spacing  = 2
C_ButtonFirstStyle	= 'border-radius:1px; color:black; background-color: rgb(229,249,203) ;'		### Square pale
				###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: gray;'

C_ButtonSecondStyle	= 'border-radius:1px; color:black; background-color: rgb(179,200,93); '			### Square dark
				###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: darkGray; '

C_ButtonPinkStyle	= 'border-radius:1px; color:black; background-color: rgb(255,179,191); '   ### light pink
				###'border-style: outset; border-width: 2px; border-radius: 2px; border-color: darkGray; '

app = new qApp
{
	DrawWidget()
        newWindow(size)
        exec()
}

### FUNCTIONS

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

Func DrawWidget()

	### Global definition for win

	win = new qWidget()
	{
		# Set the Window Icon
		setWindowIcon(new qIcon(new qPixmap(WQueen)))
                win.setminimumwidth(700)
                win.setminimumheight(700)

		Button = newList(size, size)	    ### Internal Array with Letters

		setWindowTitle('Eight Queens Game')
		setStyleSheet('background-color:White')

		workHeight = win.height()
		fontSize   = 8 + (workHeight / 100)

		move(moveX, moveY)
                resize(700,700)

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

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

		###----------------------------------------------
		### Title Top Row - Moves Count

			TitleMoves = new qLineEdit(win)
			{
				setStyleSheet("background-color:rgb(255,255,204)")
				setFont(new qFont("Calibri",fontsize,100,0))
				setAlignment( Qt_AlignHCenter)
				setAlignment( Qt_AlignVCenter)
				setText(" Moves: "+ nMoves)
			}

			sizeBtn = new QPushButton(win)
			{
				    setStyleSheet("background-color:rgb(255,255,204)")
				    setFont(new qFont("Calibri",fontsize,100,0))
				    setText(" Enter size: ")
			}

			lineSize = new qLineEdit(win)
			{
				setStyleSheet("background-color:rgb(255,255,204)")
				setFont(new qFont("Calibri",fontsize,100,0))
				setAlignment( Qt_AlignHCenter)
				setAlignment( Qt_AlignVCenter)
            setreturnPressedEvent("newBoardSize()")
				setText(" 8 ")
			}

			SolveGame = new QPushButton(win)
			{
				    setStyleSheet("background-color:rgb(255,204,229)")
				    setFont(new qFont("Calibri",fontsize,100,0))
				    setText(" Solve ")
				    setClickEvent("solveGame()")
			}

			NewGame	 = new QPushButton(win)
			{
				setStyleSheet("background-color:rgb(255,204,229)")
				setFont(new qFont("Calibri",fontsize,100,0))
				setText(" New ")
				setClickEvent("newGame()")
			}

			btnQuit	 = new QPushButton(win)
			{
				setStyleSheet("background-color:rgb(255,204,229)")
				setFont(new qFont("Calibri",fontsize,100,0))
				setText("Exit")
				setClickEvent("pQuit()")
			}

		###------------------------------------------------

		### QVBoxLayout lays out widgets in a vertical column, from top to bottom.

		### Vertical
		LayoutButtonMain = new QVBoxLayout()

		LayoutButtonMain.setSpacing(C_Spacing)
		LayoutButtonMain.setContentsMargins(5,5,5,5)

		### Horizontal - TOP ROW
			LayoutTitleRow = new QHBoxLayout()
			{
				setSpacing(C_Spacing)
				setContentsMargins(0,0,0,0)
			}

			LayoutTitleRow.AddWidget(TitleMoves)
			LayoutTitleRow.AddWidget(sizeBtn)
			LayoutTitleRow.AddWidget(lineSize)
			LayoutTitleRow.AddWidget(SolveGame)
			LayoutTitleRow.AddWidget(NewGame)
			LayoutTitleRow.AddWidget(btnQuit)

			LayoutButtonMain.AddLayout(LayoutTitleRow)

		###----------------------------------------------
		### BUTTON ROWS

		LayoutButtonRow = list(size)

		### QHBoxLayout lays out widgets in a horizontal row, from left to right

		odd = 1
		for Row = 1 to size

			LayoutButtonRow[Row] = new QHBoxLayout()	### Horizontal
			{
				setSpacing(C_Spacing)
				setContentsmargins(0,0,0,0)
			}

			for Col = 1 to size

				### Create Buttons

					Button[Row][Col] = new QPushButton(win)
					{
						if odd % 2 = 0
							setStyleSheet(C_ButtonFirstStyle)
							odd++
						else
							setStyleSheet(C_ButtonSecondStyle)
							odd++
						ok
						setClickEvent("UserLeftClick(" + string(Row) +
								 "," + string(Col) + ")")
						setSizePolicy(1,1)
                                                resize(bwidth,bheight)
					}

				        ### Widget - Add HORZ BOTTON
					LayoutButtonRow[Row].AddWidget(Button[Row][Col])
			next
                        if size % 2 = 0
                           odd++
                        ok

		                ### Layout - Add ROW of BUTTONS
				LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
		next

		###-------------------------------------------------

		setLayout(LayoutButtonMain)

		show()
	}

return

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

func newSize()
     nSize = cmbSize.currentText()
     nSize = number(nSize)
     count = 0
     newWindow(nSize)

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

func newBoardSize()
     nrSize = number(lineSize.text())
     newWindow(nrSize)

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

func newWindow(newSize)

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

                size = newSize
                nMoves = 0
                TitleMoves.settext(" Moves: 0")

                Tiles = newlist(size,size)
                for Row = 1 to size
                    for Col = 1 to size
                        Tiles[Row][Col] = 0
                    next
                next

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

                win.resize(500,500)

                Button = newlist(size,size)
                Pink = newlist(size,size)

		LayoutButtonRow = list(size)

		### QHBoxLayout lays out widgets in a horizontal row, from left to right

                odd = 1
		for Row = 1 to size

			LayoutButtonRow[Row] = new QHBoxLayout()	### Horizontal
			{
				setSpacing(C_Spacing)
				setContentsmargins(0,0,0,0)
			}

			for Col = 1 to size

				### Create Buttons

					Button[Row][Col] = new QPushButton(win)
					{
						if odd % 2 = 1
							setStyleSheet(C_ButtonFirstStyle)
							odd++
						else
							setStyleSheet(C_ButtonSecondStyle)
							odd++
						ok
						setClickEvent("UserLeftClick(" + string(Row) +
								 "," + string(Col) + ")")
						setSizePolicy(1,1)
                                                resize(bwidth,bheight)
					}

				        ### Widget - Add HORZ BOTTON
					LayoutButtonRow[Row].AddWidget(Button[Row][Col])
			next
                        if size % 2 = 0
                           odd++
                        ok

		                ### Layout - Add ROW of BUTTONS
				LayoutButtonMain.AddLayout(LayoutButtonRow[Row])
		next

		###-------------------------------------------------

		win.setLayout(LayoutButtonMain)

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

func solveGame()

     newWindow(size)

     for Row = 1 to size
         for Col = 1 to size
             Tiles[Row][Col] = 0
         next
     next

     bwidth  = (win.width()  -8 ) / size            // <<< QT FIX because of Win Title
     bheight = (win.height() -32) / size            // <<< QT FIX because of Win Title

     odd = 1
     for Row = 1 to size
         for Col = 1 to size
	     if odd % 2 = 1
		setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight)
		odd++
	     else
		setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight)
		odd++
	     ok
         next
         if size % 2 = 0
            odd++
         ok
     next

     Queens = list(20)
     n = size
     count = count + 1
     if count = 1
        Board = []
        queen(1,n)
     ok

     sizeBoard = len(Board)/size
     num = random(sizeBoard-1) + 1
     see "Solution = " + num + nl

     for n = (num-1)*size+1 to num*size
         x = Board[n][2]
         y = Board[n][1]
         Tiles[x][y]  = 1
         setButtonImage(Button[x][y],oPic,bwidth-8,bheight)

     next

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

func prn(n)

     for i = 1 to n
         for j = 1 to n
             if Queens[i] = j
                add(Board,[i,j])
             ok
         next
     next

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

func place(row,column)

     for i = 1 to row-1
         if Queens[i]=column
            return 0
         else
            if fabs(Queens[i]-column) = fabs(i-row)
               return 0
            ok
         ok
     next
     return 1

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

func queen(row,n)

     for column = 1 to n
         if place(row,column)
            Queens[row] = column
            if row = n
               prn(n)
            else
               queen(row+1,n)
            ok
         ok
     next

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

func newGame

     newWindow(size)
     return

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

func canPlace Row,Col

     badBoard = []
     add(badBoard,[Row,Col])
     bwidth  = (win.width()  -8 ) / size            // <<< QT FIX because of Win Title
     bheight = (win.height() -32) / size            // <<< QT FIX because of Win Title
        cp1 = 1
        for n = 1 to size
            if Row < 9
               if n != Col and Tiles[Row][n] = 1
                  cp1 = 0
                  add(badBoard,[Row,n])
                  exit
               ok
            ok
        next

        cp2 = 1
        for n = 1 to size
            if Col < 9
               if n != Row and Tiles[n][Col] = 1
                  cp2 = 0
                  add(badBoard,[n,Col])
                  exit
               ok
            ok
        next

        cp3 = 1
        for x = 1 to size
            if Row + x < size + 1 and Col - x > 0
               if Tiles[Row+x][Col-x] = 1
                  cp3 = 0
                  add(badBoard,[Row+x,Col-x])
                  exit
               ok
            ok
        next

        cp4 = 1
        for x = 1 to size
            if Row - x > 0 and Col + x < size + 1
               if Tiles[Row-x][Col+x] = 1
                  cp4 = 0
                  add(badBoard,[Row-x,Col+x])
                  exit
               ok
            ok
        next

        cp5 = 1
        for x = 1 to size
            if Row + x < size + 1 and Col + x < size + 1
               if Tiles[Row+x][Col+x] = 1
                  cp5 = 0
                  add(badBoard,[Row+x,Col+x])
                  exit
               ok
            ok
        next

        cp6 = 1
        for x = 1 to size
            if Row - x > 0 and Col - x > 0
               if Tiles[Row-x][Col-x] = 1
                  cp6 = 0
                  add(badBoard,[Row-x,Col-x])
                  exit
               ok
            ok
        next

        cp7 = cp1 and cp2 and cp3 and cp4 and cp5 and cp6

        return cp7

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

func resizeBoard

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

     for Row = 1 to size
         for Col = 1 to size
             if Tiles[Row][Col] = 1
                setButtonImage(Button[Row][Col],oPic,bwidth - 8,bheight - 8)
             ok
         next
     next

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

func UserLeftClick Row,Col

     sleep(0.3)
     Tiles[Row][Col] = 1

     bWidthHeight()

     bool = (Row = oldx) and (Col = oldy)

     cp8 = canPlace(Row,Col)

     if Pink[Row][Col] = 1
        Pink[Row][Col] = 0
        Tiles[Row][Col] = 0
        if Row % 2 = 1 and Col % 2 = 1
           Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
           setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
        ok
        if Row % 2 = 0 and Col % 2 = 0
           Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
           setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
        ok
        if Row % 2 = 1 and Col % 2 = 0
           Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
           setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
        ok
        if Row % 2 = 0 and Col % 2 = 1
           Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
           setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
        ok
        checkBoard()
        return
     ok

     if cp8 = 1 and bool = 0
        setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
        Tiles[Row][Col] = 1
        nMoves = nMoves + 1
        oldx = Row
        oldy = Col
        TitleMoves.settext(" Moves: " + nMoves)
        gameOver()
     ok
     if cp8 = 1 and bool = 1
        if Row % 2 = 1 and Col % 2 = 1
           setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
        ok
        if Row % 2 = 0 and Col % 2 = 0
           setButtonImage(Button[Row][Col],oPicGray,bwidth-8,bheight-8)
        ok
        if Row % 2 = 1 and Col % 2 = 0
           setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
        ok
        if Row % 2 = 0 and Col % 2 = 1
           setButtonImage(Button[Row][Col],oPicGreen,bwidth-8,bheight-8)
        ok
        Tiles[Row][Col] = 1
     ok

     for Row = 1 to size
         for Col = 1 to size
             if Tiles[Row][Col] = 1
                setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
             ok
         next
     next

     if cp8 = 0
        pBadCell(Row,Col)
        return
     ok

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

func checkBoard()

     for Row = 1 to size
         for Col = 1 to size
         if Pink[Row][Col] = 1
            cp9 = canPlace(Row,Col)
            if cp9 = 0
               Button[Row][Col].setStyleSheet(C_ButtonPinkStyle)
               setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight)
            else
               if Row % 2 = 1 and Col % 2 = 1
                  Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
                  setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
               ok
               if Row % 2 = 0 and Col % 2 = 0
                  Button[Row][Col].setStyleSheet(C_ButtonFirstStyle)
                  setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
               ok
               if Row % 2 = 1 and Col % 2 = 0
                  Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
                  setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
               ok
               if Row % 2 = 0 and Col % 2 = 1
                  Button[Row][Col].setStyleSheet(C_ButtonSecondStyle)
                  setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight-8)
               ok
            ok
         ok
         next
     next

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

func pBadCell(Row,Col)

     for n = 1 to len(badBoard)
         Row = badBoard[n][1]
         Col = badBoard[n][2]
         Pink[Row][Col] = 1
         Button[Row][Col].setStyleSheet(C_ButtonPinkStyle)
         setButtonImage(Button[Row][Col],oPic,bwidth-8,bheight)
     next

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

func setButtonImage oBtn,oPixmap,width,height
     oBtn { setIcon(new qicon(oPixmap.scaled(width(),height(),0,0)))
	    setIconSize(new QSize(width,height))
	  }

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

func bWidthHeight()

     bWidth  = (win.width()  -8 ) / size
     bHeight = (win.height() -32) / size

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

func msgBox cText
     mb = new qMessageBox(win) {
	  setWindowTitle('Eight Queens')
	  setText(cText)
          setstandardbuttons(QMessageBox_OK)
          result = exec()
     }

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

func pQuit()
     win.close()

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

func gameOver

     total = 0
     for Row = 1 to size
         for Col = 1 to size
             if Tiles[Row][Col] = 1
                total = total + 1
             ok
         next
     next

     if total = size
        for Row = 1 to size
            for Col = 1 to size
                Button[Row][Col].setenabled(false)
            next
        next
        msgBox("You Win!")
     ok

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


>function map MonteCarloPI (n,plot=false) ...
$  X:=random(1,n);
$  Y:=random(1,n);
$  if plot then
$      plot2d(X,Y,>points,style=".");
$      plot2d("sqrt(1-x^2)",color=2,>add);
$  endif
$  return sum(X^2+Y^2<1)/n*4;
$endfunction
>MonteCarloPI(10^(1:7))
 [ 3.6  2.96  3.224  3.1404  3.1398  3.141548  3.1421492 ]
>pi
 3.14159265359
>MonteCarloPI(10000,true):


let print x = printfn "%A" x

let MonteCarloPiGreco niter =
    let eng = System.Random()
    let action () =
        let x: float = eng.NextDouble()
        let y: float = eng.NextDouble()
        let res: float = System.Math.Sqrt(x**2.0 + y**2.0)
        if res < 1.0 then
            1
        else
            0
    let res = [ for x in 1..niter do yield action() ]
    let tmp: float = float(List.reduce (+) res) / float(res.Length)
    4.0*tmp

MonteCarloPiGreco 1000 |> print
MonteCarloPiGreco 10000 |> print
MonteCarloPiGreco 100000 |> print


USING: kernel math math.functions random sequences ;

: limit ( -- n ) 2 32 ^ ; inline
: in-circle ( x y -- ? ) limit [ sq ] [email protected] [ + ] [ <= ] bi* ;
: rand ( -- r ) limit random ;
: pi ( n -- pi ) [ [ drop rand rand in-circle ] count ] keep / 4 * >float ;


# 1. Divide n by 12. Remember the remainder (n is 8 for the eight queens
#    puzzle).
# 2. Write a list of the even numbers from 2 to n in order.
# 3. If the remainder is 3 or 9, move 2 to the end of the list.
# 4. Append the odd numbers from 1 to n in order, but, if the remainder is 8,
#    switch pairs (i.e. 3, 1, 7, 5, 11, 9, …).
# 5. If the remainder is 2, switch the places of 1 and 3, then move 5 to the
#    end of the list.
# 6. If the remainder is 3 or 9, move 1 and 3 to the end of the list.
# 7. Place the first-column queen in the row with the first number in the
#    list, place the second-column queen in the row with the second number in
#    the list, etc.

def n_queens(n)
  if n == 1
    return "Q"
  elsif n < 4
    puts "no solutions for n=#{n}"
    return ""
  end

  evens = (2..n).step(2).to_a
  odds = (1..n).step(2).to_a

  rem = n % 12  # (1)
  nums = evens  # (2)

  nums.rotate if rem == 3 or rem == 9  # (3)

  # (4)
  if rem == 8
    odds = odds.each_slice(2).flat_map(&:reverse)
  end
  nums.concat(odds)

  # (5)
  if rem == 2
    nums[nums.index(1)], nums[nums.index(3)] = nums[nums.index(3)], nums[nums.index(1)]
    nums << nums.delete(5)
  end

  # (6)
  if rem == 3 or rem == 9
    nums << nums.delete(1)
    nums << nums.delete(3)
  end

  # (7)
  nums.map do |q|
    a = Array.new(n,".")
    a[q-1] = "Q"
    a*(" ")
  end
end

(1 .. 15).each {|n| puts "n=#{n}"; puts n_queens(n); puts}


class MontyCarlo
{
  // assume square/circle of width 1 unit
  static Float findPi (Int samples)
  {
    Int insideCircle := 0
    samples.times
    {
      x := Float.random
      y := Float.random
      if ((x*x + y*y).sqrt <= 1.0f) insideCircle += 1
    }
    return insideCircle * 4.0f / samples
  }

  public static Void main ()
  {
    [100, 1000, 10000, 1000000, 10000000].each |sample|
    {
      echo ("Sample size $sample gives PI as ${findPi(sample)}")
    }
  }
}


include random.fs

10000 value r

: hit? ( -- ? )
  r random dup *
  r random dup * +
  r dup * < ;

: sims ( n -- hits )
  0 swap 0 do hit? if 1+ then loop ;


MODULE Simulation

   IMPLICIT NONE

   CONTAINS

   FUNCTION Pi(samples)
     REAL :: Pi
     REAL :: coords(2), length
     INTEGER :: i, in_circle, samples

     in_circle = 0
     DO i=1, samples
       CALL RANDOM_NUMBER(coords)
       coords = coords * 2 - 1
       length = SQRT(coords(1)*coords(1) + coords(2)*coords(2))
       IF (length <= 1) in_circle = in_circle + 1
     END DO
     Pi = 4.0 * REAL(in_circle) / REAL(samples)
   END FUNCTION Pi

 END MODULE Simulation

 PROGRAM MONTE_CARLO

   USE Simulation

   INTEGER :: n = 10000

   DO WHILE (n <= 100000000)
     WRITE (*,*) n, Pi(n)
     n = n * 10
   END DO

 END PROGRAM MONTE_CARLO


[loop]
input "How many queens (N>=4)";n
if n < 4 then
 print "Must be greater than 4"
 goto [loop]
end if

dim plot$(100,100)
dim q(n+20)
dim e(n+20)
dim o(n+20)
r=n mod 6
if r<>2 and r<>3 then
  gosub [samp]
  goto [shoBoard]
end if
for i=1 to int(n/2)
  e(i) = 2 * i
next
for i=1 to int((n/2)+.5)
 o(i) = 2 *i-1
next
if r = 2 then gosub [edt2]
if r = 3 then gosub [edt3]
s = 1
for i=1 to n
  if e(i)>0 then
    q(s) = e(i)
    s    = s+1
  end if
next
for i=1 to n
  if o(i) > 0 then
    q(s) = o(i)
    s    = s + 1
  end if
next
' print board
[shoBoard]
cls
for i = 1 to n
  plot$(i,26-q(i)) = "*"
  plot$(i,24-n)    = chr$(96+i)
  plot$(n+1,26-i)  = str$(i)
next i
for ii = 1 to 100
 for jj = 1 to 100
  print left$(plot$(jj,ii)+" ",1);
 next jj
print
next ii
end

' the simple case
[samp]
p = 1
for i = 1 to n
  if i mod 2=0 then
    q(p) = i
    p    = p + 1
  end if
next i
for i = 1 to n
  if i mod 2 then
    q(p) = i
    p    = p + 1
  end if
next
return
' edit list when remainder is 2
[edt2]
for i=1 to n
  if o(i) = 3 then
    o(i) = 1
   else
    if o(i)=1 then o(i) = 3
  end if
  if o(i) = 5 then
    o(i)= o(i) -1
   else
    if o(i) = 0 then
      o(i) = 5
      return
    end if
  end if
next

' edit list when remainder is 3
[edt3]
for i = 1 to n
  if e(i) = 2 then
    e(i)  = e(i)-1
   else
    if e(i) = 0 then
      e(i) = 2
      goto [more]
    end if
  end if
next i
' edit list some more
[more]
for i = 1 to n
  if (o(i)=1 or o(i)=3) then
    o(i) = o(i)-1
   else
    if o(i) = 0 then
      o(i)   = 1
      o(i+1) = 3
      return
    end if
  end if
next


' version 23-10-2016
' compile with: fbc -s console

Randomize Timer  'seed the random function

Dim As Double x, y, pi, error_
Dim As UInteger m = 10, n, n_start, n_stop = m, p

Print
Print " Mumber of throws  Ratio (Pi)     Error"
Print

Do
    For n = n_start To n_stop -1
        x = Rnd
        y = Rnd
        If (x * x + y * y) <= 1 Then p = p +1
    Next
    Print Using "    ############,  "; m ;
    pi = p * 4 / m
    error_ = 3.141592653589793238462643383280 - pi
    Print RTrim(Str(pi),"0");Tab(35); Using "##.#############"; error_
    m = m * 10
    n_start = n_stop
    n_stop = m
Loop Until m > 1000000000 ' 1,000,000,000

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


package main

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

func getPi(numThrows int) float64 {
    inCircle := 0
    for i := 0; i < numThrows; i++ {
        //a square with a side of length 2 centered at 0 has
        //x and y range of -1 to 1
        randX := rand.Float64()*2 - 1 //range -1 to 1
        randY := rand.Float64()*2 - 1 //range -1 to 1
        //distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
        dist := math.Hypot(randX, randY)
        if dist < 1 { //circle with diameter of 2 has radius of 1
            inCircle++
        }
    }
    return 4 * float64(inCircle) / float64(numThrows)
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(getPi(10000))
    fmt.Println(getPi(100000))
    fmt.Println(getPi(1000000))
    fmt.Println(getPi(10000000))
    fmt.Println(getPi(100000000))
}


const N: usize = 8;

fn try(mut board: &mut [[bool; N]; N], row: usize, mut count: &mut i64) {
   if row == N {
       *count += 1;
       for r in board.iter() {
           println!("{}", r.iter().map(|&x| if x {"x"} else {"."}.to_string()).collect::<Vec<String>>().join(" "))
       }
       println!("");
       return
   }
   for i in 0..N {
       let mut ok: bool = true;
       for j in 0..row {
           if board[j][i]
               || i+j >= row && board[j][i+j-row]
               || i+row < N+j && board[j][i+row-j]
           { ok = false }
       }
       if ok {
           board[row][i] = true;
           try(&mut board, row+1, &mut count);
           board[row][i] = false;
       }
   }
}

fn main() {
   let mut board: [[bool; N]; N] = [[false; N]; N];
   let mut count: i64 = 0;
   try (&mut board, 0, &mut count);
   println!("Found {} solutions", count)
}


import Control.Monad
import System.Random

getPi throws = do
  results <- replicateM throws one_trial
  return (4 * fromIntegral (sum results) / fromIntegral throws)
  where
    one_trial = do
      rand_x <- randomRIO (-1, 1)
      rand_y <- randomRIO (-1, 1)
      let dist :: Double
          dist = sqrt (rand_x * rand_x + rand_y * rand_y)
      return (if dist < 1 then 1 else 0)


FUNCTION Pi(samples)
   inside = 0
   DO i = 1, samples
      inside = inside + ( (RAN(1)^2 + RAN(1)^2)^0.5 <= 1)
   ENDDO
   Pi = 4 * inside / samples
END

   WRITE(ClipBoard) Pi(1E4) ! 3.1504
   WRITE(ClipBoard) Pi(1E5) ! 3.14204
   WRITE(ClipBoard) Pi(1E6) ! 3.141672
   WRITE(ClipBoard) Pi(1E7) ! 3.1412856


procedure main()
  every t := 10 ^ ( 5 to 9 ) do
     printf("Rounds=%d Pi ~ %r\n",t,getPi(t))
end

link printf

procedure getPi(rounds)
   incircle := 0.
   every 1 to rounds do
      if 1 > sqrt((?0 * 2 - 1) ^ 2 + (?0 * 2 - 1) ^ 2) then
         incircle +:= 1
   return 4 * incircle / rounds
end


/* Store all 92 permutations in a SAS dataset. Translation of Fortran 77 */
data queens;
array a{8} p1-p8;
array s{8};
array u{30};
n=8;
do i=1 to n;
a(i)=i;
end;
do i=1 to 4*n-2;
u(i)=0;
end;
m=0;
i=1;
r=2*n-1;
goto L40;
L30:
s(i)=j;
u(p)=1;
u(q+r)=1;
i=i+1;
L40:
if i>n then goto L80;
j=i;
L50:
z=a(i);
y=a(j);
p=i-y+n;
q=i+y-1;
a(i)=y;
a(j)=z;
if u(p)=0 and u(q+r)=0 then goto L30;
L60:
j=j+1;
if j<=n then goto L50;
L70:
j=j-1;
if j=i then goto L90;
z=a(i);
a(i)=a(j);
a(j)=z;
goto L70;
L80:
m=m+1;
output;
L90:
i=i-1;
if i=0 then goto L100;
p=i-a(i)+n;
q=i+a(i)-1;
j=s(i);
u(p)=0;
u(q+r)=0;
goto L60;
L100:
put n m;
keep p1-p8;
run;


piMC=: monad define "0
  4* y%~ +/ 1>: %: +/ *: <: +: (2,y) [email protected]$ 0
)


public class MC {
	public static void main(String[] args) {
		System.out.println(getPi(10000));
		System.out.println(getPi(100000));
		System.out.println(getPi(1000000));
		System.out.println(getPi(10000000));
		System.out.println(getPi(100000000));

	}
	public static double getPi(int numThrows){
		int inCircle= 0;
		for(int i= 0;i < numThrows;i++){
			//a square with a side of length 2 centered at 0 has
			//x and y range of -1 to 1
			double randX= (Math.random() * 2) - 1;//range -1 to 1
			double randY= (Math.random() * 2) - 1;//range -1 to 1
			//distance from (0,0) = sqrt((x-0)^2+(y-0)^2)
			double dist= Math.sqrt(randX * randX + randY * randY);
			//^ or in Java 1.5+: double dist= Math.hypot(randX, randY);
			if(dist < 1){//circle with diameter of 2 has radius of 1
				inCircle++;
			}
		}
		return 4.0 * inCircle / numThrows;
	}
}


object NQueens {

  private implicit class RichPair[T](
    pair: (T,T))(
    implicit num: Numeric[T]
  ) {
    import num._

    def safe(x: T, y: T): Boolean =
      pair._1 - pair._2 != abs(x - y)
  }

  def solve(n: Int): Iterator[Seq[Int]] = {
    (0 to n-1)
      .permutations
      .filter { v =>
        (0 to n-1).forall { y =>
          (y+1 to n-1).forall { x =>
            (x,y).safe(v(x),v(y))
          }
        }
      }
  }

  def main(args: Array[String]): Unit = {
    val n = args.headOption.getOrElse("8").toInt
    val (solns1, solns2) = solve(n).duplicate
    solns1
      .zipWithIndex
      .foreach { case (soln, i) =>
        Console.out.println(s"Solution #${i+1}")
        output(n)(soln)
      }
    val n_solns = solns2.size
    if (n_solns == 1) {
      Console.out.println("Found 1 solution")
    } else {
      Console.out.println(s"Found $n_solns solutions")
    }
  }

  def output(n: Int)(board: Seq[Int]): Unit = {
    board.foreach { queen =>
      val row =
        "_|" * queen + "Q" + "|_" * (n-queen-1)
      Console.out.println(row)
    }
  }
}


function mcpi(n) {
    var x, y, m = 0;

    for (var i = 0; i < n; i += 1) {
        x = Math.random();
        y = Math.random();

        if (x * x + y * y < 1) {
            m += 1;
        }
    }

    return 4 * m / n;
}

console.log(mcpi(1000));
console.log(mcpi(10000));
console.log(mcpi(100000));
console.log(mcpi(1000000));
console.log(mcpi(10000000));


# In case gojq is used, trim leading 0s:
function prng {
    cat /dev/urandom | tr -cd '0-9' | fold -w 10 | sed 's/^0*\(.*\)*\(.\)*$/\1\2/'
}

prng | jq -nMr -f program.jq


(import (scheme base)
        (scheme write)
        (srfi 1))

;; return list of solutions to n-queens problem
(define (n-queens n) ; breadth-first solution
  (define (place-initial-row) ; puts a queen on each column of row 0
    (list-tabulate n (lambda (col) (list (cons 0 col)))))
  (define (place-on-row soln-so-far row)
    (define (invalid? col)
      (any (lambda (posn)
             (or (= col (cdr posn)) ; on same column
                 (= (abs (- row (car posn))) ; on same diagonal
                    (abs (- col (cdr posn))))))
           soln-so-far))
    ;
    (do ((col 0 (+ 1 col))
         (res '() (if (invalid? col)
                    res
                    (cons (cons (cons row col) soln-so-far)
                          res))))
      ((= col n) res)))
  ;
  (do ((res (place-initial-row)
            (apply append
                   (map (lambda (soln-so-far) (place-on-row soln-so-far row))
                        res)))
       (row 1 (+ 1 row)))
    ((= row n) res)))

;; display solutions in 2-d array form
(define (pretty-print solutions n)
  (define (posn->index posn)
    (+ (* n (cdr posn))
       (car posn)))
  (define (pp solution)
    (let ((board (make-vector (square n) ".")))
      (for-each (lambda (queen) (vector-set! board
                                             (posn->index queen)
                                             "Q"))
                solution)
      (let loop ((row 0)
                 (col 0))
        (cond ((= row n)
               (newline))
              ((= col n)
               (newline)
               (loop (+ 1 row) 0))
              (else
                (display (vector-ref board (posn->index (cons row col))))
                (loop row (+ 1 col)))))))
  ;
  (display (string-append "Found "
                          (number->string (length solutions))
                          " solutions for n="
                          (number->string n)
                          "\n\n"))
  (for-each pp solutions))

;; create table of number of solutions
(do ((n 1 (+ 1 n)))
  ((> n 10) )
  (display n)
  (display " ")
  (display (length (n-queens n)))
  (newline))

;; show some examples
(pretty-print (n-queens 1) 1)
(pretty-print (n-queens 2) 2)
(pretty-print (n-queens 3) 3)
(pretty-print (n-queens 4) 4)
(pretty-print (n-queens 5) 5)
(pretty-print (n-queens 8) 8)


using Printf

function monteπ(n)
    s = count(rand() ^ 2 + rand() ^ 2 < 1 for _ in 1:n)
    return 4s / n
end

for n in 10 .^ (3:8)
    p = monteπ(n)
    println("$(lpad(n, 9)): π ≈ $(lpad(p, 10)), pct.err = ", @sprintf("%2.5f%%", abs(p - π) / π))
end


// version 1.1.0

fun mcPi(n: Int): Double {
    var inside = 0
    (1..n).forEach {
        val x = Math.random()
        val y = Math.random()
        if (x * x + y * y <= 1.0) inside++
    }
    return 4.0 * inside / n
}

fun main(args: Array<String>) {
    println("Iterations -> Approx Pi  -> Error%")
    println("----------    ----------    ------")
    var n = 1_000
    while (n <= 100_000_000) {
        val pi = mcPi(n)
        val err = Math.abs(Math.PI - pi) / Math.PI * 100.0
        println(String.format("%9d  -> %10.8f -> %6.4f", n, pi, err))
        n *= 10
    }
}


//Length of board side
Board_size = 8;

function flag_out = no_attack(side, board, pos)
    //Evaluates (pos(1),pos(2)) in board if it's not on any queen attacking range
    //side (scalar): board's side length
    //board (sidexside matrix): matrix of 0s and 1s representing queens on a board
    //pos (1x2 matrix): postition on board to be evaluated
    //flag_out (bool): %T if position is available, and %F otherwise

    //Counting queens on rows and columns
    row_col = sum(board(pos(1),:)) + sum(board(:,pos(2)));

    //Counting queens on first diagonal
    diag_1 = sum(...
                 diag(board, 0 +...
                     (pos(2)>pos(1))*(pos(2)-pos(1)) +...
                     (pos(1)>pos(2))*(pos(2)-pos(1))...
                     )...
                 );

    //Counting queens on second diagonal
    a = pos(1) + pos(2);
    if a<=side+1 then
        rows = [1:a-1]
        cols = a - rows;
    else
        d = 2*(side+1)-a-1;
        rows = [side:-1:side-d+1]
        cols  = a - rows;
    end

    diag_2 = 0;
    for i = 1:length(rows)
        diag_2 = diag_2 + board(rows(i),cols(i));
    end

    //Check if there's any queen
    flag_out = ( ~(row_col | diag_1 | diag_2) );
endfunction

//Solution counter
Sol_count = 0;

//"Soltion found" flag
Sol_found = %F;

//Empty board
Board = zeros(Board_size,Board_size);

//Matrix for backtracking
Queens= zeros(Board_size,2);

//Queens counter
N_queens = Board_size;

//Row and column counters
i = 1; j = 1;

//Start counting time
tic();

//Begin search
while i <= Board_size
    while j <= Board_size
        //Availability flag: check position (i,j)
        flag = %F;
        if (0 < i & 0 < j) & (i <= Board_size & j <= Board_size) then
            flag = no_attack(Board_size,Board,[i j]);
        end

        //Reset solution flag
        Sol_found = %F;

        if flag then
            //Put a queen on the board if position is available
            Board(i,j) = 1;

            //Update number of remaining queens
            N_queens = N_queens - 1;

            //Keep track of queens positions
            Queens(Board_size - N_queens,:) = [i j];

            //Jump to next row end of line is reached
            if i+1<=Board_size
                i = i + 1;
            end
            //Start over from the begining of new line
            j = 0;

            //Count and flag a solution if all queens have
            //been placed on the board
            if N_queens == 0 then
                Sol_count = Sol_count + 1;
                Sol_found = %T;
                break
            end
        end

        //Increment column number
        j = j + 1;
    end

    //Increment row number and start from first column
    if ~Sol_found then
        i = i + 1;
        j = 1;

        //Limiting placement of the first queen to the first row
        //Stop searching solutions if columns of first row
        //have been tested
        if i == 2 & j == 1 & sum(Board) == 0  then
            break
        end
    end

    //Backtracking: if (i,j) reaches the and of the board
    //and there are queens left to be placed on it
    if ~Sol_found & i == Board_size + 1 & j == 1 then
        ind = Board_size - N_queens;
        if ind > 0 then
            //Recover last queen's position
            i = Queens(ind,1);
            j = Queens(ind,2);

            //Remove it from the board and from the counter
            Board(i,j) = 0;
            Queens(ind,:) = [0 0];
            N_queens = N_queens + 1;

            //Move to next column
            j = j + 1;
        end
    end
end

//Printing result on console
disp("There are "+string(Sol_count)+" solutions for a "+...
     string(Board_size)+"x"+string(Board_size)+" board.");
//Time elapsed
disp("Time: "+string(toc())+"s.");


 for pow = 2 to 6
    n = 10^pow
    print n, getPi(n)
next

end

function getPi(n)
    incircle = 0
    for throws=0 to n
        scan
        incircle = incircle + (rnd(1)^2+rnd(1)^2 < 1)
    next
    getPi = 4*incircle/throws
end function


10 mode 1:randomize time:defint a-z
20 input "How many samples";n
30 u=n/100+1
40 r=100
50 for i=1 to n
60 if i mod u=0 then locate 1,3:print using "##% done"; i/n*100
70 x=rnd*2*r-r
80 y=rnd*2*r-r
90 if sqr(x*x+y*y)<r then m=m+1
100 next
110 pi2!=4*m/n
120 locate 1,3
130 print m;"points in circle"
140 print "Computed value of pi:"pi2!
150 print "Difference to real value of pi: ";
160 print using "+#.##%"; (pi2!-pi)/pi*100


to square :n
  output :n * :n
end
to trial :r
  output less? sum square random :r square random :r  square :r
end
to sim :n :r
  make "hits 0
  repeat :n [if trial :r [make "hits :hits + 1]]
  output 4 * :hits / :n
end

show sim    1000 10000  ; 3.18
show sim   10000 10000  ; 3.1612
show sim  100000 10000  ; 3.145
show sim 1000000 10000  ; 3.140828


$ include "seed7_05.s7i";

var array integer: board is 8 times 0;
var integer: solutionNum is 0;

const func boolean: safe (in integer: y) is func
  result
    var boolean: safe is TRUE;
  local
    var integer: i is 1;
  begin
    while i < y and safe do
      safe := board[y - i] <> board[y] and
              board[y - i] <> board[y] - i and
              board[y - i] <> board[y] + i;
      incr(i);
    end while;
  end func;

const proc: putBoard is func
  local
    var integer: y is 0;
  begin
    incr(solutionNum);
    writeln;
    writeln("Solution " <& solutionNum);
    for y range 1 to 8 do
      writeln("|_" mult pred(board[y]) <& "|Q" <& "|_" mult (8 - board[y]) <& "|");
    end for;
  end func;

const proc: main is func
  local
    var integer: y is 1;
  begin
    while y >= 1 do
      repeat
        incr(board[y]);
      until board[y] > 8 or safe(y);
      if board[y] <= 8 then
        if y < 8 then
          incr(y);
          board[y] := 0;
        else
          putBoard;
        end if;
      else
        decr(y);
      end if;
    end while;
  end func;


integer iMIN_SAMPLE_POWER = 0;
integer iMAX_SAMPLE_POWER = 6;
default {
	state_entry() {
		llOwnerSay("Estimating Pi ("+(string)PI+")");
		integer iSample = 0;
		for(iSample=iMIN_SAMPLE_POWER ; iSample<=iMAX_SAMPLE_POWER  ; iSample++) {
			integer iInCircle = 0;
			integer x = 0;
			integer iMaxSamples = (integer)llPow(10, iSample);
			for(x=0 ; x<iMaxSamples ; x++) {
				if(llSqrt(llPow(llFrand(2.0)-1.0, 2.0)+llPow(llFrand(2.0)-1.0, 2.0))<1.0) {
					iInCircle++;
				}
			}
			float fPi = ((4.0*iInCircle)/llPow(10, iSample));
			float fError = llFabs(100.0*(PI-fPi)/PI);
			llOwnerSay((string)iSample+": "+(string)iMaxSamples+" = "+(string)fPi+", Error = "+(string)fError+"%");
		}
		llOwnerSay("Done.");
	}
}


function MonteCarlo ( n_throws )
    math.randomseed( os.time() )

    n_inside = 0
    for i = 1, n_throws do
    	if math.random()^2 + math.random()^2 <= 1.0 then
            n_inside = n_inside + 1
    	end
    end

    return 4 * n_inside / n_throws
end

print( MonteCarlo( 10000 ) )
print( MonteCarlo( 100000 ) )
print( MonteCarlo( 1000000 ) )
print( MonteCarlo( 10000000 ) )


MonteCarloPi[samplesize_Integer] := N[4Mean[If[# > 1, 0, 1] & /@ Norm /@ RandomReal[1, {samplesize, 2}]]]


function piEstimate = monteCarloPi(numDarts)

    %The square has a sides of length 2, which means the circle has radius
    %1.

    %Generate a table of random x-y value pairs in the range [0,1] sampled
    %from the uniform distribution for each axis.
    darts = rand(numDarts,2);

    %Any darts that are in the circle will have position vector whose
    %length is less than or equal to 1 squared.
    dartsInside = ( sum(darts.^2,2) <= 1 );

    piEstimate = 4*sum(dartsInside)/numDarts;

end


func N_queens_solution(N = 8) {

    func collision(field, row) {
        for i in (^row) {
            var distance = (field[i] - field[row])
            distance ~~ [0, row-i, i-row] && return true
        }
        return false
    }

    func search(field, row) {
        row == N && return field
        for i in (^N) {
            field[row] = i
            if (!collision(field, row)) {
                return (__FUNC__(field, row+1) || next)
            }
        }
        return []
    }

    for i in (0 .. N>>1) {
        if (var r = search([i], 1)) {
            return r
        }
    }
}

for n in (1..15) {
    say "#{'%2d' % n}: #{N_queens_solution(n) || 'No solution'}"
}


load("distrib");
approx_pi(n):= block(
  [x: random_continuous_uniform(0, 1, n),
   y: random_continuous_uniform(0, 1, n),
   r, cin: 0, listarith: true],
   r: x^2 + y^2,
   for r0 in r do if r0<1 then cin: cin + 1,
   4*cin/n);

float(approx_pi(100));


fn monteCarlo iterations =
(
    radius = 1.0
    pointsInCircle = 0
    for i in 1 to iterations do
    (
        testPoint = [(random -radius radius), (random -radius radius)]
        if length testPoint <= radius then
        (
            pointsInCircle += 1
        )
    )
    4.0 * pointsInCircle / iterations
)


import math, random

randomize()

proc pi(nthrows: float): float =
  var inside = 0.0
  for i in 1..int64(nthrows):
    if hypot(rand(1.0), rand(1.0)) < 1:
      inside += 1
  result = 4 * inside / nthrows

for n in [10e4, 10e6, 10e7, 10e8]:
  echo pi(n)


let get_pi throws =
  let rec helper i count =
    if i = throws then count
    else
      let rand_x = Random.float 2.0 -. 1.0
      and rand_y = Random.float 2.0 -. 1.0 in
      let dist = sqrt (rand_x *. rand_x +. rand_y *. rand_y) in
      if dist < 1.0 then
        helper (i+1) (count+1)
      else
        helper (i+1) count
  in float (4 * helper 0 0) /. float throws


-- MONADIC FUNCTIONS (for list monad) ------------------------------------------

-- Monadic bind for lists is simply ConcatMap
-- which applies a function f directly to each value in the list,
-- and returns the set of results as a concat-flattened list

-- bind :: (a -> [b]) -> [a] -> [b]
on bind(f, xs)
    -- concat :: a -> a -> [a]
    script concat
        on |λ|(a, b)
            a & b
        end |λ|
    end script

    foldl(concat, {}, map(f, xs))
end bind

-- Monadic return/unit/inject for lists: just wraps a value in a list
-- a -> [a]
on unit(a)
    [a]
end unit

-- TEST ------------------------------------------------------------------------
on run
    -- Pythagorean triples drawn from integers in the range [1..n]
    -- {(x, y, z) | x <- [1..n], y <- [x+1..n], z <- [y+1..n], (x^2 + y^2 = z^2)}

    pythagoreanTriples(25)

    --> {{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17},
    --   {9, 12, 15}, {12, 16, 20}, {15, 20, 25}}

end run

-- pythagoreanTriples :: Int -> [(Int, Int, Int)]
on pythagoreanTriples(maxInteger)
    script X
        on |λ|(X)
            script Y
                on |λ|(Y)
                    script Z
                        on |λ|(Z)
                            if X * X + Y * Y = Z * Z then
                                unit([X, Y, Z])
                            else
                                []
                            end if
                        end |λ|
                    end script

                    bind(Z, enumFromTo(1 + Y, maxInteger))
                end |λ|
            end script

            bind(Y, enumFromTo(1 + X, maxInteger))
        end |λ|
    end script

    bind(X, enumFromTo(1, maxInteger))

end pythagoreanTriples

-- GENERIC  FUNCTIONS ---------------------------------------------------------

-- enumFromTo :: Int -> Int -> [Int]
on enumFromTo(m, n)
    if n < m then
        set d to -1
    else
        set d to 1
    end if
    set lst to {}
    repeat with i from m to n by d
        set end of lst to i
    end repeat
    return lst
end enumFromTo

-- foldl :: (a -> b -> a) -> a -> [b] -> a
on foldl(f, startValue, xs)
    tell mReturn(f)
        set v to startValue
        set lng to length of xs
        repeat with i from 1 to lng
            set v to |λ|(v, item i of xs, i, xs)
        end repeat
        return v
    end tell
end foldl

-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
    tell mReturn(f)
        set lng to length of xs
        set lst to {}
        repeat with i from 1 to lng
            set end of lst to |λ|(item i of xs, i, xs)
        end repeat
        return lst
    end tell
end map

-- Lift 2nd class handler function into 1st class script wrapper
-- mReturn :: Handler -> Script
on mReturn(f)
    if class of f is script then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn


* N queens problem
* Set N to the desired number.  The program prints out all solution boards.
	N = 5
	NM1 = N - 1; NP1 = N + 1; NSZ = N * NP1; &STLIMIT = 10 ** 9; &ANCHOR = 1
	DEFINE('SOLVE(B)I')
* This pattern tests if the first queen attacks any of the others:
	TEST = BREAK('Q') 'Q' (ARBNO(LEN(N) '-') LEN(N) 'Q'
+	      | ARBNO(LEN(NP1) '-') LEN(NP1) 'Q'
+	      | ARBNO(LEN(NM1) '-') LEN(NM1) 'Q')
	P = LEN(NM1) . X LEN(1); L = 'Q' DUPL('-',NM1) ' '
	SOLVE()        :(END)
SOLVE	EQ(SIZE(B),NSZ) 	    :S(PRINT)
* Add another row with a queen:
	B = L B
LOOP	I = LT(I,N) I + 1 :F(RETURN)
	B TEST :S(NEXT)
	SOLVE(B)
* Try queen in next square:
NEXT	B P = '-' X :(LOOP)
PRINT	SOLUTION = SOLUTION + 1
	OUTPUT = 'Solution number ' SOLUTION ' is:'
PRTLOOP B LEN(NP1) . OUTPUT = :S(PRTLOOP)F(RETURN)
END


function p = montepi(samples)
  in_circle = 0;
  for samp = 1:samples
    v = [ unifrnd(-1,1), unifrnd(-1,1) ];
    if ( v*v.' <= 1.0 )
      in_circle++;
    endif
  endfor
  p = 4*in_circle/samples;
endfunction

l = 1e4;
while (l < 1e7)
  disp(montepi(l));
  l *= 10;
endwhile


Program MonteCarlo(output);

uses
  Math;

function MC_Pi(expo: integer): real;
  var
    x, y: real;
    i, hits, samples: longint;
  begin
    samples := 10**expo;
    hits := 0;
    randomize;
    for i := 1 to samples do
    begin
      x := random;
      y := random;
      if sqrt(x*x + y*y) < 1.0 then
        inc(hits);
    end;
    MC_Pi := 4.0 * hits / samples;
  end;

var
  i: integer;
begin
  for i := 4 to 8 do
    writeln (10**i, ' samples give ', MC_Pi(i):7:5, ' as pi.');
end.


#include <iostream>
#include <vector>

using namespace std;

// std::vector can be a list monad.  Use the >> operator as the bind function
template <typename T>
auto operator>>(const vector<T>& monad, auto f)
{
    // Declare a vector of the same type that the function f returns
    vector<remove_reference_t<decltype(f(monad.front()).front())>> result;
    for(auto& item : monad)
    {
        // Apply the function f to each item in the monad. f will return a
        // new list monad containing 0 or more items.
        const auto r = f(item);
        // Concatenate the results of f with previous results
        result.insert(result.end(), begin(r), end(r));
    }

    return result;
}

// The Pure function returns a vector containing one item, t
auto Pure(auto t)
{
    return vector{t};
}

// A function to double items in the list monad
auto Double(int i)
{
    return Pure(2 * i);
}

// A function to increment items
auto Increment(int i)
{
    return Pure(i + 1);
}

// A function to convert items to a string
auto NiceNumber(int i)
{
    return Pure(to_string(i) + " is a nice number\n");
}

// A function to map an item to a sequence ending at max value
// for example: 497 -> {497, 498, 499, 500}
auto UpperSequence = [](auto startingVal)
{
    const int MaxValue = 500;
    vector<decltype(startingVal)> sequence;
    while(startingVal <= MaxValue)
        sequence.push_back(startingVal++);
    return sequence;
};

// Print contents of a vector
void PrintVector(const auto& vec)
{
    cout << " ";
    for(auto value : vec)
    {
        cout << value << " ";
    }
    cout << "\n";
}

// Print the Pythagorean triples
void PrintTriples(const auto& vec)
{
    cout << "Pythagorean triples:\n";
    for(auto it = vec.begin(); it != vec.end();)
    {
        auto x = *it++;
        auto y = *it++;
        auto z = *it++;

        cout << x << ", " << y << ", " << z << "\n";
    }
    cout << "\n";
}

int main()
{
    // Apply Increment, Double, and NiceNumber to {2, 3, 4} using the monadic bind
    auto listMonad =
        vector<int> {2, 3, 4} >>
        Increment >>
        Double >>
        NiceNumber;

    PrintVector(listMonad);

    // Find Pythagorean triples using the list monad.  The 'x' monad list goes
    // from 1 to the max; the 'y' goes from the current 'x' to the max; and 'z'
    // goes from the current 'y' to the max.  The last bind returns the triplet
    // if it is Pythagorean, otherwise it returns an empty list monad.
    auto pythagoreanTriples = UpperSequence(1) >>
        [](int x){return UpperSequence(x) >>
        [x](int y){return UpperSequence(y) >>
        [x, y](int z){return (x*x + y*y == z*z) ? vector{x, y, z} : vector<int>{};};};};

    PrintTriples(pythagoreanTriples);
}


let print_table = function (pos) {
	pos.foreach(function (_, i) {
		stdout.printf("  %c", 'a' + i);
	});

	stdout.write("\n");

	pos.foreach(function (col, row) {
		stdout.printf("%d", row + 1);
		stdout.printf("%s #\n", range(col).reduce("", function (s, t) {
			return s .. "   ";
		}));
	});

	stdout.write("\n\n");
};

let threatens = function (row_a, col_a, row_b, col_b) {
	return row_a == row_b
	    or col_a == col_b
	    or abs(row_a - row_b) == abs(col_a - col_b);
};

let good = function(pos, end_idx) {
	return pos.all(function (col_a, row_a) {
		return range(row_a + 1, end_idx).all(function (row_b) {
			let col_b = pos[row_b];
			return not threatens(row_a, col_a, row_b, col_b);
		});
	});
};

// Returns number of solutions
let n_queens = function (pos, index) {
	if index >= pos.length {
		if good(pos, index) {
			print_table(pos);
			return 1;
		}

		return 0;
	}

	if not good(pos, index) {
		return 0;
	}

	return pos.map(function (_, col) {
		pos[index] = col;
		return n_queens(pos, index + 1);
	}).reduce(0, function (a, b) { return a + b; });
};

stdout.printf("%d solutions\n", n_queens(range(8), 0));


sub pi {
  my $nthrows = shift;
  my $inside = 0;
  foreach (1 .. $nthrows) {
    my $x = rand() * 2 - 1;
    my $y = rand() * 2 - 1;
    if (sqrt($x*$x + $y*$y) < 1) {
      $inside++;
    }
  }
  return 4 * $inside / $nthrows;
}

printf "%9d: %07f\n", $_, pi($_) for 10**4, 10**6;


with javascript_semantics
integer N = 100
for i=1 to 6 do
    integer inside = 0
    for n=1 to N do
        integer x = rand(N),
                y = rand(N)
        inside += (x*x+y*y<N*N)
    end for
    pp({N,4*inside/N})
    N *= 10
end for


(defn bind [coll f] (apply vector (mapcat f coll)))
(defn unit [val] (vector val))

(defn doubler [n] [(* 2 n)])   ; takes a number and returns a List number
(def vecstr (comp vector str)) ; takes a number and returns a List string

(bind (bind (vector 3 4 5) doubler) vecstr) ; evaluates to ["6" "8" "10"]
(-> [3 4 5]
  (bind doubler)
  (bind vecstr)) ; also evaluates to ["6" "8" "10"]


program List_monad;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

type
  TmList = record
    Value: TArray<Integer>;
    function ToString: string;
    function Bind(f: TFunc<TArray<Integer>, TmList>): TmList;
  end;

function Create(aValue: TArray<Integer>): TmList;
begin
  Result.Value := copy(aValue, 0, length(aValue));
end;

{ TmList }

function TmList.Bind(f: TFunc<TArray<Integer>, TmList>): TmList;
begin
  Result := f(self.Value);
end;

function TmList.ToString: string;
var
  i: Integer;
begin
  Result := '[ ';
  for i := 0 to length(value) - 1 do
  begin
    if i > 0 then
      Result := Result + ', ';
    Result := Result + value[i].toString;
  end;
  Result := Result + ']';
end;

function Increment(aValue: TArray<Integer>): TmList;
var
  i: integer;
begin
  SetLength(Result.Value, length(aValue));
  for i := 0 to High(aValue) do
    Result.Value[i] := aValue[i] + 1;
end;

function Double(aValue: TArray<Integer>): TmList;
var
  i: integer;
begin
  SetLength(Result.Value, length(aValue));
  for i := 0 to High(aValue) do
    Result.Value[i] := aValue[i] * 2;
end;

var
  ml1, ml2: TmList;

begin
  ml1 := Create([3, 4, 5]);
  ml2 := ml1.Bind(Increment).Bind(double);
  Writeln(ml1.ToString, ' -> ', ml2.ToString);
  readln;
end.


WITH RECURSIVE
  positions(i) AS (
    VALUES(0)
    UNION SELECT ALL
    i+1 FROM positions WHERE i < 63
    ),
  solutions(board, n_queens) AS (
    SELECT '----------------------------------------------------------------', CAST(0 AS BIGINT)
      FROM positions
    UNION
    SELECT
      substr(board, 1, i) || '*' || substr(board, i+2),n_queens + 1 AS n_queens
      FROM positions AS ps, solutions
    WHERE n_queens < 8
      AND substr(board,1,i) != '*'
      AND NOT EXISTS (
        SELECT 1 FROM positions WHERE
          substr(board,i+1,1) = '*' AND
            (
                i % 8 = ps.i %8 OR
                CAST(i / 8 AS INT) = CAST(ps.i / 8 AS INT) OR
                CAST(i / 8 AS INT) + (i % 8) = CAST(ps.i / 8 AS INT) + (ps.i % 8) OR
                CAST(i / 8 AS INT) - (i % 8) = CAST(ps.i / 8 AS INT) - (ps.i % 8)
            )
        LIMIT 1
        )
   ORDER BY n_queens DESC -- remove this when using Postgres (they don't support ORDER BY in CTEs)
  )
SELECT board,n_queens FROM solutions WHERE n_queens = 8;


<?
$loop = 1000000; # loop to 1,000,000
$count = 0;
for ($i=0; $i<$loop; $i++) {
  $x = rand() / getrandmax();
  $y = rand() / getrandmax();
  if(($x*$x) + ($y*$y)<=1) $count++;
}
echo "loop=".number_format($loop).", count=".number_format($count).", pi=".($count/$loop*4);
?>


sim1(N, F) = C =>
  C = 0,
  I = 0,
  while (I <= N)
    C := C + apply(F),
    I := I + 1
  end.


(de carloPi (Scl)
   (let (Dim (** 10 Scl)  Dim2 (* Dim Dim)  Pi 0)
      (do (* 4 Dim)
         (let (X (rand 0 Dim)  Y (rand 0 Dim))
            (when (>= Dim2 (+ (* X X) (* Y Y)))
               (inc 'Pi) ) ) )
      (format Pi Scl) ) )

(for N 6
   (prinl (carloPi N)) )


;; -> and ->> are the pipeline operators
;; (-> x f g h) = (h (g ( f x)))
;; (->> x f (g a) h) = (h (g a ( f x)))

(define (List.unit elem)  (append '(List) elem))
(define (List.bind xs f)  (List.unit (->> xs rest (map f)  (map rest) (apply append))))
(define (List.lift f)     (lambda(elem) (List.unit (f elem))))

(define List.square  (List.lift (lambda(x) (*  x x))))
(define List.cube    (List.lift (lambda(x) (* x x x))))
(define List.tostr   (List.lift number->string))

;; composition

(-> '(List 1 -2 3 -5) (List.bind List.cube) (List.bind List.tostr))
    → (List "1" "-8" "27" "-125")
;; or
(-> '(1 -2 3 -5) List.unit (List.bind List.cube) (List.bind List.tostr))
     → (List "1" "-8" "27" "-125")


type ListMonad() =
   member o.Bind(  (m:'a list), (f: 'a -> 'b list) ) = List.concat( List.map f m )
   member o.Return(x) = [x]
   member o.Zero()    = []

let list = ListMonad()

let pyth_triples n = list { let! x = [1..n]
                            let! y = [x..n]
                            let! z = [y..n]
                            if x*x + y*y = z*z then return (x,y,z) }

printf "%A" (pyth_triples 100)


USING: kernel math monads prettyprint ;
FROM: monads => do ;

{ 3 4 5 }
>>= [ 1 + array-monad return ] swap call
>>= [ 2 * array-monad return ] swap call .


Dim As Integer m1(1 To 3) = {3,4,5}
Dim As String m2 = "["
Dim As Integer x, y ,z
For x = 1 To Ubound(m1)
    y = m1(x) + 1
    z = y * 2
    m2 &= Str(z) & ", "
Next x
m2 = Left(m2, Len(m2) -2)
m2 &= "]"
Print m2
Sleep


-- A column of a matrix.
CREATE TYPE INTEGER_ARRAY AS INTEGER ARRAY[]@
-- The whole matrix of any size.
CREATE TYPE INTEGER_MATRIX AS INTEGER_ARRAY ARRAY[]@

/**
 * Retrieves the value from a matrix at a specific position.
 *
 * IN X: Row number.
 * IN Y: Column number.
 * IN M: Matrix.
 * RETURN the integer value at that position.
 */
CREATE OR REPLACE FUNCTION GET_INTEGER_VALUE(
  IN X SMALLINT,
  IN Y SMALLINT,
  IN M INTEGER_MATRIX)
RETURNS INTEGER
F_GET_INTEGER_VALUE: BEGIN
  DECLARE A INTEGER_ARRAY;
  DECLARE RET INTEGER;

  SET A = M[X];
  SET RET = A[Y];
  RETURN RET;
END F_GET_INTEGER_VALUE
@

/**
 * Establishes the given value at a specific position in the matrix.
 *
 * IN X: Row number.
 * IN Y: Column number.
 * INOUT M: Matrix.
 * IN VAL: Value to set in the matrix.
 */
CREATE OR REPLACE PROCEDURE SET_INTEGER_VALUE(
  IN X SMALLINT,
  IN Y SMALLINT,
  INOUT M INTEGER_MATRIX,
  IN VAL INTEGER)
P_SET_INTEGER_VALUE: BEGIN
  DECLARE A INTEGER_ARRAY;

  SET A = M[X];
  SET A[Y] = VAL;
  SET M[X] = A;
END P_SET_INTEGER_VALUE
@

/**
 * Initializes the matriz at a given size with the same value in all positions.
 *
 * INOUT M: Matrix.
 * IN X: Number of rows.
 * IN Y: Number of columns per row.
 * IN VAL: Value to set in the matrix.
 */
CREATE OR REPLACE PROCEDURE INIT_INTEGER_MATRIX(
  INOUT M INTEGER_MATRIX,
  IN X SMALLINT,
  IN Y SMALLINT,
  IN VAL INTEGER)
P_INIT_INTEGER_MATRIX: BEGIN
  DECLARE I SMALLINT DEFAULT 1;
  DECLARE J SMALLINT;
  DECLARE A INTEGER_ARRAY;

  WHILE (I <= X) DO
   SET A = ARRAY[];
   SET J = 1;
   WHILE (J <= Y) DO
    SET A[J] = VAL;
    SET J = J + 1;
   END WHILE;
   SET M[I] = A;
   SET I = I + 1;
  END WHILE;
END P_INIT_INTEGER_MATRIX
@

/**
 * Prints the content of the matrix to the standard output.
 *
 * INOUT M: Matrix.
 */
CREATE OR REPLACE PROCEDURE PRINT_INTEGER_MATRIX(
  IN M INTEGER_MATRIX)
P_PRINT_INTEGER_MATRIX: BEGIN
  DECLARE I SMALLINT DEFAULT 1;
  DECLARE J SMALLINT;
  DECLARE X SMALLINT;
  DECLARE Y SMALLINT;
  DECLARE VAL INTEGER;
  DECLARE A INTEGER_ARRAY;
  DECLARE RET VARCHAR(256);

  SET X = CARDINALITY(M);
  CALL DBMS_OUTPUT.PUT_LINE('>>>>>');
  WHILE (I <= X) DO
   SET A = M[I];
   SET RET = '[';
   SET Y = CARDINALITY(A);
   SET J = 1;
   WHILE (J <= Y) DO
    SET VAL = A[J];
    SET RET = RET || VAL;
    SET J = J + 1;
    IF (J <= Y) THEN
     SET RET = RET || ',';
    END IF;
   END WHILE;
   SET RET = RET || ']';
   CALL DBMS_OUTPUT.PUT_LINE(RET);
   SET I = I + 1;
  END WHILE;
  CALL DBMS_OUTPUT.PUT_LINE('<<<<<');
END P_PRINT_INTEGER_MATRIX
@

/**
 * Checks if a queen is safe in the given position.
 *
 * IN M: Matrix representing the chessboard.
 * IN ROW: Row of the queen.
 * IN COL: Column in the row for the queen.
 * IN SIZE: Size of the chessboard (max row, max col).
 * RETURNS true if the position is safe.
 */
CREATE OR REPLACE FUNCTION IS_SAFE(
  IN M INTEGER_MATRIX,
  IN ROW SMALLINT,
  IN COL SMALLINT,
  IN SIZE SMALLINT)
 MODIFIES SQL DATA
 RETURNS BOOLEAN
 F_IS_SAFE: BEGIN
  DECLARE I SMALLINT;
  DECLARE J SMALLINT;
  DECLARE VAL INTEGER;

  -- Debug purposes.
  --CALL SET_INTEGER_VALUE(ROW, COL, M, -1);
  --CALL PRINT_INTEGER_MATRIX(M);
  --CALL SET_INTEGER_VALUE(ROW, COL, M, 0);

  SET I = 1;
  WHILE (I <= COL) DO
   SET VAL = GET_INTEGER_VALUE(ROW, I, M);
   IF (VAL = 1) THEN
    RETURN FALSE;
   END IF;
   SET I = I + 1;
  END WHILE;

  SET I = ROW;
  SET J = COL;
  WHILE (I >= 1 AND J >= 1) DO
   SET VAL = GET_INTEGER_VALUE(I, J, M);
   IF (VAL = 1) THEN
    CALL SET_INTEGER_VALUE(ROW, COL, M, 0);
    RETURN FALSE;
   END IF;
   SET I = I - 1;
   SET J = J - 1;
  END WHILE;

  SET I = ROW;
  SET J = COL;
  WHILE (J >= 1 AND I <= SIZE) DO
   SET VAL = GET_INTEGER_VALUE(I, J, M);
   IF (VAL = 1) THEN
    RETURN FALSE;
   END IF;
   SET I = I + 1;
   SET J = J - 1;
  END WHILE;

  RETURN TRUE;
 END F_IS_SAFE
@

/**
 * Dummy procedure for the recurssion.
 *
 * IN SIZE: Size of the chessboard (max row, max col).
 * IN COL: Column to analyse.
 * OUT RET: True if it was possible to put all queens
 */
CREATE OR REPLACE PROCEDURE SOLVE_N_QUEENS(
  INOUT M INTEGER_MATRIX,
  IN SIZE SMALLINT,
  IN COL SMALLINT,
  OUT RET BOOLEAN)
 P_SOLVE_N_QUEENS: BEGIN
 END P_SOLVE_N_QUEENS
@

/**
 * Solves the n-queens algoritm.
 *
 * IN SIZE: Size of the chessboard (max row, max col).
 * IN COL: Column to analyse.
 * OUT RET: True if it was possible to put all queens
 */
CREATE OR REPLACE PROCEDURE SOLVE_N_QUEENS(
  INOUT M INTEGER_MATRIX,
  IN SIZE SMALLINT,
  IN COL SMALLINT,
  OUT RET BOOLEAN)
 MODIFIES SQL DATA
 P_SOLVE_N_QUEENS: BEGIN
  DECLARE I SMALLINT;
  DECLARE SAFE BOOLEAN;
  DECLARE SOLVED BOOLEAN;

  -- Debug purposes.
  --CALL PRINT_INTEGER_MATRIX(M);
  SET RET = FALSE;
  IF (COL > SIZE) THEN
   SET RET = TRUE;
  ELSE
   SET I = 1;
   WHILE (I <= SIZE AND NOT RET) DO
    SET SAFE = IS_SAFE(M, I, COL, SIZE);
    IF (SAFE) THEN
     CALL SET_INTEGER_VALUE(I, COL, M, 1);
     CALL SOLVE_N_QUEENS(M, SIZE, COL + 1, SOLVED);
     IF (SOLVED) THEN
      SET RET = TRUE;
     ELSE
      CALL SET_INTEGER_VALUE(I, COL, M, 0); -- Backtrack.
     END IF;

    END IF;

    SET I = I + 1;
   END WHILE;

  END IF;
 END P_SOLVE_N_QUEENS
@

/**
 * Main procedure to solve the n-queen algoritm.
 *
 * IN SIZE: Size of the chessboard. The bigger it is, the more time it takes.
 */
CREATE OR REPLACE PROCEDURE N_QUEENS(
  IN SIZE SMALLINT)
 P_N_QUEENS: BEGIN
  DECLARE M INTEGER_MATRIX;
  DECLARE SOL BOOLEAN DEFAULT FALSE;

  CALL INIT_INTEGER_MATRIX(M, SIZE, SIZE, 0);

  CALL SOLVE_N_QUEENS(M, SIZE, 1, SOL);
  IF (SOL = TRUE) THEN
   CALL PRINT_INTEGER_MATRIX(M);
  ELSE
   CALL DBMS_OUTPUT.PUT_LINE('Solution does not exist.');
  END IF;

 END P_N_QUEENS
@

--#SET TERMINATOR ;

-- Activates the standard output for the current session.
SET SERVEROUTPUT ON;

CALL N_QUEENS(4);

CALL N_QUEENS(8);

CALL N_QUEENS(16);


function Get-Pi ($Iterations = 10000) {
    $InCircle = 0
    for ($i = 0; $i -lt $Iterations; $i++) {
        $x = Get-Random 1.0
        $y = Get-Random 1.0
        if ([Math]::Sqrt($x * $x + $y * $y) -le 1) {
            $InCircle++
        }
    }
    $Pi = [decimal] $InCircle / $Iterations * 4
    $RealPi = [decimal] "3.141592653589793238462643383280"
    $Diff = [Math]::Abs(($Pi - $RealPi) / $RealPi * 100)
    New-Object PSObject `
        | Add-Member -PassThru NoteProperty Iterations $Iterations `
        | Add-Member -PassThru NoteProperty Pi $Pi `
        | Add-Member -PassThru NoteProperty "% Difference" $Diff
}


OpenConsole()

Procedure.d MonteCarloPi(throws.d)
	inCircle.d = 0
		For i = 1 To throws.d
			randX.d = (Random(2147483647)/2147483647)*2-1
			randY.d = (Random(2147483647)/2147483647)*2-1
			dist.d  = Sqr(randX.d*randX.d + randY.d*randY.d)
			If dist.d < 1
				inCircle = inCircle + 1
			EndIf
		Next i
	pi.d = (4 * inCircle / throws.d)
	ProcedureReturn pi.d

EndProcedure

PrintN ("'built-in' #Pi         = " + StrD(#PI,20))
PrintN ("MonteCarloPi(10000)    = " + StrD(MonteCarloPi(10000),20))
PrintN ("MonteCarloPi(100000)   = " + StrD(MonteCarloPi(100000),20))
PrintN ("MonteCarloPi(1000000)  = " + StrD(MonteCarloPi(1000000),20))
PrintN ("MonteCarloPi(10000000) = " + StrD(MonteCarloPi(10000000),20))

PrintN("Press any key"): Repeat: Until Inkey() <> ""


package main

import "fmt"

type mlist struct{ value []int }

func (m mlist) bind(f func(lst []int) mlist) mlist {
    return f(m.value)
}

func unit(lst []int) mlist {
    return mlist{lst}
}

func increment(lst []int) mlist {
    lst2 := make([]int, len(lst))
    for i, v := range lst {
        lst2[i] = v + 1
    }
    return unit(lst2)
}

func double(lst []int) mlist {
    lst2 := make([]int, len(lst))
    for i, v := range lst {
        lst2[i] = 2 * v
    }
    return unit(lst2)
}

func main() {
    ml1 := unit([]int{3, 4, 5})
    ml2 := ml1.bind(increment).bind(double)
    fmt.Printf("%v -> %v\n", ml1.value, ml2.value)
}


bind=: S:0
unit=: boxopen

m_num=: unit
m_str=: [email protected]":


(*
 * val threat : (int * int) -> (int * int) -> bool
 * Returns true iff the queens at the given positions threaten each other
 *)
fun threat (x, y) (x', y') =
  x = x' orelse y = y' orelse abs(x - x') = abs(y - y');

(*
 * val conflict : (int * int) -> (int * int) list -> bool
 * Returns true if there exists a conflict with the position and the list of queens.
 *)
fun conflict pos = List.exists (threat pos);

(*
 * val addqueen : (int * int * (int * int) list * (unit -> (int * int) list option)) -> (int * int) list option
 * Returns either NONE in the case that no solution exists or SOME(l) where l is a list of positions making up the solution.
 *)
fun addqueen(i, n, qs, fc) =
  let
    fun try j =
      if j > n then fc()
      else if (conflict (i, j) qs) then try (j + 1)
      else if i = n then SOME((i, j)::qs)
      else addqueen(i + 1, n, (i,j)::qs, fn() => try (j + 1))
  in
    try 1
  end;

(*
 * val queens : int -> (int * int) list option
 * Given the board dimension n, returns a solution for the n-queens problem.
 *)
fun queens(n) = addqueen(1, n, [], fn () => NONE);

(* SOME [(8,4),(7,2),(6,7),(5,3),(4,6),(3,8),(2,5),(1,1)] *)
queens(8);

(* NONE *)
queens(2);


>>> import random, math
>>> throws = 1000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1520000000000001
>>> throws = 1000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1396359999999999
>>> throws = 100000000
>>> 4.0 * sum(math.hypot(*[random.random()*2-1
	                 for q in [0,1]]) < 1
              for p in xrange(throws)) / float(throws)
3.1415666400000002


  [ $ "bigrat.qky" loadfile ] now!

  [ [ 64 bit ] constant
    dup random dup *
    over random dup * +
    swap dup * < ]            is hit    (   --> b )

  [ 0 swap times
      [ hit if 1+ ] ]         is sims   ( n --> n )

  [ dup echo say " trials "
    dup sims 4 *
    swap 20 point$ echo$ cr ] is trials ( n -->   )

' [ 10 100 1000 10000 100000 1000000 ] witheach trials


# nice but not suitable for big samples!
monteCarloPi <- function(samples) {
  x <- runif(samples, -1, 1) # for big samples, you need a lot of memory!
  y <- runif(samples, -1, 1)
  l <- sqrt(x*x + y*y)
  return(4*sum(l<=1)/samples)
}

# this second function changes the samples number to be
# multiple of group parameter (default 100).
monteCarlo2Pi <- function(samples, group=100) {
  lim <- ceiling(samples/group)
  olim <- lim
  c <- 0
  while(lim > 0) {
    x <- runif(group, -1, 1)
    y <- runif(group, -1, 1)
    l <- sqrt(x*x + y*y)
    c <- c + sum(l <= 1)
    lim <- lim - 1
  }
  return(4*c/(olim*group))
}

print(monteCarloPi(1e4))
print(monteCarloPi(1e5))
print(monteCarlo2Pi(1e7))


Array.prototype.bind = function (func) {
  return this.map(func).reduce(function (acc, a) { return acc.concat(a); });
}

Array.unit = function (elem) {
  return [elem];
}

Array.lift = function (func) {
  return function (elem) { return Array.unit(func(elem)); };
}

inc = function (n) { return n + 1; }
doub = function (n) { return 2 * n; }
listy_inc = Array.lift(inc);
listy_doub = Array.lift(doub);

[3,4,5].bind(listy_inc).bind(listy_doub); // [8, 10, 12]


julia> unit(v) = [v...]
unit (generic function with 1 method)

julia> import Base.bind

julia> bind(v, f) = f.(v)
bind (generic function with 5 methods)

julia> f1(x) = x + 1
f1 (generic function with 1 method)

julia> f2(x) = 2x
f2 (generic function with 1 method)

julia> bind(bind(unit([2, 3, 4]), f1), f2)
3-element Array{Int64,1}:
  6
  8
 10

julia> unit([2, 3, 4]) .|> f1 .|> f2
3-element Array{Int64,1}:
  6
  8
 10


// version 1.2.10

class MList<T : Any> private constructor(val value: List<T>) {
    fun <U : Any> bind(f: (List<T>) -> MList<U>) = f(this.value)

    companion object {
        fun <T : Any> unit(lt: List<T>) = MList<T>(lt)
    }
}

fun doubler(li: List<Int>) = MList.unit(li.map { 2 * it } )

fun letters(li: List<Int>) = MList.unit(li.map { "${('@' + it)}".repeat(it) } )

fun main(args: Array<String>) {
    val iv = MList.unit(listOf(2, 3, 4))
    val fv = iv.bind(::doubler).bind(::letters)
    println(fv.value)
}


#lang racket

(define (in-unit-circle? x y) (<= (sqrt (+ (sqr x) (sqr y))) 1))
;; point in ([-1,1], [-1,1])
(define (random-point-in-2x2-square) (values (* 2 (- (random) 1/2)) (* 2 (- (random) 1/2))))

;; Area of circle is (pi r^2). r is 1, area of circle is pi
;; Area of square is 2^2 = 4
;; There is a pi/4 chance of landing in circle
;; .: pi = 4*(proportion passed) = 4*(passed/samples)
(define (passed:samples->pi passed samples) (* 4 (/ passed samples)))

;; generic kind of monte-carlo simulation
(define (monte-carlo run-length report-frequency
                     sample-generator pass?
                     interpret-result)
  (let inner ((samples 0) (passed 0) (cnt report-frequency))
    (cond
      [(= samples run-length) (interpret-result passed samples)]
      [(zero? cnt) ; intermediate report
       (printf "~a samples of ~a: ~a passed -> ~a~%"
               samples run-length passed (interpret-result passed samples))
       (inner samples passed report-frequency)]
      [else
       (inner (add1 samples)
              (if (call-with-values sample-generator pass?)
                  (add1 passed) passed) (sub1 cnt))])))

;; (monte-carlo ...) gives an "exact" result... which will be a fraction.
;; to see how it looks as a decimal we can exact->inexact it
(let ((mc (monte-carlo 10000000 1000000 random-point-in-2x2-square in-unit-circle? passed:samples->pi)))
  (printf "exact = ~a~%inexact = ~a~%(pi - guess) = ~a~%" mc (exact->inexact mc) (- pi mc)))


my @random_distances = ([+] rand**2 xx 2) xx *;

sub approximate_pi(Int $n) {
    4 * @random_distances[^$n].grep(* < 1) / $n
}

say "Monte-Carlo π approximation:";
say "$_ iterations:  ", approximate_pi $_
    for 100, 1_000, 10_000;


/*REXX program computes and displays the value of  pi÷4  using the Monte Carlo algorithm*/
numeric digits 20                                /*use 20 decimal digits to handle args.*/
parse arg times chunk digs r? .                  /*does user want a specific number?    */
if times=='' | times==","  then times=   5e12    /*five trillion should do it, hopefully*/
if chunk=='' | chunk==","  then chunk= 100000    /*perform Monte Carlo in  100k  chunks.*/
if digs =='' |  digs==","  then  digs=     99    /*indicates to use length of  PI - 1.  */
if datatype(r?, 'W')       then call random ,,r? /*Is there a random seed?  Then use it.*/
                                                 /* [↓]  pi meant to line─up with a SAY.*/
           pi= 3.141592653589793238462643383279502884197169399375105820974944592307816406
pi= strip( left(pi, digs + length(.) ) )         /*obtain length of pi to what's wanted.*/
numeric digits length(pi) - 1                    /*define decimal digits as length PI -1*/
say '                    1         2         3         4         5         6         7   '
say 'scale:    1·234567890123456789012345678901234567890123456789012345678901234567890123'
say                                              /* [↑]  a two─line scale for showing pi*/
say 'true pi= '       pi"+"                      /*we might as well brag about true  pi.*/
say                                              /*display a blank line for separation. */
limit   = 10000 - 1                              /*REXX random generates only integers. */
limitSq = limit **2                              /*··· so, instead of one, use limit**2.*/
accuracy= 0                                      /*accuracy of Monte Carlo pi  (so far).*/
@reps= 'repetitions:  Monte Carlo  pi  is'       /*a handy─dandy short literal for a SAY*/
!= 0                                             /*!:  is the accuracy of pi  (so far). */
       do j=1  for times % chunk
                     do chunk                    /*do Monte Carlo, one chunk at─a─time. */
                     if random(, limit)**2 + random(, limit)**2 <= limitSq   then != ! + 1
                     end   /*chunk*/
       reps= chunk * j                           /*calculate the number of repetitions. */
       _= compare(4*! / reps, pi)                /*compare apples and  ···  crabapples. */
       if _<=accuracy  then iterate              /*Not better accuracy?  Keep truckin'. */
       say right(commas(reps), 20) @reps  'accurate to'  _-1  "places."  /*─1≡dec. point*/
       accuracy= _                               /*use this accuracy for next baseline. */
       end   /*j*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: procedure; arg _; do k=length(_)-3  to 1  by -3; _=insert(',',_,k); end;  return _


import math,sequtils,sugar,strformat
func root(x:float):seq[float] = @[sqrt(x),-sqrt(x)]
func asin(x:float):seq[float] = @[arcsin(x),arcsin(x)+TAU,arcsin(x)-TAU]
func format(x:float):seq[string] = @[&"{x:.2f}"]

#'bind' is a nim keyword, how about an infix operator instead
#our bind is the standard map+cat
func `-->`[T,U](input: openArray[T],f: T->seq[U]):seq[U] =
  input.map(f).concat

echo [0.5] --> root --> asin --> format


use strict;
use feature 'say';
use Data::Monad::List;

# Cartesian product to 'count' in binary
my @cartesian = [(
    list_flat_map_multi { scalar_list(join '', @_) }
        scalar_list(0..1),
        scalar_list(0..1),
        scalar_list(0..1)
)->scalars];
say join "\n", @{shift @cartesian};

say '';

# Pythagorean triples
my @triples = [(
    list_flat_map_multi { scalar_list(
            { $_[0] < $_[1] && $_[0]**2+$_[1]**2 == $_[2]**2 ? join(',',@_) : () }
        ) }
        scalar_list(1..10),
        scalar_list(1..10),
        scalar_list(1..10)
)->scalars];

for (@{shift @triples}) {
    say keys %$_ if keys %$_;
}


function bindf(sequence m, integer f)
    return f(m)
end function

function unit(sequence m)
    return m
end function

function increment(sequence l)
    return unit(sq_add(l,1))
end function

function double(sequence l)
    return unit(sq_mul(l,2))
end function

sequence m1 = unit({3, 4, 5}),
         m2 = bindf(bindf(m1,increment),double)
printf(1,"%v -> %v\n", {m1, m2})


	let maxn = 31

	func nq(n: Int) -> Int {
	    var cols = Array(repeating: 0, count: maxn)
	    var diagl = Array(repeating: 0, count: maxn)
	    var diagr = Array(repeating: 0, count: maxn)
	    var posibs = Array(repeating: 0, count: maxn)
	    var num = 0
	    for q0 in 0...n-3 {
		for q1 in q0+2...n-1 {
		    let bit0: Int = 1<<q0
		    let bit1: Int = 1<<q1
		    var d: Int = 0
		    cols[0] = bit0 | bit1 | (-1<<n)
		    diagl[0] = (bit0<<1|bit1)<<1
		    diagr[0] = (bit0>>1|bit1)>>1

		    var posib: Int = ~(cols[0] | diagl[0] | diagr[0])

		    while (d >= 0) {
			while(posib != 0) {
			    let bit: Int = posib & -posib
			    let ncols: Int = cols[d] | bit
			    let ndiagl: Int = (diagl[d] | bit) << 1;
			    let ndiagr: Int = (diagr[d] | bit) >> 1;
			    let nposib: Int = ~(ncols | ndiagl | ndiagr);
			    posib^=bit
			    num += (ncols == -1 ? 1 : 0)
			    if (nposib != 0){
				if(posib != 0) {
				    posibs[d] = posib
				    d += 1
				}
				cols[d] = ncols
				diagl[d] = ndiagl
				diagr[d] = ndiagr
				posib = nposib
			    }
			}
			d -= 1
			posib = d<0 ? n : posibs[d]

		    }
		}

	    }
	    return num*2
	}
	if(CommandLine.arguments.count == 2) {

	    let board_size: Int = Int(CommandLine.arguments[1])!
	    print ("Number of solutions for board size \(board_size) is: \(nq(n:board_size))")

	} else {
	    print("Usage: 8q <n>")
	}


decimals(8)
see "monteCarlo(1000) = " + monteCarlo(1000) + nl
see "monteCarlo(10000) = " + monteCarlo(10000) + nl
see "monteCarlo(100000) = " + monteCarlo(100000) + nl

func monteCarlo t
     n=0
     for i = 1 to t
         if sqrt(pow(random(1),2) + pow(random(1),2)) <= 1 n += 1 ok
     next
     t = (4 * n) / t
     return t


def approx_pi(throws)
  times_inside = throws.times.count {Math.hypot(rand, rand) <= 1.0}
  4.0 * times_inside / throws
end

[1000, 10_000, 100_000, 1_000_000, 10_000_000].each do |n|
   puts "%8d samples: PI = %s" % [n, approx_pi(n)]
end


extern crate rand;

use rand::Rng;
use std::f64::consts::PI;

// `(f32, f32)` would be faster for some RNGs (including `rand::thread_rng` on 32-bit platforms
// and `rand::weak_rng` as of rand v0.4) as `next_u64` combines two `next_u32`s if not natively
// supported by the RNG.  It would less accurate however.
fn is_inside_circle((x, y): (f64, f64)) -> bool {
    x * x + y * y <= 1.0
}

fn simulate<R: Rng>(rng: &mut R, samples: usize) -> f64 {
    let mut count = 0;
    for _ in 0..samples {
        if is_inside_circle(rng.gen()) {
            count += 1;
        }
    }
    (count as f64) / (samples as f64)
}

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

    println!("Real pi: {}", PI);

    for samples in (3..9).map(|e| 10_usize.pow(e)) {
        let estimate = 4.0 * simulate(&mut rng, samples);
        let deviation = 100.0 * (1.0 - estimate / PI).abs();
        println!("{:9}: {:<11} dev: {:.5}%", samples, estimate, deviation);
    }
}


object MonteCarlo {
  private val random = new scala.util.Random

  /** Returns a random number between -1 and 1 */
  def nextThrow: Double = (random.nextDouble * 2.0) - 1.0

  /** Returns true if the argument point would be 'inside' the unit circle with
    * center at the origin, and bounded by a square with side lengths of 2
    * units. */
  def insideCircle(pt: (Double, Double)): Boolean = pt match {
    case (x, y) => (x * x) + (y * y) <= 1.0
  }

  /** Runs the simulation the specified number of times. Uses the result to
    * estimate a value of pi */
  def simulate(times: Int): Double = {
    val inside = Iterator.tabulate (times) (_ => (nextThrow, nextThrow)) count insideCircle
    inside.toDouble / times.toDouble * 4.0
  }

  def main(args: Array[String]): Unit = {
    val sims = Seq(10000, 100000, 1000000, 10000000, 100000000)
    sims.foreach { n =>
      println(n+" simulations; pi estimation: "+ simulate(n))
    }
  }
}


"""A List Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from itertools import chain

from typing import Any
from typing import Callable
from typing import Iterable
from typing import List
from typing import TypeVar

T = TypeVar("T")

class MList(List[T]):
    @classmethod
    def unit(cls, value: Iterable[T]) -> MList[T]:
        return cls(value)

    def bind(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return MList(chain.from_iterable(map(func, self)))

    def __rshift__(self, func: Callable[[T], MList[Any]]) -> MList[Any]:
        return self.bind(func)

if __name__ == "__main__":
    # Chained int and string functions
    print(
        MList([1, 99, 4])
        .bind(lambda val: MList([val + 1]))
        .bind(lambda val: MList([f"${val}.00"]))
    )

    # Same, but using `>>` as the bind operator.
    print(
        MList([1, 99, 4])
        >> (lambda val: MList([val + 1]))
        >> (lambda val: MList([f"${val}.00"]))
    )

    # Cartesian product of [1..5] and [6..10]
    print(
        MList(range(1, 6)).bind(
            lambda x: MList(range(6, 11)).bind(lambda y: MList([(x, y)]))
        )
    )

    # Pythagorean triples with elements between 1 and 25
    print(
        MList(range(1, 26)).bind(
            lambda x: MList(range(x + 1, 26)).bind(
                lambda y: MList(range(y + 1, 26)).bind(
                    lambda z: MList([(x, y, z)])
                    if x * x + y * y == z * z
                    else MList([])
                )
            )
        )
    )


#lang racket

(define (bind x f) (append-map f x))
(define return list)
(define ((lift f) x) (list (f x)))

(define listy-inc (lift add1))
(define listy-double (lift (λ (x) (* 2 x))))

(bind (bind '(3 4 5) listy-inc) listy-double)
;; => '(8 10 12)

(define (pythagorean-triples n)
  (bind (range 1 n)
        (λ (x)
          (bind (range (add1 x) n)
                (λ (y)
                  (bind (range (add1 y) n)
                        (λ (z)
                          (if (= (+ (* x x) (* y y)) (* z z))
                              (return (list x y z))
                              '()))))))))

(pythagorean-triples 25)
;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))

(require syntax/parse/define)

(define-syntax-parser do-macro
  [(_ [x {~datum <-} y] . the-rest) #'(bind y (λ (x) (do-macro . the-rest)))]
  [(_ e) #'e])

(define (pythagorean-triples* n)
  (do-macro
   [x <- (range 1 n)]
   [y <- (range (add1 x) n)]
   [z <- (range (add1 y) n)]
   (if (= (+ (* x x) (* y y)) (* z z))
       (return (list x y z))
       '())))

(pythagorean-triples* 25)
;; => '((3 4 5) (5 12 13) (6 8 10) (8 15 17) (9 12 15) (12 16 20))


program N_queens;

  parameter SIZE_LOG2 = 3;
  parameter SIZE = 1 << SIZE_LOG2;

  `define ABS_DIFF(a,b) (a>b?a-b:b-a)

  class board;
    rand bit [SIZE_LOG2-1:0] row[SIZE];

    constraint rook_moves {
      foreach (row[i]) foreach (row[j]) if (i < j) {
        row[i] != row[j];
      }
    }

    constraint diagonal_moves {
      foreach (row[i]) foreach (row[j]) if (i < j) {
        `ABS_DIFF(row[i], row[j]) != `ABS_DIFF(i,j);
      }
    }

    function void next;
      randomize;
      foreach (row[i]) begin
        automatic bit [SIZE-1:0] x = 1 << row[i];
        $display( "  %b", x );
      end
      $display("--");
    endfunction

  endclass

  board b = new;
  initial repeat(1) b.next;

endprogram


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

const func float: pi (in integer: throws) is func
  result
    var float: pi is 0.0;
  local
    var integer: throw is 0;
    var integer: inside is 0;
  begin
    for throw range 1 to throws do
      if rand(0.0, 1.0) ** 2 + rand(0.0, 1.0) ** 2 <= 1.0 then
        incr(inside);
      end if;
    end for;
    pi := flt(4 * inside) / flt(throws);
  end func;

const proc: main is func
  begin
    writeln("    10000: " <& pi(    10000) digits 5);
    writeln("   100000: " <& pi(   100000) digits 5);
    writeln("  1000000: " <& pi(  1000000) digits 5);
    writeln(" 10000000: " <& pi( 10000000) digits 5);
    writeln("100000000: " <& pi(100000000) digits 5);
  end func;


import <Utilities/Random.sl>;
import <Utilities/Conversion.sl>;

main(args(2)) := monteCarlo(stringToInt(args[1]), stringToInt(args[2]));

monteCarlo(n, seed) :=
	let
		totalHits := monteCarloHelper(n, seedRandom(seed), 0);
	in
		(totalHits / intToFloat(n))*4.0;

monteCarloHelper(n, generator, result) :=
	let
		xRand := getRandom(generator);
		x := xRand.Value/(generator.RandomMax + 1.0);
		yRand := getRandom(xRand.Generator);
		y := yRand.Value/(generator.RandomMax + 1.0);

		newResult := result + 1 when x^2 + y^2 < 1.0 else
					 result;
	in
		result when n < 0 else
		monteCarloHelper(n - 1, yRand.Generator, newResult);


func monteCarloPi(nthrows) {
    4 * (^nthrows -> count_by {
        hypot(1.rand(2) - 1, 1.rand(2) - 1) < 1
    }) / nthrows
}

for n in [1e2, 1e3, 1e4, 1e5, 1e6] {
    printf("%9d: %07f\n", n, monteCarloPi(n))
}


program define mcdisk
	clear all
	quietly set obs `1'
	gen x=2*runiform()
	gen y=2*runiform()
	quietly count if (x-1)^2+(y-1)^2<1
	display 4*r(N)/_N
end

. mcdisk 10000
3.1424

. mcdisk 1000000
3.141904

. mcdisk 100000000
3.1416253


import Foundation

func mcpi(sampleSize size:Int) -> Double {
    var x = 0 as Double
    var y = 0 as Double
    var m = 0 as Double

    for i in 0..<size {
        x = Double(arc4random()) / Double(UINT32_MAX)
        y = Double(arc4random()) / Double(UINT32_MAX)

        if ((x * x) + (y * y) < 1) {
            m += 1
        }
    }

    return (4.0 * m) / Double(size)
}

println(mcpi(sampleSize: 100))
println(mcpi(sampleSize: 1000))
println(mcpi(sampleSize: 10000))
println(mcpi(sampleSize: 100000))
println(mcpi(sampleSize: 1000000))
println(mcpi(sampleSize: 10000000))
println(mcpi(sampleSize: 100000000))


multi bind (@list, &code) { @list.map: &code };

multi bind ($item, &code) { $item.&code };

sub divisors (Int $int) { gather for 1 .. $int { .take if $int %% $_ } }

put (^10).&bind(* + 3).&bind(&divisors)».&bind(*.base: 2).join: "\n";


# Project : Monads/List monad

 func main()
        str = "["
        for x in [3,4,5]
             y = x+1
             z = y*2
             str = str + z + ", "
        next
        str = left(str, len(str) -2)
        str = str + "]"
        see str + nl


class Array
  def bind(f)
    flat_map(&f)
  end
  def self.unit(*args)
    args
  end
  # implementing lift is optional, but is a great helper method for turning
  # ordinary funcitons into monadic versions of them.
  def self.lift(f)
    -> e { self.unit(f[e]) }
  end
end

inc = -> n { n + 1 }
str = -> n { n.to_s }
listy_inc = Array.lift(inc)
listy_str = Array.lift(str)

Array.unit(3,4,5).bind(listy_inc).bind(listy_str) #=> ["4", "5", "6"]

# Note that listy_inc and listy_str cannot be composed directly,
# as they don't have compatible type signature.
# Due to duck typing (Ruby will happily turn arrays into strings),
#   in order to show this, a new function will have to be used:

doub = -> n { 2*n }
listy_doub = Array.lift(doub)
[3,4,5].bind(listy_inc).bind(listy_doub) #=> [8, 10, 12]

# Direct composition will cause a TypeError, as Ruby cannot evaluate 2*[4, 5, 6]
# Using bind with the composition is *supposed* to fail, no matter the programming language.
comp = -> f, g {-> x {f[g[x]]}}
[3,4,5].bind(comp[listy_doub, listy_inc]) #=> TypeError: Array can't be coerced into Fixnum

# Composition needs to be defined in terms of bind
class Array
  def bind_comp(f, g)
    bind(g).bind(f)
  end
end

[3,4,5].bind_comp(listy_doub, listy_inc) #=> [8, 10, 12]


templates queens
  def n: $;
  templates addColumn
    def prev: $;
    templates addIfPossible
      def row: $;
      def minor: $ - $prev::length - 1;
      def major: $ + $prev::length + 1;
      // If prev is not an array that contains row, send it on...
      $prev -> \(when <~[<=$row>]> do $ !\)
            -> \(when <?($ -> \[i]($ - $i !\) <~[<=$minor>]>)> do $ !\)
            -> \(when <?($ -> \[i]($ + $i !\) <~[<=$major>]>)> do $ !\)
            -> [ $..., $row] !
    end addIfPossible
    1..$n -> addIfPossible !
  end addColumn
  1..$n -> [$] -> #
  when <[]($n)> do $ !
  otherwise $ -> addColumn -> #
end queens

def solutions: [ 8 -> queens ];
'For 8 queens there are $solutions::length; solutions
' -> !OUT::write

def columns: ['abcdefgh'...];
'One of them is $solutions(1) -> \[i]('$columns($i);$;' !\);
' -> !OUT::write

'For 3 queens there are $:[3 -> queens] -> $::length; solutions
' -> !OUT::write


proc pi {samples} {
    set i 0
    set inside 0
    while {[incr i] <= $samples} {
        if {sqrt(rand()**2 + rand()**2) <= 1.0} {
            incr inside
        }
    }
    return [expr {4.0 * $inside / $samples}]
}

puts "PI is approx [expr {atan(1)*4}]\n"
foreach runs {1e2 1e4 1e6 1e8} {
    puts "$runs => [pi $runs]"
}


#import std
#import flo

mcp "n" = times/4. div\float"n" (rep"n" (fleq/.5+ sqrt+ plus+ ~~ sqr+ minus/.5+ rand)?/~& plus/1.) 0.


import "random" for Random
import "/fmt" for Fmt

var rand = Random.new()

var mcPi = Fn.new { |n|
    var inside = 0
    for (i in 1..n) {
        var x = rand.float()
        var y = rand.float()
        if (x*x + y*y <= 1) inside = inside + 1
    }
    return 4 * inside / n
}

System.print("Iterations -> Approx Pi  -> Error\%")
System.print("----------    ----------    ------")
var n = 1000
while (n <= 1e8) {
    var pi = mcPi.call(n)
    var err = (Num.pi - pi).abs / Num.pi * 100.0
    Fmt.print("$9d  -> $10.8f -> $6.4f", n, pi, err)
    n = n * 10
}


s := "[" : Push 5, 4, 3

Do While Used ()
  y = Set (x, Pop ()) + 1
  s = Join (s, Str (Set (z, y * 2)), ", " )
Loop

Print Show (Set (s, Join (Clip (s, 2), "]")))


class Mlist {
    construct new(value) { _value = value }

    value { _value }

    bind(f) { f.call(_value) }

    static unit(lst) { Mlist.new(lst) }
}

var increment = Fn.new { |lst|
    var lst2 = lst.map { |v| v + 1 }.toList
    return Mlist.unit(lst2)
}

var double = Fn.new { |lst|
    var lst2 = lst.map { |v| v * 2 }.toList
    return Mlist.unit(lst2)
}

var ml1 = Mlist.unit([3, 4, 5])
var ml2 = ml1.bind(increment).bind(double)
System.print("%(ml1.value) -> %(ml2.value)")


class MList{
   fcn init(xs){ var list=vm.arglist }
   fcn bind(f) { list=list.apply(f); self }
   fcn toString{ list.toString() }
}


package require Tcl 8.5

proc unsafe {y} {
    global b
    set x [lindex $b $y]
    for {set i 1} {$i <= $y} {incr i} {
	set t [lindex $b [expr {$y - $i}]]
	if {$t==$x || $t==$x-$i || $t==$x+$i} {
	    return 1
	}
    }
    return 0
}

proc putboard {} {
    global b s N
    puts "\n\nSolution #[incr s]"
    for {set y 0} {$y < $N} {incr y} {
	for {set x 0} {$x < $N} {incr x} {
	    puts -nonewline [expr {[lindex $b $y] == $x ? "|Q" : "|_"}]
	}
	puts "|"
    }
}

proc main {n} {
    global b N
    set N $n
    set b [lrepeat $N 0]
    set y 0
    lset b 0 -1
    while {$y >= 0} {
	lset b $y [expr {[lindex $b $y] + 1}]
	while {[lindex $b $y] < $N && [unsafe $y]} {
	    lset b $y [expr {[lindex $b $y] + 1}]
	}
	if {[lindex $b $y] >= $N} {
	    incr y -1
	} elseif {$y < $N-1} {
	    lset b [incr y] -1;
	} else {
	    putboard
	}
    }
}

main [expr {$argc ? int(0+[lindex $argv 0]) : 8}]


code Ran=1, CrLf=9;
code real RlOut=48;

func real MontePi(N);   \Calculate pi using Monte Carlo method
int  N;                 \number of randomly selected points
int  I, X, Y, C;
def  R = 10000;         \radius of circle
[C:= 0;                 \initialize count of points in circle
for I:= 0 to N-1 do
        [X:= Ran(R);
         Y:= Ran(R);
        if X*X + Y*Y <= R*R then C:= C+1;
        ];
return float(C)*4.0 / float(N);   \Acir/Asqr = pi*R^2/4*R^2 = pi/4
];

[RlOut(0, MontePi(        100));  CrLf(0);
 RlOut(0, MontePi(     10_000));  CrLf(0);
 RlOut(0, MontePi(  1_000_000));  CrLf(0);
 RlOut(0, MontePi(100_000_000));  CrLf(0);
]


fcn monty(n){
   inCircle:=0;
   do(n){
      x:=(0.0).random(1); y:=(0.0).random(1);
      if(x*x + y*y < 1.0) inCircle+=1;
   }
   4.0*inCircle/n
}


#!/bin/bash

# variable declaration
typeset -i BoardSize=8
typeset -i p=0
typeset -i total=0
typeset -i board

# initialization
function init
{
    for (( i=0;i<$BoardSize;i++ ))
    do
        (( board[$i]=-1 ))
    done
}

# check if queen can be placed
function place
{
        typeset -i flag=1
        for (( i=0;i<$1;i++ ))
        do
                if [[ (${board[$i]}-${board[$1]} -eq ${i}-${1}) || (${board[$i]}-${board[$1]} -eq ${1}-${i}) || (${board[$i]} -eq ${board[$1]}) ]]
                then
                        (( flag=0 ))
                fi
        done
        [[ $flag -eq 0 ]]
        return $?
}

# print the result
function out
{
        printf "Problem of queen %d:%d\n" $BoardSize $total
}

# free the variables
function depose
{
    unset p
    unset total
    unset board
    unset BoardSize
}

# back tracing
function work
{
    while [[ $p -gt -1 ]]
        do
        (( board[$p]++ ))
        if  [[ ${board[$p]} -ge ${BoardSize} ]]
        then  # back tracing
            (( p-- ))
        else  # try next position
            place $p
            if [[ $? -eq 1 ]]
            then
                (( p++ ))
                if [[ $p -ge ${BoardSize} ]]
                then
                    (( total++ ))
                    (( p-- ))
                else
                    (( board[$p]=-1 ))
                fi
            fi
        fi
    done
}

# entry
init
work
out
depose


#import std
#import nat

remove_reflections = ^D([email protected],~&); ~&K2hlPS+ * ^lrNCCs/~&r difference*D
remove_rotations   = ~&K2hlrS2S+ * num; ~&srlXSsPNCCs

#executable <'par',''>
#optimize+

queens =

%np+~command.options.&h.keyword.&iNC; -+
   ~&iNC+ file$[contents: --<''>+ mat` *+ %nP*=*],
   remove_rotations+ remove_reflections+ ~&rSSs+ nleq-<&l*rFlhthPXPSPS,
   ~&i&& ~&lNrNCXX; ~&rr->rl ^/~&l ~&lrrhrSiF4E?/~&rrlPlCrtPX @r ^|/~& ^|T\~& -+
      -<&l^|*DlrTS/~& ~&iiDlSzyCK9hlPNNXXtCS,
      ^jrX/~& @rZK20lrpblPOlrEkPK13lhPK2 ~&i&& nleq$-&lh+-,
   ^/~&NNXS+iota -<&l+ ~&plll2llr2lrPrNCCCCNXS*=irSxPSp+ ^H/block iota; *iiK0 ^/~& sum+-


'N-queens problem - non recursive & structured - vba - 26/02/2017
Sub n_queens()
    Const l = 15  'number of queens
    Const b = False  'print option
    Dim a(l), s(l), u(4 * l - 2)
    Dim n, m, i, j, p, q, r, k, t, z
    For i = 1 To UBound(a): a(i) = i: Next i
    For n = 1 To l
        m = 0
        i = 1
        j = 0
        r = 2 * n - 1
        Do
            i = i - 1
            j = j + 1
            p = 0
            q = -r
            Do
                i = i + 1
                u(p) = 1
                u(q + r) = 1
                z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                p = i - a(i) + n
                q = i + a(i) - 1
                s(i) = j
                j = i + 1
            Loop Until j > n Or u(p) Or u(q + r)
            If u(p) = 0 Then
                If u(q + r) = 0 Then
                    m = m + 1  'm: number of solutions
                    If b Then
                        Debug.Print "n="; n; "m="; m
                        For k = 1 To n
                            For t = 1 To n
                                Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
                            Next t
                            Debug.Print
                        Next k
                    End If
                End If
            End If
            j = s(i)
            Do While j >= n And i <> 0
                Do
                    z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                    j = j - 1
                Loop Until j < i
                i = i - 1
                p = i - a(i) + n
                q = i + a(i) - 1
                j = s(i)
                u(p) = 0
                u(q + r) = 0
            Loop
        Loop Until i = 0
        Debug.Print n, m  'number of queens, number of solutions
    Next n
End Sub 'n_queens


'N-queens problem - non recursive & structured - vbs - 24/02/2017
const l=15
dim a(),s(),u(): redim a(l),s(l),u(4*l-2)
for i=1 to l: a(i)=i: next
for n=1 to l
    m=0
    i=1
    j=0
    r=2*n-1
    Do
        i=i-1
        j=j+1
        p=0
        q=-r
        Do
            i=i+1
            u(p)=1
            u(q+r)=1
            z=a(j): a(j)=a(i): a(i)=z  'swap a(i),a(j)
            p=i-a(i)+n
            q=i+a(i)-1
            s(i)=j
            j=i+1
        Loop Until j>n Or u(p)<>0 Or u(q+r)<>0
        If u(p)=0 Then
            If u(q+r)=0 Then
                m=m+1  'm: number of solutions
                'x="": for k=1 to n: x=x&" "&a(k): next: msgbox x,,m
             End If
        End If
        j=s(i)
        Do While j>=n And i<>0
            Do
                z=a(j): a(j)=a(i): a(i)=z  'swap a(i),a(j)
                j=j-1
            Loop Until j<i
            i=i-1
            p=i-a(i)+n
            q=i+a(i)-1
            j=s(i)
            u(p)=0
            u(q+r)=0
        Loop
    Loop Until i=0
    wscript.echo n &":"& m
next 'n


'N-queens problem - non recursive & structured - vb6 - 25/02/2017
Sub n_queens()
    Const l = 15  'number of queens
    Const b = False  'print option
    Dim a(l), s(l), u(4 * l - 2)
    Dim n, m, i, j, p, q, r, k, t, z
    For i = 1 To UBound(a): a(i) = i: Next i
    For n = 1 To l
        m = 0
        i = 1
        j = 0
        r = 2 * n - 1
        Do
            i = i - 1
            j = j + 1
            p = 0
            q = -r
            Do
                i = i + 1
                u(p) = 1
                u(q + r) = 1
                z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                p = i - a(i) + n
                q = i + a(i) - 1
                s(i) = j
                j = i + 1
            Loop Until j > n Or u(p) Or u(q + r)
            If u(p) = 0 Then
                If u(q + r) = 0 Then
                    m = m + 1  'm: number of solutions
                    If b Then
                        Debug.Print "n="; n; "m="; m
                        For k = 1 To n
                            For t = 1 To n
                                Debug.Print IIf(a(n - k + 1) = t, "Q", ".");
                            Next t
                            Debug.Print
                        Next k
                    End If
                End If
            End If
            j = s(i)
            Do While j >= n And i <> 0
                Do
                    z = a(j): a(j) = a(i): a(i) = z  'Swap a(i), a(j)
                    j = j - 1
                Loop Until j < i
                i = i - 1
                p = i - a(i) + n
                q = i + a(i) - 1
                j = s(i)
                u(p) = 0
                u(q + r) = 0
            Loop
        Loop Until i = 0
        Debug.Print n, m  'number of queens, number of solutions
    Next n
End Sub 'n_queens


'N-queens problem - non recursive & structured - vb.net - 26/02/2017
Module Mod_n_queens
    Sub n_queens()
        Const l = 15  'number of queens
        Const b = False  'print option
        Dim a(l), s(l), u(4 * l - 2)
        Dim n, m, i, j, p, q, r, k, t, z
        Dim w As String
        For i = 1 To UBound(a) : a(i) = i : Next i
        For n = 1 To l
            m = 0
            i = 1
            j = 0
            r = 2 * n - 1
            Do
                i = i - 1
                j = j + 1
                p = 0
                q = -r
                Do
                    i = i + 1
                    u(p) = 1
                    u(q + r) = 1
                    z = a(j) : a(j) = a(i) : a(i) = z  'Swap a(i), a(j)
                    p = i - a(i) + n
                    q = i + a(i) - 1
                    s(i) = j
                    j = i + 1
                Loop Until j > n Or u(p) Or u(q + r)
                If u(p) = 0 Then
                    If u(q + r) = 0 Then
                        m = m + 1  'm: number of solutions
                        If b Then
                            Debug.Print("n=" & n & " m=" & m) : w = ""
                            For k = 1 To n
                                For t = 1 To n
                                    w = w & If(a(n - k + 1) = t, "Q", ".")
                                Next t
                                Debug.Print(w)
                            Next k
                        End If
                    End If
                End If
                j = s(i)
                Do While j >= n And i <> 0
                    Do
                        z = a(j) : a(j) = a(i) : a(i) = z  'Swap a(i), a(j)
                        j = j - 1
                    Loop Until j < i
                    i = i - 1
                    p = i - a(i) + n
                    q = i + a(i) - 1
                    j = s(i)
                    u(p) = 0
                    u(q + r) = 0
                Loop
            Loop Until i = 0
            Debug.Print(n & vbTab & m)  'number of queens, number of solutions
        Next n
    End Sub 'n_queens
End Module


def (nqueens n queens)
  prn "step: " queens  # show progress
  if (len.queens = n)
    prn "solution! " queens
    # else
    let row (if queens (queens.zero.zero + 1) 0)
      for col 0 (col < n) ++col
        let new_queens (cons (list row col) queens)
          if (no conflicts.new_queens)
            (nqueens n new_queens)

# check if the first queen in 'queens' lies on the same column or diagonal as
# any of the others
def (conflicts queens)
  let (curr ... rest) queens
    or (let curr_column curr.1
         (some (fn(_) (= _ curr_column))
               (map cadr rest)))  # columns
       (some (fn(_) (diagonal_match curr _))
             rest)

def (diagonal_match curr other)
  (= (abs (curr.0 - other.0))
     (abs (curr.1 - other.1)))