/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program binSearch64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .asciz "Value find at index : @ \n"
szCarriageReturn:   .asciz "\n"
sMessRecursif:      .asciz "Recursive search : \n"
sMessNotFound:      .asciz "Value not found. \n"

TableNumber:        .quad   4,6,7,10,11,15,22,30,35
                    .equ NBELEMENTS,  (. - TableNumber) / 8
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
sZoneConv:          .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                           // entry of program
    mov x0,4                                    // search first value
    ldr x1,qAdrTableNumber                      // address number table
    mov x2,NBELEMENTS                           // number of élements
    bl bSearch
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

    mov x0,#11                                  // search median value
    ldr x1,qAdrTableNumber
    mov x2,#NBELEMENTS
    bl bSearch
    ldr x1,qAdrsZoneConv
    bl conversion10                             // decimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

    mov x0,#12                                  //value not found
    ldr x1,qAdrTableNumber
    mov x2,#NBELEMENTS
    bl bSearch
    cmp x0,#-1
    bne 2f
    ldr x0,qAdrsMessNotFound
    bl affichageMess
    b 3f
2:
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message
3:
    mov x0,#35                                  // search last value
    ldr x1,qAdrTableNumber
    mov x2,#NBELEMENTS
    bl bSearch
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

/****************************************/
/*       recursive                      */
/****************************************/
    ldr x0,qAdrsMessRecursif
    bl affichageMess                            // display message

    mov x0,#4                                   // search first value
    ldr x1,qAdrTableNumber
    mov x2,#0                                   // low index of elements
    mov x3,#NBELEMENTS - 1                      // high index of elements
    bl bSearchR
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

    mov x0,#11
    ldr x1,qAdrTableNumber
    mov x2,#0
    mov x3,#NBELEMENTS - 1
    bl bSearchR
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

    mov x0,#12
    ldr x1,qAdrTableNumber
    mov x2,#0
    mov x3,#NBELEMENTS - 1
    bl bSearchR
    cmp x0,#-1
    bne 4f
    ldr x0,qAdrsMessNotFound
    bl affichageMess
    b 5f
4:
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

5:
    mov x0,#35
    ldr x1,qAdrTableNumber
    mov x2,#0
    mov x3,#NBELEMENTS - 1
    bl bSearchR
    ldr x1,qAdrsZoneConv
    bl conversion10                             // décimal conversion
    ldr x0,qAdrsMessResult
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc                       // insert result at @ character
    bl affichageMess                            // display message

100:                                            // standard end of the program
    mov x0, #0                                  // return code
    mov x8, #EXIT                               // request to exit program
    svc #0                                      // perform the system call

//qAdrsMessValeur:          .quad sMessValeur
qAdrsZoneConv:            .quad sZoneConv
qAdrszCarriageReturn:     .quad szCarriageReturn
qAdrsMessResult:          .quad sMessResult
qAdrsMessRecursif:        .quad sMessRecursif
qAdrsMessNotFound:        .quad sMessNotFound
qAdrTableNumber:          .quad TableNumber

/******************************************************************/
/*     binary search   iterative                                  */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the number of elements */
/* x0 return index or -1 if not find */
bSearch:
    stp x1,lr,[sp,-16]!              // save  registers
    stp x2,x3,[sp,-16]!              // save  registers
    stp x4,x5,[sp,-16]!              // save  registers
    mov x3,#0                        // low index
    sub x4,x2,#1                     // high index = number of elements - 1
1:
    cmp x3,x4
    bgt 99f
    add x2,x3,x4                     // compute (low + high) /2
    lsr x2,x2,#1
    ldr x5,[x1,x2,lsl #3]            // load value of table at index x2
    cmp x5,x0
    beq 98f
    bgt 2f
    add x3,x2,#1                     // lower -> index low = index + 1
    b 1b                             // and loop
2:
    sub x4,x2,#1                     // bigger -> index high = index - 1
    b 1b                             // and loop
98:
    mov x0,x2                        // find !!!
    b 100f
99:
    mov x0,#-1                       //not found
100:
    ldp x4,x5,[sp],16                // restaur  2 registers
    ldp x2,x3,[sp],16                // restaur  2 registers
    ldp x1,lr,[sp],16                // restaur  2 registers
    ret                              // return to address lr x30
/******************************************************************/
/*     binary search   recursif                                  */
/******************************************************************/
/* x0 contains the value to search */
/* x1 contains the adress of table */
/* x2 contains the low index of elements */
/* x3 contains the high index of elements */
/* x0 return index or -1 if not find */
bSearchR:
    stp x2,lr,[sp,-16]!              // save  registers
    stp x3,x4,[sp,-16]!              // save  registers
    stp x5,x6,[sp,-16]!              // save  registers
    cmp x3,x2                        // index high < low ?
    bge 1f
    mov x0,#-1                       // yes -> not found
    b 100f
1:
    add x4,x2,x3                                     // compute (low + high) /2
    lsr x4,x4,#1
    ldr x5,[x1,x4,lsl #3]                            // load value of table at index x4
    cmp x5,x0
    beq 99f
    bgt 2f                                           // bigger ?
    add x2,x4,#1                                     // no new search with low = index + 1
    bl bSearchR
    b 100f
2:                                                   // bigger
    sub x3,x4,#1                                     // new search with high = index - 1
    bl bSearchR
    b 100f
99:
    mov x0,x4                                      // find !!!
    b 100f
100:
    ldp x5,x6,[sp],16                // restaur  2 registers
    ldp x3,x4,[sp],16                // restaur  2 registers
    ldp x2,lr,[sp],16                // restaur  2 registers
    ret                              // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


; Barnsley fern

(defun make-array (size)
  "Create an empty array with size*size elements."
  (setq m-array (make-vector size nil))
  (dotimes (i size)
    (setf (aref m-array i) (make-vector size 0)))
  m-array)

(defun barnsley-next (p)
  "Return the next Barnsley fern coordinates."
  (let ((r (random 100))
        (x (car p))
        (y (cdr p)))
      (cond ((< r 2)  (setq nx 0) (setq ny (* 0.16 y)))
            ((< r 9)  (setq nx (- (* 0.2 x) (* 0.26 y)))
                        (setq ny (+ 1.6 (* 0.23 x) (* 0.22 y))))
            ((< r 16) (setq nx (+ (* -0.15 x) (* 0.28 y)))
                        (setq ny (+ 0.44 (* 0.26 x) (* 0.24 y))))
            (t        (setq nx (+ (* 0.85 x) (* 0.04 y)))
                        (setq ny (+ 1.6 (* -0.04 x) (* 0.85 y)))))
      (cons nx ny)))

(defun barnsley-lines (arr size)
  "Turn array into a string for XPM conversion."
  (setq all "")
  (dotimes (y size)
    (setq line "")
    (dotimes (x size)
      (setq line (concat line (if (= (elt (elt arr y) x) 1) "*" "."))))
    (setq all (concat all "\"" line "\",\n")))
  all)

(defun barnsley-show (arr size)
  "Convert size*size array to XPM image and show it."
  (insert-image (create-image (concat (format "/* XPM */
static char * barnsley[] = {
\"%i %i 2 1\",
\".      c #000000\",
\"*      c #00ff00\"," size size)
    (barnsley-lines arr size) "};") 'xpm t)))

(defun barnsley (size scale max-iter)
  "Plot the Barnsley fern."
  (let ((arr (make-array size))
        (p (cons 0 0)))
    (dotimes (it max-iter)
      (setq p (barnsley-next p))
      (setq x (round (+ (/ size 2) (* scale (car p)))))
      (setq y (round (- size (* scale (cdr p)) 1)))
      (setf (elt (elt arr y) x) 1))
    (barnsley-show arr size)))

(barnsley 400 35 100000)


(defun defarray (name size initial-element)
   (cons name
         (compress1 name
                    (cons (list :HEADER
                                :DIMENSIONS (list size)
                                :MAXIMUM-LENGTH (1+ size)
                                :DEFAULT initial-element
                                :NAME name)
                                nil))))

(defconst *dim* 100000)

(defun array-name (array)
   (first array))

(defun set-at (array i val)
   (cons (array-name array)
         (aset1 (array-name array)
                (cdr array)
                i
                val)))

(defun populate-array-ordered (array n)
   (if (zp n)
       array
       (populate-array-ordered (set-at array
                                       (- *dim* n)
                                       (- *dim* n))
                               (1- n))))
(include-book "arithmetic-3/top" :dir :system)

(defun binary-search-r (needle haystack low high)
   (declare (xargs :measure (nfix (1+ (- high low)))))
   (let* ((mid (floor (+ low high) 2))
          (current (aref1 (array-name haystack)
                          (cdr haystack)
                          mid)))
         (cond ((not (and (natp low) (natp high))) nil)
               ((= current needle)
                mid)
               ((zp (1+ (- high low))) nil)
               ((> current needle)
                (binary-search-r needle
                                 haystack
                                 low
                                 (1- mid)))
               (t (binary-search-r needle
                                   haystack
                                   (1+ mid)
                                   high)))))

(defun binary-search (needle haystack)
   (binary-search-r needle haystack 0
                    (maximum-length (array-name haystack)
                                    (cdr haystack))))

(defun test-bsearch (needle)
   (binary-search needle
                  (populate-array-ordered
                   (defarray 'haystack *dim* 0)
                   *dim*)))


open System.Drawing

let (|F1|F2|F3|F4|) r =
    if r < 0.01 then F1
    else if r < 0.08 then F3
    else if r < 0.15 then F4
    else F2

let barnsleyFernFunction (x, y) = function
    | F1 -> (0.0, 0.16*y)
    | F2 -> ((0.85*x + 0.04*y), (-0.04*x + 0.85*y + 1.6))
    | F3 -> ((0.2*x - 0.26*y), (0.23*x + 0.22*y + 1.6))
    | F4 -> ((-0.15*x + 0.28*y), (0.26*x + 0.24*y + 0.44))

let barnsleyFern () =
    let rnd = System.Random()
    (0.0, 0.0)
    |> Seq.unfold (fun point -> Some (point, barnsleyFernFunction point (rnd.NextDouble())))

let run width height =
    let emptyBitmap = new Bitmap(int width,int height)
    let bitmap =
        barnsleyFern ()
        |> Seq.take 250000 // calculate points
        |> Seq.map (fun (x,y) -> (int (width/2.0+(width*x/11.0)), int (height-(height*y/11.0)))) // transform to pixels
        |> Seq.fold (fun (b:Bitmap) (x,y) -> b.SetPixel(x-1,y-1,Color.ForestGreen); b) emptyBitmap // add pixels to bitmap
    bitmap.Save("BFFsharp.png")


INT FUNC BinarySearch(INT ARRAY a INT len,value)
  INT low,high,mid

  low=0 high=len-1
  WHILE low<=high
  DO
    mid=low+(high-low) RSH 1
    IF a(mid)>value THEN
      high=mid-1
    ELSEIF a(mid)<value THEN
      low=mid+1
    ELSE
      RETURN (mid)
    FI
  OD
RETURN (-1)

PROC Test(INT ARRAY a INT len,value)
  INT i

  Put('[)
  FOR i=0 TO len-1
  DO
    PrintI(a(i))
    IF i<len-1 THEN Put(32) FI
  OD
  i=BinarySearch(a,len,value)
  Print("] ") PrintI(value)
  IF i<0 THEN
    PrintE(" not found")
  ELSE
    Print(" found at index ")
    PrintIE(i)
  FI
RETURN

PROC Main()
  INT ARRAY a=[65530 0 1 2 5 6 8 9]

  Test(a,8,6)
  Test(a,8,-6)
  Test(a,8,9)
  Test(a,8,-10)
  Test(a,8,10)
  Test(a,8,7)
RETURN


s" SDL2" add-lib
\c #include <SDL2/SDL.h>
c-function sdl-init		SDL_Init		n -- n
c-function sdl-quit		SDL_Quit		-- void
c-function sdl-createwindow	SDL_CreateWindow	a n n n n n -- a
c-function sdl-createrenderer	SDL_CreateRenderer	a n n -- a
c-function sdl-setdrawcolor	SDL_SetRenderDrawColor	a n n n n -- n
c-function sdl-drawpoint	SDL_RenderDrawPoint	a n n -- n
c-function sdl-renderpresent	SDL_RenderPresent	a -- void
c-function sdl-delay            SDL_Delay               n -- void

require random.fs

0 value window
0 value renderer
variable x
variable y

: initFern ( -- )
  $20 sdl-init drop
  s\" Rosetta Task : Barnsley fern\x0" drop 0 0 1000 1000 $0 sdl-createwindow to window
  window -1 $2 sdl-createrenderer to renderer
  renderer 0 255 0 255 sdl-setdrawcolor drop
;

create coefficients
             0 ,    0 ,   0 , 160 ,    0 ,    \  1% of the time - f1
           200 , -260 , 230 , 220 , 1600 ,    \  7% of the time - f3
          -150 ,  280 , 260 , 240 ,  440 ,    \  7% of the time - f4
           850 ,   40 , -40 , 850 , 1600 ,    \ 85% of the time - f2

: nextcoeff ( n -- n+1 coeff ) coefficients over cells + @ swap 1+ swap ;
: transformation ( n -- )
  nextcoeff x @ *   swap nextcoeff y @ *    rot + 1000 /   swap
  nextcoeff x @ *   swap nextcoeff y @ *    rot + 1000 /   swap nextcoeff rot +    y ! drop
  x !  \ x shall be modified after y calculation
;
: randomchoice ( -- index )
  100 random
  dup 0 > swap
  dup 7 > swap
  dup 14 > swap drop
  + + negate 5 *
;

: fern
initFern
20000 0 do
  randomchoice transformation
  renderer x @ 10 / 500 + y @ 10 / sdl-drawpoint drop
loop
renderer sdl-renderpresent
5000 sdl-delay
sdl-quit
;

fern


!Generates an output file "plot.dat" that contains the x and y coordinates
!for a scatter plot that can be visualized with say, GNUPlot
program BarnsleyFern
implicit none

double precision :: p(4), a(4), b(4), c(4), d(4), e(4), f(4), trx, try, prob
integer :: itermax, i

!The probabilites and coefficients can be modified to generate other
!fractal ferns, e.g. http://www.home.aone.net.au/~byzantium/ferns/fractal.html
!probabilities
p(1) = 0.01; p(2) = 0.85; p(3) = 0.07; p(4) = 0.07

!coefficients
a(1) =  0.00; a(2) =  0.85; a(3) =  0.20; a(4) = -0.15
b(1) =  0.00; b(2) =  0.04; b(3) = -0.26; b(4) =  0.28
c(1) =  0.00; c(2) = -0.04; c(3) =  0.23; c(4) =  0.26
d(1) =  0.16; d(2) =  0.85; d(3) =  0.22; d(4) =  0.24
e(1) =  0.00; e(2) =  0.00; e(3) =  0.00; e(4) =  0.00
f(1) =  0.00; f(2) =  1.60; f(3) =  1.60; f(4) =  0.44

itermax = 100000

trx = 0.0D0
try = 0.0D0

open(1, file="plot.dat")
write(1,*) "#X            #Y"
write(1,'(2F10.5)') trx, try

do i = 1, itermax
  call random_number(prob)
  if (prob < p(1)) then
    trx = a(1) * trx + b(1) * try + e(1)
    try = c(1) * trx + d(1) * try + f(1)
  else if(prob < (p(1) + p(2))) then
    trx = a(2) * trx + b(2) * try + e(2)
    try = c(2) * trx + d(2) * try + f(2)
  else if ( prob < (p(1) + p(2) + p(3))) then
    trx = a(3) * trx + b(3) * try + e(3)
    try = c(3) * trx + d(3) * try + f(3)
  else
    trx = a(4) * trx + b(4) * try + e(4)
    try = c(4) * trx + d(4) * try + f(4)
  end if
  write(1,'(2F10.5)') trx, try
end do
close(1)
end program BarnsleyFern


with Ada.Text_IO;  use Ada.Text_IO;

procedure Test_Recursive_Binary_Search is
   Not_Found : exception;

   generic
      type Index is range <>;
      type Element is private;
      type Array_Of_Elements is array (Index range <>) of Element;
      with function "<" (L, R : Element) return Boolean is <>;
   function Search (Container : Array_Of_Elements; Value : Element) return Index;

   function Search (Container : Array_Of_Elements; Value : Element) return Index is
      Mid : Index;
   begin
      if Container'Length > 0 then
         Mid := (Container'First + Container'Last) / 2;
         if Value < Container (Mid) then
            if Container'First /= Mid then
               return Search (Container (Container'First..Mid - 1), Value);
            end if;
         elsif Container (Mid) < Value then
            if Container'Last /= Mid then
               return Search (Container (Mid + 1..Container'Last), Value);
            end if;
         else
            return Mid;
         end if;
      end if;
      raise Not_Found;
   end Search;

   type Integer_Array is array (Positive range <>) of Integer;
   function Find is new Search (Positive, Integer, Integer_Array);

   procedure Test (X : Integer_Array; E : Integer) is
   begin
      New_Line;
      for I in X'Range loop
         Put (Integer'Image (X (I)));
      end loop;
      Put (" contains" & Integer'Image (E) & " at" & Integer'Image (Find (X, E)));
   exception
      when Not_Found =>
         Put (" does not contain" & Integer'Image (E));
   end Test;
begin
   Test ((2, 4, 6, 8, 9), 2);
   Test ((2, 4, 6, 8, 9), 1);
   Test ((2, 4, 6, 8, 9), 8);
   Test ((2, 4, 6, 8, 9), 10);
   Test ((2, 4, 6, 8, 9), 9);
   Test ((2, 4, 6, 8, 9), 5);
end Test_Recursive_Binary_Search;


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

Sub barnsley(height As UInteger)

  Dim As Double x, y, xn, yn
  Dim As Double f = height / 10.6
  Dim As UInteger offset_x = height \ 4 - height \ 40
  Dim As UInteger n, r

  ScreenRes height \ 2, height, 32

  For n = 1 To height * 50

    r = Int(Rnd * 100)      ' f from 0 to 99

    Select Case As Const r
      Case 0 To 84
        xn  =  0.85 * x + 0.04 * y
        yn  = -0.04 * x + 0.85 * y + 1.6
      Case 85 To 91
        xn  = 0.2  * x - 0.26 * y
        yn  = 0.23 * x + 0.22 * y + 1.6
      Case 92 To 98
        xn  = -0.15 * x + 0.28 * y
        yn  =  0.26 * x + 0.24 * y + 0.44
      Case Else
        xn = 0
        yn = 0.16 * y
    End Select

    x = xn : y = yn
    PSet( offset_x + x * f, height - y * f), RGB(0, 255, 0)

  Next
' remove comment (') in next line to save window as .bmp file
' BSave "barnsley_fern_" + Str(height) + ".bmp", 0

End Sub

' ------=< MAIN >=------

' adjustable window height
' call the subroutine with the height you want
' it's possible to have a window that's large than your display
 barnsley(800)

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


BEGIN
MODE ELEMENT = STRING;

# Iterative: #
PROC iterative binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: (
    INT out,
        low := LWB hay stack,
        high := UPB hay stack;
    WHILE low < high DO
        INT mid := (low+high) OVER 2;
        IF hay stack[mid] > needle THEN high := mid-1
        ELIF hay stack[mid] < needle THEN low := mid+1
        ELSE out:= mid; stop iteration FI
    OD;
        low EXIT
    stop iteration:
        out
);
# Recursive: #
PROC recursive binary search = ([]ELEMENT hay stack, ELEMENT needle)INT: (
    IF LWB hay stack > UPB hay stack THEN
        LWB hay stack
    ELIF LWB hay stack = UPB hay stack THEN
        IF hay stack[LWB hay stack] = needle THEN LWB hay stack
        ELSE LWB hay stack FI
    ELSE
        INT mid := (LWB hay stack+UPB hay stack) OVER 2;
        IF hay stack[mid] > needle THEN recursive binary search(hay stack[:mid-1], needle)
        ELIF hay stack[mid] < needle THEN mid + recursive binary search(hay stack[mid+1:], needle)
        ELSE mid FI
   FI
);
# Test cases: #
test:(
  ELEMENT needle = "mister";
  []ELEMENT hay stack = ("AA","Maestro","Mario","Master","Mattress","Mister","Mistress","ZZ"),
          test cases = ("A","Master","Monk","ZZZ");

  PROC test search = (PROC([]ELEMENT, ELEMENT)INT search, []ELEMENT test cases)VOID:
    FOR case TO UPB test cases DO
        ELEMENT needle = test cases[case];
        INT index = search(hay stack, needle);
        BOOL found = ( index <= 0 | FALSE | hay stack[index]=needle);
        print(("""", needle, """ ", (found|"FOUND at"|"near"), " index ", whole(index, 0), newline))
    OD;
  test search(iterative binary search, test cases);
  test search(recursive binary search, test cases)
)
END


begin % binary search %
    % recursive binary search, left most insertion point %
    integer procedure binarySearchLR ( integer array A ( * )
                                     ; integer value find, Low, high
                                     ) ;
        if high < low then low
        else begin
            integer mid;
            mid := ( low + high ) div 2;
            if A( mid ) >= find then binarySearchLR( A, find, low,     mid - 1 )
            else                     binarySearchLR( A, find, mid + 1, high    )
        end binarySearchR ;
    % iteratve binary search leftmost insertion point %
    integer procedure binarySearchLI ( integer array A ( * )
                                     ; integer value find, lowInit, highInit
                                     ) ;
        begin
            integer low, high;
            low  := lowInit;
            high := highInit;
            while low <= high do begin
                integer mid;
                mid := ( low + high ) div 2;
                if A( mid ) >= find then high := mid - 1
                else                     low  := mid + 1
            end while_low_le_high ;
            low
        end binarySearchLI ;
    % tests %
    begin
        integer array t ( 1 :: 10 );
        integer tPos;
        tPos := 1;
        for tValue := 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 do begin
            t( tPos ) := tValue;
            tPos      := tPOs + 1
        end for_tValue ;
        for s := 0 step 8 until 24 do begin
            integer pos;
            pos := binarySearchLR( t, s, 1, 10 );
            if t( pos ) = s then write( I_W := 3, S_W := 0, "recursive search finds           ", s, " at ", pos )
            else                 write( I_W := 3, S_W := 0, "recursive search suggests insert ", s, " at ", pos )
            ;
            pos := binarySearchLI( t, s, 1, 10 );
            if t( pos ) = s then write( I_W := 3, S_W := 0, "iterative search finds           ", s, " at ", pos )
            else                 write( I_W := 3, S_W := 0, "iterative search suggests insert ", s, " at ", pos )
        end for_s
    end
end.


## Barnsley fern fractal 2/17/17 aev
reset
fn="BarnsleyFernGnu"; clr='"green"';
ttl="Barnsley fern fractal"
dfn=fn.".dat"; ofn=fn.".png";
set terminal png font arial 12 size 640,640
set print dfn append
set output ofn
unset border; unset xtics; unset ytics; unset key;
set size square
set title ttl font "Arial:Bold,12"
n=100000; max=100; x=y=xw=yw=p=0;
randgp(top) = floor(rand(0)*top)
do for [i=1:n] {
  p=randgp(max);
  if (p==1) {xw=0;yw=0.16*y;}
  if (1<p&&p<=8) {xw=0.2*x-0.26*y;yw=0.23*x+0.22*y+1.6;}
  if (8<p&&p<=15) {xw=-0.15*x+0.28*y;yw=0.26*x+0.24*y+0.44;}
  if (p>15) {xw=0.85*x+0.04*y;yw=-0.04*x+0.85*y+1.6;}
  x=xw;y=yw; print x," ",y;
}
plot dfn using 1:2 with points  pt 7 ps 0.5 lc @clr
set output
unset print


binsrch←{
   ⎕IO(⍺{                       ⍝ first lower bound is start of array
       ⍵<⍺:⍬                    ⍝ if high < low, we didn't find it
       mid←⌊(⍺+⍵)÷2             ⍝ calculate mid point
       ⍺⍺[mid]>⍵⍵:⍺∇mid-1       ⍝ if too high, search from ⍺ to mid-1
       ⍺⍺[mid]<⍵⍵:(mid+1)∇⍵     ⍝ if too low, search from mid+1 to ⍵
       mid                      ⍝ otherwise, we did find it
   }⍵)⎕IO+(≢⍺)-1                ⍝ first higher bound is top of array
}


on binarySearch(n, theList, l, r)
    repeat until (l = r)
        set m to (l + r) div 2
        if (item m of theList < n) then
            set l to m + 1
        else
            set r to m
        end if
    end repeat

    if (item l of theList is n) then return l
    return missing value
end binarySearch

on test(n, theList, l, r)
    set |result| to binarySearch(n, theList, l, r)
    if (|result| is missing value) then
        return (n as text) & " is not in range " & l & " thru " & r & " of the list"
    else
        return "The first occurrence of " & n & " in range " & l & " thru " & r & " of the list is at index " & |result|
    end if
end test

set theList to {1, 2, 3, 3, 5, 7, 7, 8, 9, 10, 11, 12}
return test(7, theList, 4, 11) & linefeed & test(7, theList, 7, 12) & linefeed & test(7, theList, 1, 5)


package main

import (
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "log"
    "math/rand"
    "os"
)

// values from WP
const (
    xMin = -2.1820
    xMax = 2.6558
    yMin = 0.
    yMax = 9.9983
)

// parameters
var (
    width = 200
    n     = int(1e6)
    c     = color.RGBA{34, 139, 34, 255} // forest green
)

func main() {
    dx := xMax - xMin
    dy := yMax - yMin
    fw := float64(width)
    fh := fw * dy / dx
    height := int(fh)
    r := image.Rect(0, 0, width, height)
    img := image.NewRGBA(r)
    draw.Draw(img, r, &image.Uniform{color.White}, image.ZP, draw.Src)
    var x, y float64
    plot := func() {
        // transform computed float x, y to integer image coordinates
        ix := int(fw * (x - xMin) / dx)
        iy := int(fh * (yMax - y) / dy)
        img.SetRGBA(ix, iy, c)
    }
    plot()
    for i := 0; i < n; i++ {
        switch s := rand.Intn(100); {
        case s < 85:
            x, y =
                .85*x+.04*y,
                -.04*x+.85*y+1.6
        case s < 85+7:
            x, y =
                .2*x-.26*y,
                .23*x+.22*y+1.6
        case s < 85+7+7:
            x, y =
                -.15*x+.28*y,
                .26*x+.24*y+.44
        default:
            x, y = 0, .16*y
        }
        plot()
    }
    // write img to png file
    f, err := os.Create("bf.png")
    if err != nil {
        log.Fatal(err)
    }
    if err := png.Encode(f, img); err != nil {
        log.Fatal(err)
    }
}


/* ARM assembly Raspberry PI  */
/*  program binsearch.s   */

/************************************/
/* Constantes                       */
/************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessResult:        .ascii "Value find at index : "
sMessValeur:        .fill 11, 1, ' '            @ size => 11
szCarriageReturn:   .asciz "\n"
sMessRecursif:      .asciz "Recursive search : \n"
sMessNotFound:      .asciz "Value not found. \n"

.equ NBELEMENTS,      9
TableNumber:	     .int   4,6,7,10,11,15,22,30,35

/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                                           @ entry of program
    mov r0,#4                                   @ search first value
    ldr r1,iAdrTableNumber                      @ address number table
    mov r2,#NBELEMENTS                          @ number of élements
    bl bSearch
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message

    mov r0,#11                                  @ search median value
    ldr r1,iAdrTableNumber
    mov r2,#NBELEMENTS
    bl bSearch
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message

    mov r0,#12                                  @value not found
    ldr r1,iAdrTableNumber
    mov r2,#NBELEMENTS
    bl bSearch
    cmp r0,#-1
    bne 2f
    ldr r0,iAdrsMessNotFound
    bl affichageMess
    b 3f
2:
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message
3:
    mov r0,#35                                  @ search last value
    ldr r1,iAdrTableNumber
    mov r2,#NBELEMENTS
    bl bSearch
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message
/****************************************/
/*       recursive                      */
/****************************************/
    ldr r0,iAdrsMessRecursif
    bl affichageMess                            @ display message

    mov r0,#4                                   @ search first value
    ldr r1,iAdrTableNumber
    mov r2,#0                                   @ low index of elements
    mov r3,#NBELEMENTS - 1                      @ high index of elements
    bl bSearchR
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message

    mov r0,#11
    ldr r1,iAdrTableNumber
    mov r2,#0
    mov r3,#NBELEMENTS - 1
    bl bSearchR
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message

    mov r0,#12
    ldr r1,iAdrTableNumber
    mov r2,#0
    mov r3,#NBELEMENTS - 1
    bl bSearchR
    cmp r0,#-1
    bne 2f
    ldr r0,iAdrsMessNotFound
    bl affichageMess
    b 3f
2:
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message
3:
    mov r0,#35
    ldr r1,iAdrTableNumber
    mov r2,#0
    mov r3,#NBELEMENTS - 1
    bl bSearchR
    ldr r1,iAdrsMessValeur                      @ display value
    bl conversion10                             @ call function
    ldr r0,iAdrsMessResult
    bl affichageMess                            @ display message

100:                                            @ standard end of the program
    mov r0, #0                                  @ return code
    mov r7, #EXIT                               @ request to exit program
    svc #0                                      @ perform the system call

iAdrsMessValeur:          .int sMessValeur
iAdrszCarriageReturn:     .int szCarriageReturn
iAdrsMessResult:          .int sMessResult
iAdrsMessRecursif:        .int sMessRecursif
iAdrsMessNotFound:        .int sMessNotFound
iAdrTableNumber:          .int TableNumber

/******************************************************************/
/*     binary search   iterative                                  */
/******************************************************************/
/* r0 contains the value to search */
/* r1 contains the adress of table */
/* r2 contains the number of elements */
/* r0 return index or -1 if not find */
bSearch:
    push {r2-r5,lr}                                 @ save registers
    mov r3,#0                                       @ low index
    sub r4,r2,#1                                    @ high index = number of elements - 1
1:
    cmp r3,r4
    movgt r0,#-1                                    @not found
    bgt 100f
    add r2,r3,r4                                    @ compute (low + high) /2
    lsr r2,#1
    ldr r5,[r1,r2,lsl #2]                           @ load value of table at index r2
    cmp r5,r0
    moveq r0,r2                                     @ find !!!
    beq 100f
    addlt r3,r2,#1                                  @ lower -> index low = index + 1
    subgt r4,r2,#1                                  @ bigger -> index high = index - 1
    b 1b                                            @ and loop
100:
    pop {r2-r5,lr}
    bx lr                       @ return
/******************************************************************/
/*     binary search   recursif                                  */
/******************************************************************/
/* r0 contains the value to search */
/* r1 contains the adress of table */
/* r2 contains the low index of elements */
/* r3 contains the high index of elements */
/* r0 return index or -1 if not find */
bSearchR:
    push {r2-r5,lr}                                  @ save registers
    cmp r3,r2                                        @ index high < low ?
    movlt r0,#-1                                     @ yes -> not found
    blt 100f

    add r4,r2,r3                                     @ compute (low + high) /2
    lsr r4,#1
    ldr r5,[r1,r4,lsl #2]                            @ load value of table at index r4
    cmp r5,r0
    moveq r0,r4                                      @ find !!!
    beq 100f

    bgt 1f                                           @ bigger ?
    add r2,r4,#1                                     @ no new search with low = index + 1
    bl bSearchR
    b 100f
1:                                                   @ bigger
    sub r3,r4,#1                                     @ new search with high = index - 1
    bl bSearchR
100:
    pop {r2-r5,lr}
    bx lr                                            @ return
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}                          @ save  registres
    mov r2,#0                                      @ counter length
1:                                                 @ loop length calculation
    ldrb r1,[r0,r2]                                @ read octet start position + index
    cmp r1,#0                                      @ if 0 its over
    addne r2,r2,#1                                 @ else add 1 in the length
    bne 1b                                         @ and loop
                                                   @ so here r2 contains the length of the message
    mov r1,r0                                      @ address message in r1
    mov r0,#STDOUT                                 @ code to write to the standard output Linux
    mov r7, #WRITE                                 @ code call system "write"
    svc #0                                         @ call systeme
    pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres
    bx lr                                          @ return
/******************************************************************/
/*     Converting a register to a decimal unsigned                */
/******************************************************************/
/* r0 contains value and r1 address area   */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    push {r1-r4,lr}                                 @ save registers
    mov r3,r1
    mov r2,#LGZONECAL

1:	                                            @ start loop
    bl divisionpar10U                               @unsigned  r0 <- dividende. quotient ->r0 reste -> r1
    add r1,#48                                      @ digit
    strb r1,[r3,r2]                                 @ store digit on area
    cmp r0,#0                                       @ stop if quotient = 0
    subne r2,#1                                     @ else previous position
    bne 1b	                                    @ and loop
                                                    @ and move digit from left of area
    mov r4,#0
2:
    ldrb r1,[r3,r2]
    strb r1,[r3,r4]
    add r2,#1
    add r4,#1
    cmp r2,#LGZONECAL
    ble 2b
                                                     @ and move spaces in end on area
    mov r0,r4                                        @ result length
    mov r1,#' '                                      @ space
3:
    strb r1,[r3,r4]                                  @ store space in area
    add r4,#1                                        @ next position
    cmp r4,#LGZONECAL
    ble 3b                                           @ loop if r4 <= area size

100:
    pop {r1-r4,lr}                                   @ restaur registres
    bx lr                                            @return

/***************************************************/
/*   division par 10   unsigned                    */
/***************************************************/
/* r0 dividende   */
/* r0 quotient */
/* r1 remainder  */
divisionpar10U:
    push {r2,r3,r4, lr}
    mov r4,r0                                        @ save value
    //mov r3,#0xCCCD                                 @ r3 <- magic_number lower  raspberry 3
    //movt r3,#0xCCCC                                @ r3 <- magic_number higter raspberry 3
    ldr r3,iMagicNumber                              @ r3 <- magic_number    raspberry 1 2
    umull r1, r2, r3, r0                             @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
    mov r0, r2, LSR #3                               @ r2 <- r2 >> shift 3
    add r2,r0,r0, lsl #2                             @ r2 <- r0 * 5
    sub r1,r4,r2, lsl #1                             @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)
    pop {r2,r3,r4,lr}
    bx lr                                            @ leave function
iMagicNumber:  	.int 0xCCCCCCCD


import javafx.animation.AnimationTimer
import javafx.application.Application
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.image.ImageView
import javafx.scene.image.WritableImage
import javafx.scene.paint.Color
import javafx.stage.Stage

class BarnsleyFern extends Application {

    @Override
    void start(Stage primaryStage) {
        primaryStage.title = 'Barnsley Fern'
        primaryStage.scene = getScene()
        primaryStage.show()
    }

    def getScene() {
        def root = new Group()
        def scene = new Scene(root, 640, 640)
        def imageWriter = new WritableImage(640, 640)
        def imageView = new ImageView(imageWriter)
        root.children.add imageView

        def pixelWriter = imageWriter.pixelWriter

        def x = 0, y = 0

        ({

            50.times {
                def r = Math.random()

                if (r <= 0.01) {
                    x = 0
                    y = 0.16 * y
                } else if (r <= 0.08) {
                    x = 0.2 * x - 0.26 * y
                    y = 0.23 * x + 0.22 * y + 1.6
                } else if (r <= 0.15) {
                    x = -0.15 * x + 0.28 * y
                    y = 0.26 * x + 0.24 * y + 0.44
                } else {
                    x = 0.85 * x + 0.04 * y
                    y = -0.04 * x + 0.85 * y + 1.6
                }

                pixelWriter.setColor(Math.round(640 / 2 + x * 640 / 11) as Integer, Math.round(640 - y * 640 / 11) as Integer, Color.GREEN)
            }

        } as AnimationTimer).start()

        scene
    }

    static void main(args) {
        launch(BarnsleyFern)
    }
}


binarySearch: function [arr,val,low,high][
    if high < low -> return ø
    mid: shr low+high 1
    case [val]
        when? [< arr\[mid]] -> return binarySearch arr val low mid-1
        when? [> arr\[mid]] -> return binarySearch arr val mid+1 high
        else                -> return mid
]

ary: [
    0 1 4 5 6 7 8 9 12 26 45 67
    78 90 98 123 211 234 456 769
    865 2345 3215 14345 24324
]

loop [0 42 45 24324 99999] 'v [
    i: binarySearch ary v 0 (size ary)-1
    if? not? null? i    -> print ["found" v "at index:" i]
    else                -> print [v "not found"]
]


import Data.List (scanl')
import Diagrams.Backend.Rasterific.CmdLine
import Diagrams.Prelude
import System.Random

type Pt  = (Double, Double)

-- Four affine transformations used to produce a Barnsley fern.
f1, f2, f3, f4 :: Pt -> Pt
f1 (x, y) = (                       0,             0.16 * y)
f2 (x, y) = ( 0.85 * x + 0.04 * y    , -0.04 * x + 0.85 * y + 1.60)
f3 (x, y) = ( 0.20 * x - 0.26 * y    ,  0.23 * x + 0.22 * y + 1.60)
f4 (x, y) = (-0.15 * x + 0.28 * y    ,  0.26 * x + 0.24 * y + 0.44)

-- Given a random number in [0, 1) transform an initial point by a randomly
-- chosen function.
func :: Pt -> Double -> Pt
func p r | r < 0.01  = f1 p
         | r < 0.86  = f2 p
         | r < 0.93  = f3 p
         | otherwise = f4 p

-- Using a sequence of uniformly distributed random numbers in [0, 1) return
-- the same number of points in the fern.
fern :: [Double] -> [Pt]
fern = scanl' func (0, 0)

-- Given a supply of random values and a count, generate a diagram of a fern
-- composed of that number of points.
drawFern :: [Double] -> Int -> Diagram B
drawFern rs n = frame 0.5 . diagramFrom . take n $ fern rs
  where diagramFrom = flip atPoints (repeat dot) . map p2
        dot = circle 0.005 # lc green

-- To generate a PNG image of a fern, call this program like:
--
--   fern -o fern.png -w 640 -h 640 50000
--
-- where the arguments specify the width, height and number of points in the
-- image.
main :: IO ()
main = do
  rand <- getStdGen
  mainWith $ drawFern (randomRs (0, 1) rand)


100 PROGRAM "Fern.bas"
110 RANDOMIZE
120 SET VIDEO MODE 1:SET VIDEO COLOR 0:SET VIDEO X 40:SET VIDEO Y 27
130 OPEN #101:"video:"
140 DISPLAY #101:AT 1 FROM 1 TO 27
150 SET PALETTE BLACK,GREEN
160 LET MX=16000:LET X,Y=0
170 FOR N=1 TO MX
180   LET P=RND(100)
190   SELECT CASE P
200   CASE IS<=1
210     LET NX=0:LET NY=.16*Y
220   CASE IS<=8
230     LET NX=.2*X-.26*Y:LET NY=.23*X+.22*Y+1.6
240   CASE IS<=15
250     LET NX=-.15*X+.28*Y:LET NY=.26*X+.24*Y+.44
260   CASE ELSE
270     LET NX=.85*X+.04*Y:LET NY=-.04*X+.85*Y+1.6
280   END SELECT
290   LET X=NX:LET Y=NY
300   PLOT X*96+600,Y*96
310 NEXT


array := "1,2,4,6,8,9"
StringSplit, A, array, `,   ; creates associative array
MsgBox % x := BinarySearch(A, 4, 1, A0) ; Recursive
MsgBox % A%x%
MsgBox % x := BinarySearchI(A, A0, 4)  ; Iterative
MsgBox % A%x%

BinarySearch(A, value, low, high) { ; A0 contains length of array
  If (high < low)               ; A1, A2, A3...An are array elements
    Return not_found
  mid := Floor((low + high) / 2)
  If (A%mid% > value) ; A%mid% is automatically global since no such locals are present
    Return BinarySearch(A, value, low, mid - 1)
  Else If (A%mid% < value)
    Return BinarySearch(A, value, mid + 1, high)
  Else
    Return mid
}

BinarySearchI(A, lengthA, value) {
  low := 0
  high := lengthA - 1
  While (low <= high) {
    mid := Floor((low + high) / 2) ; round to lower integer
    If (A%mid% > value)
      high := mid - 1
    Else If (A%mid% < value)
      low := mid + 1
    Else
      Return mid
  }
  Return not_found
}


import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class BarnsleyFern extends JPanel {

    BufferedImage img;

    public BarnsleyFern() {
        final int dim = 640;
        setPreferredSize(new Dimension(dim, dim));
        setBackground(Color.white);
        img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
        createFern(dim, dim);
    }

    void createFern(int w, int h) {
        double x = 0;
        double y = 0;

        for (int i = 0; i < 200_000; i++) {
            double tmpx, tmpy;
            double r = Math.random();

            if (r <= 0.01) {
                tmpx = 0;
                tmpy = 0.16 * y;
            } else if (r <= 0.08) {
                tmpx = 0.2 * x - 0.26 * y;
                tmpy = 0.23 * x + 0.22 * y + 1.6;
            } else if (r <= 0.15) {
                tmpx = -0.15 * x + 0.28 * y;
                tmpy = 0.26 * x + 0.24 * y + 0.44;
            } else {
                tmpx = 0.85 * x + 0.04 * y;
                tmpy = -0.04 * x + 0.85 * y + 1.6;
            }
            x = tmpx;
            y = tmpy;

            img.setRGB((int) Math.round(w / 2 + x * w / 11),
                    (int) Math.round(h - y * h / 11), 0xFF32CD32);
        }
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        g.drawImage(img, 0, 0, null);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Barnsley Fern");
            f.setResizable(false);
            f.add(new BarnsleyFern(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}


function binary_search(array, value, left, right,       middle) {
    if (right < left) return 0
    middle = int((right + left) / 2)
    if (value == array[middle]) return 1
    if (value <  array[middle])
        return binary_search(array, value, left, middle - 1)
    return binary_search(array, value, middle + 1, right)
}


// Barnsley fern fractal
//6/17/16 aev
function pBarnsleyFern(canvasId, lim) {
    // DCLs
    var canvas = document.getElementById(canvasId);
    var ctx = canvas.getContext("2d");
    var w = canvas.width;
    var h = canvas.height;
    var x = 0.,
        y = 0.,
        xw = 0.,
        yw = 0.,
        r;
    // Like in PARI/GP: return random number 0..max-1
    function randgp(max) {
        return Math.floor(Math.random() * max)
    }
    // Clean canvas
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, w, h);
    // MAIN LOOP
    for (var i = 0; i < lim; i++) {
        r = randgp(100);
        if (r <= 1) {
            xw = 0;
            yw = 0.16 * y;
        } else if (r <= 8) {
            xw = 0.2 * x - 0.26 * y;
            yw = 0.23 * x + 0.22 * y + 1.6;
        } else if (r <= 15) {
            xw = -0.15 * x + 0.28 * y;
            yw = 0.26 * x + 0.24 * y + 0.44;
        } else {
            xw = 0.85 * x + 0.04 * y;
            yw = -0.04 * x + 0.85 * y + 1.6;
        }
        x = xw;
        y = yw;
        ctx.fillStyle = "green";
        ctx.fillRect(x * 50 + 260, -y * 50 + 540, 1, 1);
    } //fend i
}


Lbl BSEARCH
0→L
r₃-1→H
While L≤H
 (L+H)/2→M
 If {L+M}>r₂
  M-1→H
 ElseIf {L+M}<r₂
  M+1→L
 Else
  M
  Return
 End
End
-1
Return


// version 1.1.0

import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*

class BarnsleyFern(private val dim: Int) : JPanel() {
    private val img: BufferedImage

    init {
        preferredSize = Dimension(dim, dim)
        background = Color.black
        img = BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)
        createFern(dim, dim)
    }

    private fun createFern(w: Int, h: Int) {
        var x = 0.0
        var y = 0.0
        for (i in 0 until 200_000) {
            var tmpx: Double
            var tmpy: Double
            val r = Math.random()
            if (r <= 0.01) {
                tmpx = 0.0
                tmpy = 0.16 * y
            }
            else if (r <= 0.86) {
                tmpx =  0.85 * x + 0.04 * y
                tmpy = -0.04 * x + 0.85 * y + 1.6
            }
            else if (r <= 0.93) {
                tmpx = 0.2  * x - 0.26 * y
                tmpy = 0.23 * x + 0.22 * y + 1.6
            }
            else {
                tmpx = -0.15 * x + 0.28 * y
                tmpy =  0.26 * x + 0.24 * y + 0.44
            }
            x = tmpx
            y = tmpy
            img.setRGB(Math.round(w / 2.0 + x * w / 11.0).toInt(),
                       Math.round(h - y * h / 11.0).toInt(), 0xFF32CD32.toInt())
        }
    }

    override protected fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.drawImage(img, 0, 0, null)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "Barnsley Fern"
        f.setResizable(false)
        f.add(BarnsleyFern(640), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.setVisible(true)
    }
}


FUNCTION binary_search ( array() AS Integer, value AS Integer, lo AS Integer, hi AS Integer) AS Integer
  DIM middle AS Integer

  IF hi < lo THEN
    binary_search = 0
  ELSE
    middle = (hi + lo) / 2
    SELECT CASE value
      CASE IS < array(middle)
	binary_search = binary_search(array(), value, lo, middle-1)
      CASE IS > array(middle)
	binary_search = binary_search(array(), value, middle+1, hi)
      CASE ELSE
	binary_search = middle
    END SELECT
  END IF
END FUNCTION


{def fern
 {lambda {:size :sign}
  {if {> :size 2}
   then M:size
        T{* 70 :sign}
          {fern {* :size 0.5} {- :sign}}
        T{* {- 70} :sign}
        M:size
        T{* {- 70} :sign}
          {fern {* :size 0.5} :sign}
        T{* 70 :sign}
        T{* 7 :sign}
          {fern {- :size 1} :sign}
        T{* {- 7} :sign}
        M{* -:size 2}
   else }}}

{def F {fern 25 1}}


nomainwin
WindowWidth=800
WindowHeight=600
open "Barnsley Fern" for graphics_nf_nsb as #1
#1 "trapclose [q];down;fill black;flush;color green"

for n = 1 To WindowHeight * 50
    r = int(rnd(1)*100)
    Select Case
      Case (r>=0) and (r<=84)
        xn=0.85*x+0.04*y
        yn=-0.04*x+0.85*y+1.6
      Case (r>84) and (r<=91)
        xn=0.2*x-0.26*y
        yn=0.23*x+0.22*y+1.6
      Case (r>91) and (r<=98)
        xn=-0.15*x+0.28*y
        yn=0.26*x+0.24*y+0.44
      Case Else
        xn=0
        yn=0.16*y
    End Select
    x=xn
    y = yn
    #1 "set ";x*80+300;" ";WindowHeight/1.1-y*50
  next n
  #1 "flush"
  wait
[q]
close #1


function binarySearchR(array, valor, lb, ub)
    if ub < lb then
        return false
    else
        mitad = floor((lb + ub) / 2)
        if valor < array[mitad] then return binarySearchR(array, valor, lb, mitad-1)
        if valor > array[mitad] then return binarySearchR(array, valor, mitad+1, ub)
        if valor = array[mitad] then return mitad
    end if
end function


g = love.graphics
wid, hei = g.getWidth(), g.getHeight()

function choose( i, j )
  local r = math.random()
  if r < .01 then return 0, .16 * j
    elseif r < .07 then return .2 * i - .26 * j, .23 * i + .22 * j + 1.6
    elseif r < .14 then return -.15 * i + .28 * j, .26 * i + .24 * j + .44
    else return .85 * i + .04 * j, -.04 * i + .85 * j + 1.6
  end
end
function createFern( iterations )
  local hw, x, y, scale = wid / 2, 0, 0, 45
  local pts = {}
  for k = 1, iterations do
    pts[1] = { hw + x * scale, hei - 15 - y * scale,
               20 + math.random( 80 ),
               128 + math.random( 128 ),
               20 + math.random( 80 ), 150 }
    g.points( pts )
    x, y = choose( x, y )
  end
end
function love.load()
  math.randomseed( os.time() )
  canvas = g.newCanvas( wid, hei )
  g.setCanvas( canvas )
  createFern( 15e4 )
  g.setCanvas()
end
function love.draw()
  g.draw( canvas )
end


@echo off & setlocal enabledelayedexpansion

:: Binary Chop Algorithm - Michael Sanders 2017
::
:: example output...
::
:: binary chop algorithm vs. standard for loop
::
:: number to find 941
:: for loop required 941 iterations
:: binchop required 10 iterations

:setup

   set x=1
   set y=999
   set /a z=(%random% * (%y% - 1) / 32768 + 1)

:pseudoarray

   for /l %%q in (%x%,1,%y%) do set /a array[%%q]=%%q

:std4loop

   for /l %%q in (%x%,1,%y%) do (
      if !array[%%q]!==%z% (set f=%%q& goto :binchop)
   )

:binchop

   if !x! leq !y! (
      set /a i+=1
      set /a "p=(!x!+!y!)/2"
      call set /a t=%%array[!p!]%%
      if !t! equ !z! (set b=!i!& goto :done)
      if !t! lss !z! (set /a x=!p!+1) else (set /a y=!p!-1)
      goto :binchop
   )

:done

   cls
   echo binary chop algorithm vs. standard for loop...
   echo.
   echo . number to find !z!
   echo . for loop required !f! iterations
   echo . binchop required !b! iterations
   endlocal & exit /b 0


import nimPNG, random

randomize()

const
  width = 640
  height = 640
  minX = -2.1815
  maxX = 2.6556
  minY = 0.0
  maxY = 9.9982
  iterations = 1_000_000

var img: array[width * height * 3, char]

proc floatToPixel(x,y:float): tuple[a:int,b:int] =
  var px = abs(x - minX) / abs(maxX - minX)
  var py = abs(y - minY) / abs(maxY - minY)

  var a:int = (int)(width * px)
  var b:int = (int)(height * py)

  a = a.clamp(0, width-1)
  b = b.clamp(0, height-1)
  # flip the y axis
  (a:a,b:height-b-1)

proc pixelToOffset(a,b: int): int =
  b * width * 3 + a * 3

proc toString(a: openArray[char]): string =
  result = newStringOfCap(a.len)

  for ch in items(a):
    result.add(ch)

proc drawPixel(x,y:float) =
  var (a,b) = floatToPixel(x,y)
  var offset = pixelToOffset(a,b)

  #img[offset] = 0 # red channel
  img[offset+1] = char(250) # green channel
  #img[offset+2] = 0 # blue channel

# main
var x, y: float = 0.0

for i in 1..iterations:
  var r = random(101)
  var nx, ny: float
  if r <= 85:
    nx = 0.85 * x + 0.04 * y
    ny = -0.04 * x + 0.85 * y + 1.6
  elif r <= 85 + 7:
    nx = 0.2 * x - 0.26 * y
    ny = 0.23 * x + 0.22 * y + 1.6
  elif r <= 85 + 7 + 7:
    nx = -0.15 * x + 0.28 * y
    ny = 0.26 * x + 0.24 * y + 0.44
  else:
    nx = 0
    ny = 0.16 * y

  x = nx
  y = ny

  drawPixel(x,y)

discard savePNG24("fern.png",img.toString, width, height)


BSearch ← {
  BS ⟨a, value⟩:
  BS ⟨a, value, 0, ¯1+≠a⟩;
  BS ⟨a, value, low, high⟩:
  mid ← ⌊2÷˜low+high
  {
    high<low ? ¯1;
    (mid⊑a)>value ? BS ⟨a, value, low, mid-1⟩;
    (mid⊑a)<value ? BS ⟨a, value, mid+1, high⟩;
    mid
  }
}

•Show BSearch ⟨8‿30‿35‿45‿49‿77‿79‿82‿87‿97, 97⟩


binary_search = { search_array, value, low, high |
  true? high < low
    { null }
    {
      mid = ((low + high) / 2).to_i

      true? search_array[mid] > value
        { binary_search search_array, value, low, mid - 1 }
	{ true? search_array[mid] < value
	  { binary_search search_array, value, mid + 1, high }
	  { mid }
      }
   }
}

#Populate array
numbers = 1000.of { random 1000 }

#Sort the array
numbers.sort!

#Find a number
x = random 1000

p "Looking for #{x}"

index = binary_search numbers, x, 0, numbers.length - 1

null? index
	{ p "Not found" }
	{ p "Found at index: #{index}" }


#include <stdio.h>

int bsearch (int *a, int n, int x) {
    int i = 0, j = n - 1;
    while (i <= j) {
        int k = i + ((j - i) / 2);
        if (a[k] == x) {
            return k;
        }
        else if (a[k] < x) {
            i = k + 1;
        }
        else {
            j = k - 1;
        }
    }
    return -1;
}

int bsearch_r (int *a, int x, int i, int j) {
    if (j < i) {
        return -1;
    }
    int k = i + ((j - i) / 2);
    if (a[k] == x) {
        return k;
    }
    else if (a[k] < x) {
        return bsearch_r(a, x, k + 1, j);
    }
    else {
        return bsearch_r(a, x, i, k - 1);
    }
}

int main () {
    int a[] = {-31, 0, 1, 2, 2, 4, 65, 83, 99, 782};
    int n = sizeof a / sizeof a[0];
    int x = 2;
    int i = bsearch(a, n, x);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    x = 5;
    i = bsearch_r(a, x, 0, n - 1);
    if (i >= 0)
      printf("%d is at index %d.\n", x, i);
    else
      printf("%d is not found.\n", x);
    return 0;
}


namespace Search {
  using System;

  public static partial class Extensions {
    /// Use Binary Search to find index of GLB for value
    /// <typeparam name="T">type of entries and value</typeparam>
    /// <param name="entries">array of entries</param>
    /// <param name="value">search value</param>
    /// <remarks>entries must be in ascending order</remarks>
    /// <returns>index into entries of GLB for value</returns>
    public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value)
      where T : IComparable {
      return entries.RecursiveBinarySearchForGLB(value, 0, entries.Length - 1);
    }

    /// Use Binary Search to find index of GLB for value
    /// <typeparam name="T">type of entries and value</typeparam>
    /// <param name="entries">array of entries</param>
    /// <param name="value">search value</param>
    /// <param name="left">leftmost index to search</param>
    /// <param name="right">rightmost index to search</param>
    /// <remarks>entries must be in ascending order</remarks>
    /// <returns>index into entries of GLB for value</returns>
    public static int RecursiveBinarySearchForGLB<T>(this T[] entries, T value, int left, int right)
      where T : IComparable {
      if (left <= right) {
        var middle = left + (right - left) / 2;
        return entries[middle].CompareTo(value) < 0 ?
          entries.RecursiveBinarySearchForGLB(value, middle + 1, right) :
          entries.RecursiveBinarySearchForGLB(value, left, middle - 1);
      }

      //[Assert]left == right + 1
      // GLB: entries[right] < value && value <= entries[right + 1]
      return right;
    }

    /// Use Binary Search to find index of LUB for value
    /// <typeparam name="T">type of entries and value</typeparam>
    /// <param name="entries">array of entries</param>
    /// <param name="value">search value</param>
    /// <remarks>entries must be in ascending order</remarks>
    /// <returns>index into entries of LUB for value</returns>
    public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value)
      where T : IComparable {
      return entries.RecursiveBinarySearchForLUB(value, 0, entries.Length - 1);
    }

    /// Use Binary Search to find index of LUB for value
    /// <typeparam name="T">type of entries and value</typeparam>
    /// <param name="entries">array of entries</param>
    /// <param name="value">search value</param>
    /// <param name="left">leftmost index to search</param>
    /// <param name="right">rightmost index to search</param>
    /// <remarks>entries must be in ascending order</remarks>
    /// <returns>index into entries of LUB for value</returns>
    public static int RecursiveBinarySearchForLUB<T>(this T[] entries, T value, int left, int right)
      where T : IComparable {
      if (left <= right) {
        var middle = left + (right - left) / 2;
        return entries[middle].CompareTo(value) <= 0 ?
          entries.RecursiveBinarySearchForLUB(value, middle + 1, right) :
          entries.RecursiveBinarySearchForLUB(value, left, middle - 1);
      }

      //[Assert]left == right + 1
      // LUB: entries[left] > value && value >= entries[left - 1]
      return left;
    }
  }
}


template <class T> int binsearch(const T array[], int low, int high, T value) {
    if (high < low) {
        return -1;
    }
    auto mid = (low + high) / 2;
    if (value < array[mid]) {
        return binsearch(array, low, mid - 1, value);
    } else if (value > array[mid]) {
        return binsearch(array, mid + 1, high, value);
    }
    return mid;
}

#include <iostream>
int main()
{
  int array[] = {2, 3, 5, 6, 8};
  int result1 = binsearch(array, 0, sizeof(array)/sizeof(int), 4),
      result2 = binsearch(array, 0, sizeof(array)/sizeof(int), 8);
  if (result1 == -1) std::cout << "4 not found!" << std::endl;
  else std::cout << "4 found at " << result1 << std::endl;
  if (result2 == -1) std::cout << "8 not found!" << std::endl;
  else std::cout << "8 found at " << result2 << std::endl;

  return 0;
}


--
-- pwa\phix\BarnsleyFern.exw
-- =========================
--
with javascript_semantics
include pGUI.e

Ihandle dlg, canvas
cdCanvas cddbuffer, cdcanvas

function redraw_cb(Ihandle /*canvas*/, integer /*posx*/, integer /*posy*/)
    atom x = 0, y = 0
    integer {width, height} = IupGetIntInt(canvas, "DRAWSIZE")
    cdCanvasActivate(cddbuffer)
    for i=1 to 100000 do
        integer r = rand(100)
--      {x, y} = iff(r<=1? {             0,        0.16*y     } :
--               iff(r<=8? { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60} :
--               iff(r<=15?{-0.15*x+0.28*y, 0.26*x+0.24*y+0.44} :
--                         { 0.85*x+0.04*y,-0.04*x+0.85*y+1.60})))
        if r<=1 then        {x, y} = {             0,        0.16*y     }
        elsif r<=8 then     {x, y} = { 0.20*x-0.26*y, 0.23*x+0.22*y+1.60}
        elsif r<=15 then    {x, y} = {-0.15*x+0.28*y, 0.26*x+0.24*y+0.44}
        else                {x, y} = { 0.85*x+0.04*y,-0.04*x+0.85*y+1.60}
        end if
        cdCanvasPixel(cddbuffer, width/2+x*50, y*50, CD_DARK_GREEN)
    end for
    cdCanvasFlush(cddbuffer)
    return IUP_DEFAULT
end function

IupOpen()

canvas = IupCanvas(Icallback("redraw_cb"),"RASTERSIZE=340x540")
dlg = IupDialog(canvas,`TITLE="Barnsley Fern"`)

IupMap(dlg)
cdcanvas = cdCreateCanvas(CD_IUP, canvas)
cddbuffer = cdCreateCanvas(CD_DBUFFER, cdcanvas)
IupSetAttribute(canvas, "RASTERSIZE", NULL) -- release the minimum limitation
IupShow(dlg)
if platform()!=JS then
    IupMainLoop()
    IupClose()
end if


proc binsearch(A:[], value) {
        var low = A.domain.dim(1).low;
        var high = A.domain.dim(1).high;
        while (low <= high) {
                var mid = (low + high) / 2;

                if A(mid) > value then
                        high = mid - 1;
                else if A(mid) < value then
                        low = mid + 1;
                else
                        return mid;
        }
        return 0;
}

writeln(binsearch([3, 4, 6, 9, 11], 9));


(defn bsearch
  ([coll t]
    (bsearch coll 0 (dec (count coll)) t))
  ([coll l u t]
    (if (> l u) -1
      (let [m (quot (+ l u) 2) mth (nth coll m)]
        (cond
          ; the middle element is greater than t
          ; so search the lower half
          (> mth t) (recur coll l (dec m) t)
          ; the middle element is less than t
          ; so search the upper half
          (< mth t) (recur coll (inc m) u t)
          ; we've found our target
          ; so return its index
          (= mth t) m)))))


% Binary search in an array
% If the item is found, returns `true' and the index;
% if the item is not found, returns `false' and the leftmost insertion point
% The datatype must support the < and > operators.
binary_search = proc [T: type] (a: array[T], val: T) returns (bool, int)
                where T has lt: proctype (T,T) returns (bool),
                      T has gt: proctype (T,T) returns (bool)
    low: int := array[T]$low(a)
    high: int := array[T]$high(a)

    while low <= high do
        mid: int := low + (high - low) / 2
        if a[mid] > val then
            high := mid - 1
        elseif a[mid] < val then
            low := mid + 1
        else
            return (true, mid)
        end
    end
    return (false, low)
end binary_search

% Test the binary search on an array
start_up = proc ()
    po: stream := stream$primary_output()

    % primes up to 20 (note that arrays are 1-indexed by default)
    primes: array[int] := array[int]$[2,3,5,7,11,13,17,19]

    % binary search for each number from 1 to 20
    for n: int in int$from_to(1,20) do
        i: int
        found: bool
        found, i := binary_search[int](primes, n)

        if found then
            stream$putl(po, int$unparse(n)
                            || " found at location "
                            || int$unparse(i));
        else
            stream$putl(po, int$unparse(n)
                            || " not found, would be inserted at location "
                            || int$unparse(i));
        end
    end
end start_up


        >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. binary-search.

DATA DIVISION.
WORKING-STORAGE SECTION.
01  nums-area                           VALUE "01040612184356".
    03  nums                            PIC 9(2)
                                        OCCURS 7 TIMES
                                        ASCENDING KEY nums
                                        INDEXED BY nums-idx.
PROCEDURE DIVISION.
    SEARCH ALL nums
        WHEN nums (nums-idx) = 4
            DISPLAY "Found 4 at index " nums-idx
    END-SEARCH
    .
END PROGRAM binary-search.


EnableExplicit
DisableDebugger

DataSection
  R84:  : Data.d 0.85,0.04,-0.04,0.85,1.6
  R91:  : Data.d 0.2,-0.26,0.23,0.22,1.6
  R98:  : Data.d -0.15,0.28,0.26,0.24,0.44
  R100: : Data.d 0.0,0.0,0.0,0.16,0.0
EndDataSection

Procedure Barnsley(height.i)
  Define x.d, y.d, xn.d, yn.d, v1.d, v2.d, v3.d, v4.d, v5.d,
         f.d=height/10.6,
         offset.i=Int(height/4-height/40),
         n.i, r.i
  For n=1 To height*50
    r=Random(99,0)
    Select r
      Case 0 To 84  : Restore R84
      Case 85 To 91 : Restore R91
      Case 92 To 98 : Restore R98
      Default       : Restore R100
    EndSelect
    Read.d v1 : Read.d v2 : Read.d v3 : Read.d v4 : Read.d v5
    xn=v1*x+v2*y : yn=v3*x+v4*y+v5
    x=xn : y=yn
    Plot(offset+x*f,height-y*f,RGB(0,255,0))
  Next
EndProcedure

Define w1.i=400,
       h1.i=800

If OpenWindow(0,#PB_Ignore,#PB_Ignore,w1,h1,"Barnsley fern")
  If CreateImage(0,w1,h1,24,0) And StartDrawing(ImageOutput(0))
    Barnsley(h1)
    StopDrawing()
  EndIf
  ImageGadget(0,0,0,0,0,ImageID(0))
  Repeat : Until WaitWindowEvent(50)=#PB_Event_CloseWindow
EndIf
End


binarySearch = (xs, x) ->
  do recurse = (low = 0, high = xs.length - 1) ->
    mid = Math.floor (low + high) / 2
    switch
      when high < low then NaN
      when xs[mid] > x then recurse low, mid - 1
      when xs[mid] < x then recurse mid + 1, high
      else mid


import random
from PIL import Image

class BarnsleyFern(object):
    def __init__(self, img_width, img_height, paint_color=(0, 150, 0),
                 bg_color=(255, 255, 255)):
        self.img_width, self.img_height = img_width, img_height
        self.paint_color = paint_color
        self.x, self.y = 0, 0
        self.age = 0

        self.fern = Image.new('RGB', (img_width, img_height), bg_color)
        self.pix = self.fern.load()
        self.pix[self.scale(0, 0)] = paint_color

    def scale(self, x, y):
        h = (x + 2.182)*(self.img_width - 1)/4.8378
        k = (9.9983 - y)*(self.img_height - 1)/9.9983
        return h, k

    def transform(self, x, y):
        rand = random.uniform(0, 100)
        if rand < 1:
            return 0, 0.16*y
        elif 1 <= rand < 86:
            return 0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6
        elif 86 <= rand < 93:
            return 0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6
        else:
            return -0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44

    def iterate(self, iterations):
        for _ in range(iterations):
            self.x, self.y = self.transform(self.x, self.y)
            self.pix[self.scale(self.x, self.y)] = self.paint_color
        self.age += iterations

fern = BarnsleyFern(500, 500)
fern.iterate(1000000)
fern.fern.show()


(defun binary-search (value array)
  (let ((low 0)
        (high (1- (length array))))

    (do () ((< high low) nil)
      (let ((middle (floor (+ low high) 2)))

        (cond ((> (aref array middle) value)
               (setf high (1- middle)))

              ((< (aref array middle) value)
               (setf low (1+ middle)))

              (t (return middle)))))))


_Title "Barnsley Fern"
Dim As Integer sw, sh
sw = 400: sh = 600
Screen _NewImage(sw, sh, 8)

Dim As Long i, ox, oy
Dim As Single sRand
Dim As Double x, y, x1, y1, sx, sy
sx = 60: sy = 59
ox = 180: oy = 4
Randomize Timer

x = 0
y = 0
For i = 1 To 400000
    sRand = Rnd
    Select Case sRand
        Case Is < 0.01
            x1 = 0: y1 = 0.16 * y
        Case Is < 0.08
            x1 = 0.2 * x - 0.26 * y: y1 = 0.23 * x + 0.22 * y + 1.6
        Case Is < 0.15
            x1 = -0.15 * x + 0.28 * y: y1 = 0.26 * x + 0.24 * y + 0.44
        Case Else
            x1 = 0.85 * x + 0.04 * y: y1 = -0.04 * x + 0.85 * y + 1.6
    End Select
    x = x1
    y = y1
    PSet (x * sx + ox, sh - (y * sy) - oy), 10
Next

Sleep
System


## pBarnsleyFern(fn, n, clr, ttl, psz=600): Plot Barnsley fern fractal.
## Where: fn - file name; n - number of dots; clr - color; ttl - plot title;
## psz - picture size.
## 7/27/16 aev
pBarnsleyFern <- function(fn, n, clr, ttl, psz=600) {
  cat(" *** START:", date(), "n=", n, "clr=", clr, "psz=", psz, "\n");
  cat(" *** File name -", fn, "\n");
  pf = paste0(fn,".png"); # pf - plot file name
  A1 <- matrix(c(0,0,0,0.16,0.85,-0.04,0.04,0.85,0.2,0.23,-0.26,0.22,-0.15,0.26,0.28,0.24), ncol=4, nrow=4, byrow=TRUE);
  A2 <- matrix(c(0,0,0,1.6,0,1.6,0,0.44), ncol=2, nrow=4, byrow=TRUE);
  P <- c(.01,.85,.07,.07);
  # Creating matrices M1 and M2.
  M1=vector("list", 4); M2 = vector("list", 4);
  for (i in 1:4) {
    M1[[i]] <- matrix(c(A1[i,1:4]), nrow=2);
    M2[[i]] <- matrix(c(A2[i, 1:2]), nrow=2);
  }
  x <- numeric(n); y <- numeric(n);
  x[1] <- y[1] <- 0;
  for (i in 1:(n-1)) {
    k <- sample(1:4, prob=P, size=1);
    M <- as.matrix(M1[[k]]);
    z <- M%*%c(x[i],y[i]) + M2[[k]];
    x[i+1] <- z[1]; y[i+1] <- z[2];
  }
  plot(x, y, main=ttl, axes=FALSE, xlab="", ylab="", col=clr, cex=0.1);
  # Writing png-file
  dev.copy(png, filename=pf,width=psz,height=psz);
  # Cleaning
  dev.off(); graphics.off();
  cat(" *** END:",date(),"\n");
}
## Executing:
pBarnsleyFern("BarnsleyFernR", 100000, "dark green", "Barnsley Fern Fractal", psz=600)


class Array
  def binary_search(val, low = 0, high = (size - 1))
    return nil if high < low
    #mid = (low + high) >> 1
    mid = low + ((high - low) >> 1)
    case val <=> self[mid]
      when -1
        binary_search(val, low, mid - 1)
      when 1
        binary_search(val, mid + 1, high)
      else mid
    end
  end
end

ary = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]

[0, 42, 45, 24324, 99999].each do |val|
  i = ary.binary_search(val)
  if i
    puts "found #{val} at index #{i}: #{ary[i]}"
  else
    puts "#{val} not found in array"
  end
end


#lang racket

(require racket/draw)

(define fern-green (make-color #x32 #xCD #x32 0.66))

(define (fern dc n-iterations w h)
  (for/fold ((x #i0) (y #i0))
            ((i n-iterations))
    (define-values (x′ y′)
      (let ((r (random)))
        (cond
          [(<= r 0.01) (values 0
                               (* y 16/100))]
          [(<= r 0.08) (values (+ (* x 20/100) (* y -26/100))
                               (+ (* x 23/100) (* y 22/100) 16/10))]
          [(<= r 0.15) (values (+ (* x -15/100) (* y 28/100))
                               (+ (* x 26/100) (* y 24/100) 44/100))]
          [else (values (+ (* x 85/100) (* y 4/100))
                        (+ (* x -4/100) (* y 85/100) 16/10))])))

    (define px (+ (/ w 2) (* x w 1/11)))
    (define py (- h (* y h 1/11)))
    (send dc set-pixel (exact-round px) (exact-round py) fern-green)
    (values x′ y′)))

(define bmp (make-object bitmap% 640 640 #f #t 2))

(fern (new bitmap-dc% [bitmap bmp]) 200000 640 640)

bmp
(send bmp save-file "images/racket-barnsley-fern.png" 'png)


import std.stdio, std.array, std.range, std.traits;

/// Recursive.
bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
    if (data.empty)
        return false;
    immutable i = data.length / 2;
    immutable mid = data[i];
    if (mid > x)
        return data[0 .. i].binarySearch(x);
    if (mid < x)
        return data[i + 1 .. $].binarySearch(x);
    return true;
}

/// Iterative.
bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc
if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) {
    while (!data.empty) {
        immutable i = data.length / 2;
        immutable mid = data[i];
        if (mid > x)
            data = data[0 .. i];
        else if (mid < x)
            data = data[i + 1 .. $];
        else
            return true;
    }
    return false;
}

void main() {
    /*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted;
    foreach (const x; [1, 8, 10, 9, 5, 2])
        writefln("%2d %5s %5s %5s", x,
                 items.binarySearch(x),
                 items.binarySearchIt(x),
                 // Standard Binary Search:
                 !items.equalRange(x).empty);
}


/*REXX pgm gens X & Y coördinates for a scatter plot to be used to show a Barnsley fern.*/
parse arg N FID seed .                           /*obtain optional arguments from the CL*/
if   N=='' |   N==","  then   N= 100000          /*Not specified?   Then use the default*/
if FID=='' | FID==","  then FID= 'BARNSLEY.DAT'  /* "      "          "   "   "     "   */
if datatype(seed,'W')  then call random ,,seed   /*if specified, then use random seed.  */
call lineout FID, , 1                            /*just set the file ptr to the 1st line*/
x=0                                              /*set the initial value for  X  coörd. */
y=0                                              /* "   "     "      "    "   Y    "    */
    do #=1  for N                                /*generate   N   number of plot points.*/
    ?=random(, 100)                              /*generate a random number: 0 ≤ ? ≤ 100*/
       select
       when ?==0  then do;   xx=   0           ;    yy=            .16*y         ;     end
       when ?< 8  then do;   xx=  .2 *x - .26*y;    yy=  .23*x  +  .22*y  +  1.6 ;     end
       when ?<15  then do;   xx= -.15*x + .28*y;    yy=  .26*x  +  .24*y  +   .44;     end
       otherwise             xx=  .85*x + .04*y;    yy= -.04*x  +  .85*y  +  1.6
       end   /*select*/
                             x=xx;                     y=yy
    if #==1  then  do;    minx= x;  maxx= x;        miny= y;  maxy= y
                   end
                          minx= min(minx, x);       miny= min(miny, y)
                          maxx= max(maxx, x);       maxy= max(maxy, y)
    call lineout FID, x","y
    end      /*#*/                               /* [↓]  close the file (safe practice).*/
call lineout FID                                 /*stick a fork in it,  we're all done. */


/** Returns null if the value is not found. */
def binarySearch(collection, value) {
    var low := 0
    var high := collection.size() - 1
    while (low <= high) {
        def mid := (low + high) // 2
        def comparison := value.op__cmp(collection[mid])
        if      (comparison.belowZero()) { high := mid - 1 } \
        else if (comparison.aboveZero()) { low := mid + 1 }  \
        else if (comparison.isZero())    { return mid }      \
        else                             { throw("You expect me to binary search with a partial order?") }
    }
    return null
}


MAX_ITERATIONS = 200_000

def setup
  sketch_title 'Barnsley Fern'
  no_loop
  puts 'Be patient. This takes about 10 seconds to render.'
end

def draw
  background 0
  load_pixels
  x0 = 0.0
  y0 = 0.0
  x = 0.0
  y = 0.0
  MAX_ITERATIONS.times do
    r = rand(100)
    if r < 85
      x = 0.85 * x0 + 0.04 * y0
      y = -0.04 * x0 + 0.85 * y0 + 1.6
    elsif r < 92
      x = 0.2 * x0 - 0.26 * y0
      y = 0.23 * x0 + 0.22 * y0 + 1.6
    elsif r < 99
      x = -0.15 * x0 + 0.28 * y0
      y = 0.26 * x0 + 0.24 * y0 + 0.44
    else
      x = 0
      y = 0.16 * y
    end
    i = height - (y * 48).to_i
    j = width / 2 + (x * 48).to_i
    pixels[i * height + j] += 2_560
    x0 = x
    y0 = y
  end
  update_pixels
end

def settings
  size 500, 500
end


'Barnsley Fern - Run BASIC
  'http://rosettacode.org/wiki/Barnsley_fern#Run_BASIC
  'copy code and run it at http://www.runbasic.com
  '
  ' -----------------------------------
  ' Barnsley Fern
  ' -----------------------------------maxpoints	= 20000
graphic #g, 200, 200
#g fill("blue")
FOR n	= 1 TO maxpoints
p	= RND(0)*100
IF p <= 1 THEN
	nx	= 0
	ny	= 0.16 * y
else if p <= 8 THEN
	nx	= 0.2 * x - 0.26 * y
	ny	= 0.23 * x + 0.22 * y + 1.6
else if p <= 15 THEN
	nx	= -0.15 * x + 0.28 * y
	ny	= 0.26 * x + 0.24 * y + 0.44
else
	nx	= 0.85 * x +0.04 * y
	ny	= -0.04 * x +0.85 * y + 1.6
end if
x	= nx
y	= ny
#g "color green ; set "; x * 17 + 100; " "; y * 17

NEXT n
render #g
#g "flush"


extern crate rand;
extern crate raster;

use rand::Rng;

fn main() {
    let max_iterations = 200_000u32;
    let height = 640i32;
    let width = 640i32;

    let mut rng = rand::thread_rng();
    let mut image = raster::Image::blank(width, height);
    raster::editor::fill(&mut image, raster::Color::white()).unwrap();

    let mut x = 0.;
    let mut y = 0.;
    for _ in 0..max_iterations {
        let r = rng.gen::<f32>();
        let cx: f64;
        let cy: f64;

        if r <= 0.01 {
            cx = 0f64;
            cy = 0.16 * y as f64;
        } else if r <= 0.08 {
            cx = 0.2 * x as f64 - 0.26 * y as f64;
            cy = 0.23 * x as f64 + 0.22 * y as f64 + 1.6;
        } else if r <= 0.15 {
            cx = -0.15 * x as f64 + 0.28 * y as f64;
            cy = 0.26 * x as f64 + 0.26 * y as f64 + 0.44;
        } else {
            cx = 0.85 * x as f64 + 0.04 * y as f64;
            cy = -0.04 * x as f64 + 0.85 * y as f64 + 1.6;
        }
        x = cx;
        y = cy;

        let _ = image.set_pixel(
            ((width as f64) / 2. + x * (width as f64) / 11.).round() as i32,
            ((height as f64) - y * (height as f64) / 11.).round() as i32,
            raster::Color::rgb(50, 205, 50));
    }

    raster::save(&image, "fractal.png").unwrap();
}


import java.awt._
import java.awt.image.BufferedImage

import javax.swing._

object BarnsleyFern extends App {

  SwingUtilities.invokeLater(() =>
    new JFrame("Barnsley Fern") {

      private class BarnsleyFern extends JPanel {
        val dim = 640
        val img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)

        private def createFern(w: Int, h: Int): Unit = {
          var x, y = 0.0
          for (i <- 0 until 200000) {
            var tmpx, tmpy = .0
            val r = math.random
            if (r <= 0.01) {
              tmpx = 0
              tmpy = 0.16 * y
            }
            else if (r <= 0.08) {
              tmpx = 0.2 * x - 0.26 * y
              tmpy = 0.23 * x + 0.22 * y + 1.6
            }
            else if (r <= 0.15) {
              tmpx = -0.15 * x + 0.28 * y
              tmpy = 0.26 * x + 0.24 * y + 0.44
            }
            else {
              tmpx = 0.85 * x + 0.04 * y
              tmpy = -0.04 * x + 0.85 * y + 1.6
            }
            x = tmpx
            y = tmpy
            img.setRGB((w / 2 + tmpx * w / 11).round.toInt,
              (h - tmpy * h / 11).round.toInt, 0xFF32CD32)
          }
        }

        override def paintComponent(gg: Graphics): Unit = {
          super.paintComponent(gg)
          val g = gg.asInstanceOf[Graphics2D]
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
          g.drawImage(img, 0, 0, null)
        }

        setBackground(Color.white)
        setPreferredSize(new Dimension(dim, dim))
        createFern(dim, dim)
      }

      add(new BarnsleyFern, BorderLayout.CENTER)
      pack()
      setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
      setLocationRelativeTo(null)
      setResizable(false)
      setVisible(true)
    })

}


func bin_search val . a[] res .
  low = 0
  high = len a[] - 1
  res = -1
  while low <= high and res = -1
    mid = (low + high) div 2
    if a[mid] > val
      high = mid - 1
    elif a[mid] < val
      low = mid + 1
    else
      res = mid
    .
  .
.
a[] = [ 2 4 6 8 9 ]
call bin_search 8 a[] r
print r


class
	APPLICATION

create
	make

feature {NONE} -- Initialization

	make
		local
			a: ARRAY [INTEGER]
			keys: ARRAY [INTEGER]
		do
			a := <<0, 1, 4, 5, 6, 7, 8, 9,
			       12, 26, 45, 67, 78, 90,
			       98, 123, 211, 234, 456,
			       769, 865, 2345, 3215,
			       14345, 24324>>
			keys := <<0, 42, 45, 24324, 99999>>
			across keys as k loop
				if has_binary (a, k.item) then
					print ("The array has an element " + k.item.out)
				else
					print ("The array has NOT an element " + k.item.out)
				end
				print ("%N")
			end
		end

feature -- Search

	has_binary (a: ARRAY [INTEGER]; key: INTEGER): BOOLEAN
		-- Does `a[a.lower..a.upper]' include an element `key'?
		require
			is_sorted (a, a.lower, a.upper)
		local
			i: INTEGER
		do
			i := where_binary (a, key)
			if a.lower <= i and i <= a.upper then
				Result := True
			else
				Result := False
			end
		end

	where_binary (a: ARRAY [INTEGER]; key: INTEGER): INTEGER
		-- The index of an element `key' within `a[a.lower..a.upper]' if it exists.
		-- Otherwise an integer outside `[a.lower..a.upper]'
		require
			is_sorted (a, a.lower, a.upper)
		do
			Result := where_binary_range (a, key, a.lower, a.upper)
		end

	where_binary_range (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): INTEGER
		-- The index of an element `key' within `a[low..high]' if it exists.
		-- Otherwise an integer outside `[low..high]'
		note
			source: "http://arxiv.org/abs/1211.4470"
		require
			is_sorted (a, low, high)
		local
			i, j, mid: INTEGER
		do
			if low > high then
				Result := low - 1
			else
				from
					i := low
					j := high
					mid := low
					Result := low - 1
				invariant
					low <= i and i <= mid + 1
					low <= mid and mid <= j and j <= high
					i <= j
					has (a, key, i, j) = has (a, key, low, high)
				until
					i >= j
				loop
					mid := i + (j - i) // 2
					if a [mid] < key then
						i := mid + 1
					else
						j := mid
					end
				variant
					j - i
				end
				if a [i] = key then
					Result := i
				end
			end
		ensure
			low <= Result and Result <= high implies a [Result] = key
			Result < low or Result > high implies not has (a, key, low, high)
		end

feature -- Implementation

	is_sorted (a: ARRAY [INTEGER]; low, high: INTEGER): BOOLEAN
		-- Is `a[low..high]' sorted in nondecreasing order?
		require
			a.lower <= low
			high <= a.upper
		do
			Result := across low |..| (high - 1) as i all a [i.item] <= a [i.item + 1] end
		end

	has (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): BOOLEAN
		-- Is there an element `key' in `a[low..high]'?
		require
			a.lower <= low
			high <= a.upper
		do
			Result := across low |..| high as i some a [i.item] = key end
		end

end


(import (scheme base)
        (scheme cxr)
        (scheme file)
        (scheme inexact)
        (scheme write)
        (srfi 27))     ; for random numbers

(define (create-fern x y num-points)
  (define (new-point xn yn)
    (let ((r (* 100 (random-real))))
      (cond ((< r 1) ; f1
             (list 0 (* 0.16 yn)))
            ((< r 86) ; f2
             (list (+ (* 0.85 xn) (* 0.04 yn))
                   (+ (* -0.04 xn) (* 0.85 yn) 1.6)))
            ((< r 93) ; f3
             (list (- (* 0.2 xn) (* 0.26 yn))
                   (+ (* 0.23 xn) (* 0.22 yn) 1.6)))
            (else ; f4
              (list (+ (* -0.15 xn) (* 0.28 yn))
                    (+ (* 0.26 xn) (* 0.24 yn) 0.44))))))
  ;
  (random-source-randomize! default-random-source)
  (do ((i 0 (+ i 1))
       (pts (list (list x y)) (cons (new-point (caar pts) (cadar pts)) pts)))
    ((= i num-points) pts)))

;; output the fern to an eps file
(define (output-fern-as-eps filename fern)
  (when (file-exists? filename) (delete-file filename))
  (with-output-to-file
    filename
    (lambda ()
      (let* ((width 600)
             (height 800)
             (min-x (apply min (map car fern)))
             (max-x (apply max (map car fern)))
             (min-y (apply min (map cadr fern)))
             (max-y (apply max (map cadr fern)))
             (scale-x (/ (- width 50) (- max-x min-x)))
             (scale-y (/ (- height 50) (- max-y min-y)))
             (scale-points (lambda (point)
                             (list (truncate (+ 20 (* scale-x (- (car point) min-x))))
                                   (truncate (+ 20 (* scale-y (- (cadr point) min-y))))))))

        (display
          (string-append "%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 "
                         (number->string width) " " (number->string height) "\n"))

        ;; add each point in fern as an arc - sets linewidth based on depth in tree
        (for-each (lambda (point)
                    (display
                      (string-append (number->string (list-ref point 0))
                                     " "
                                     (number->string (list-ref point 1))
                                     " 0.1 0 360 arc\nstroke\n")))
                  (map scale-points fern))
        (display "\n%%EOF")))))

(output-fern-as-eps "barnsley.eps" (create-fern 0 0 50000))


defmodule Binary do
  def search(list, value), do: search(List.to_tuple(list), value, 0, length(list)-1)

  def search(_tuple, _value, low, high) when high < low, do: :not_found
  def search(tuple, value, low, high) do
    mid = div(low + high, 2)
    midval = elem(tuple, mid)
    cond do
      value <  midval -> search(tuple, value, low, mid-1)
      value >  midval -> search(tuple, value, mid+1, high)
      value == midval -> mid
    end
  end
end

list = [0,1,4,5,6,7,8,9,12,26,45,67,78,90,98,123,211,234,456,769,865,2345,3215,14345,24324]
Enum.each([0,42,45,24324,99999], fn val ->
  case Binary.search(list, val) do
    :not_found -> IO.puts "#{val} not found in list"
    index      -> IO.puts "found #{val} at index #{index}"
  end
end)


iteractions=1.0d6;

XY=zeros(2,iteractions+1);
x=0;
y=0;

i=2;
while i<iteractions+2
    random_numbers=rand();
    xp=x;
    if random_numbers(1) < 0.01 then
        x = 0;
        y = 0.16 * y;
    elseif random_numbers(1) >= 0.01 & random_numbers(1) < 0.01+0.85 then
        x = 0.85 * x + 0.04 * y;
        y = -0.04 * xp + 0.85 * y + 1.6;
    elseif random_numbers(1) >= 0.86 & random_numbers(1) < 0.86+0.07 then
        x = 0.2 * x - 0.26 * y;
        y = 0.23 * xp + 0.22 * y + 1.6;
    else
        x = -0.15 * x + 0.28 * y;
        y = 0.26 * xp + 0.24 * y + 0.44;
    end

    XY(1,i)=x;
    XY(2,i)=y;

    i=i+1;
end

scf(0);
clf();
xname('Barnsley fern');
plot2d(XY(1,:),XY(2,:),-0)
axes=gca();
axes.isoview="on";
axes.children.children.mark_foreground=13;


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

transform(p(1), rand) :=
    let
        x := p[1]; y := p[2];
    in
        [0.0, 0.16*y] when rand <= 0.01
    else
        [0.85*x + 0.04*y, -0.04*x + 0.85*y + 1.6] when rand <= 0.86
    else
        [0.2*x - 0.26*y, 0.23*x + 0.22*y + 1.6] when rand <= 0.93
    else
        [-0.15*x + 0.28*y, 0.26*x + 0.24*y + 0.44];

barnsleyFern(rand, count, result(2)) :=
    let
        nextRand := getRandom(rand);
        next := transform(result[size(result)], nextRand.value / 2147483647.0);
    in
        result when count <= 0
    else
        barnsleyFern(nextRand.generator, count - 1, result ++ [next]);

scale(p(1), width, height) := [round((p[1] + 2.182) * width / 4.8378),
                               round((9.9983 - p[2]) * height / 9.9983)];

entry(seed, count, width, height) :=
    let
        fern := barnsleyFern(seedRandom(seed), count, [[0.0,0.0]]);
    in
        scale(fern, width, height);


(defun binary-search (value array)
  (let ((low 0)
        (high (1- (length array))))
    (cl-do () ((< high low) nil)
      (let ((middle (floor (+ low high) 2)))
        (cond ((> (aref array middle) value)
               (setf high (1- middle)))
              ((< (aref array middle) value)
               (setf low (1+ middle)))
              (t (cl-return middle)))))))


open XWindows ;
open Motif ;

val uniformdeviate = fn seed =>
 let
  val in31m = (Real.fromInt o Int32.toInt ) (getOpt (Int32.maxInt,0) );
  val in31 = in31m +1.0;
  val (s1,s2,v) = (41160.0 , 950665216.0 , Real.realFloor seed);
  val (val1,val2) = (v*s1, v*s2);
  val next1 = Real.fromLargeInt (Real.toLargeInt IEEEReal.TO_NEGINF (val1/in31)) ;
  val next2 = Real.rem(Real.realFloor(val2/in31) , in31m );
  val valt = val1+val2 - (next1+next2)*in31m;
  val nextt = Real.realFloor(valt/in31m);
  val valt = valt - nextt*in31m;
 in
  (valt/in31m,valt)
end;

local
 val sizeup = 60.0 ;
 fun toI {x=x,y=y} = {x=Real.toInt  IEEEReal.TO_NEAREST (sizeup *x),y=Real.toInt  IEEEReal.TO_NEAREST (sizeup*y)}  ;
 val next  = [  (fn {x=x,y=y} =>  {x= 0.0,           y= 0.16*y            })
              , (fn {x=x,y=y} =>  {x= 0.85*x+0.04*y, y= ~0.04*x+0.85*y+1.6})
              , (fn {x=x,y=y} =>  {x= 0.2*x-0.26*y,  y= 0.23*x+0.22*y+1.6 })
              , (fn {x=x,y=y} =>  {x= ~0.15*x+0.28*y,y= 0.26*x+0.24*y+0.44}) ] ;
 val seed  = ref 100027.0
in

 fun putNext  1 win usegc coord =  XFlush (XtDisplay win)
 |   putNext  N win usegc coord =
  let
   val (i,ns) =  uniformdeviate ( !seed ) ;
   val _      =  seed := ns  ;
   val fi     =  List.nth (next, List.foldr (fn (a,b) => b + (if i>a then 1 else 0)) 0 [0.1,0.86,0.93,1.0] )  ;
   val nwp    =  fi coord
  in
      (XDrawPoint (XtWindow win) usegc  ( AddPoint ((XPoint o toI) coord, XPoint {x=300,y=0}) )  ;
       putNext (N-1) win usegc nwp  )
  end

end;

val demoWindow = fn () =>
let
  val shell     =  XtAppInitialise      ""    "demo" "top" [] [ XmNwidth 600, XmNheight 700 ] ;
  val main      =  XmCreateMainWindow   shell    "main"       [ XmNmappedWhenManaged true ]  ;
  val canvas    =  XmCreateDrawingArea  main   "drawarea"     [ XmNwidth 600, XmNheight 700] ;
  val usegc     =  DefaultGC (XtDisplay canvas) ;
  val _         =  XSetForeground usegc 0x4a632d ;
  val drawall   =  fn (w,c,t)=> ( XClearWindow (XtWindow canvas ); putNext 1000000 canvas usegc {x=0.0,y=0.0} ; t )
in
  (
   XtSetCallbacks   canvas [ (XmNexposeCallback ,  drawall)  ] XmNarmCallback ;
   XtManageChild    canvas ;
   XtManageChild    main   ;
   XtRealizeWidget  shell
  )
end ;


import UIKit
import CoreImage
import PlaygroundSupport

let imageWH = 300
let context = CGContext(data: nil,
                        width: imageWH,
                        height: imageWH,
                        bitsPerComponent: 8,
                        bytesPerRow: 0,
                        space: CGColorSpace(name: CGColorSpace.sRGB)!,
                        bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)!
var x0 = 0.0
var x1 = 0.0
var y0 = 0.0
var y1 = 0.0

context.setFillColor(#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1))
context.fill(CGRect(x: 0, y: 0, width: imageWH, height: imageWH))
context.setFillColor(#colorLiteral(red: 0.539716677, green: 1, blue: 0.265400682, alpha: 1))

for _ in 0..<100_000 {
    switch Int(arc4random()) % 100 {
    case 0:
        x1 = 0
        y1 = 0.16 * y0
    case 1...7:
        x1 = -0.15 * x0 + 0.28 * y0
        y1 = 0.26 * x0 + 0.24 * y0 + 0.44
    case 8...15:
        x1 = 0.2 * x0 - 0.26 * y0
        y1 = 0.23 * x0 + 0.22 * y0 + 1.6
    default:
        x1 = 0.85 * x0 + 0.04 * y0
        y1 = -0.04 * x0 + 0.85 * y0 + 1.6
    }

    context.fill(CGRect(x: 30 * x1 + Double(imageWH) / 2.0, y: 30 * y1,
                        width: 1, height: 1))

    (x0, y0) = (x1, y1)
}

let uiImage = UIImage(cgImage: context.makeImage()!)


%% Task: Binary Search algorithm
%% Author: Abhay Jain

-module(searching_algorithm).
-export([start/0]).

start() ->
    List = [1,2,3],
    binary_search(List, 5, 1, length(List)).

binary_search(List, Value, Low, High) ->
    if Low > High ->
        io:format("Number ~p not found~n", [Value]),
        not_found;
       true ->
        Mid = (Low + High) div 2,
        MidNum = lists:nth(Mid, List),
        if MidNum > Value ->
            binary_search(List, Value, Low, Mid-1);
           MidNum < Value ->
            binary_search(List, Value, Mid+1, High);
           true ->
            io:format("Number ~p found at index ~p", [Value, Mid]),
            Mid
        end
    end.


link graphics

global x, y

procedure main()
    &window := open("FERN", "g", "size=400,400", "bg=black")

    x := y := 0

    repeat {
	draw()
	delay(30)
	if *Pending() > 0 then {
	    case Event() of {
	        "q"|"\e": return
            }
	}
    }
end

procedure next_point()
    local nx, ny, r

    nx := 0.0
    ny := 0.0

    r := ?100

    if r < 1 then {
	nx := 0.0
	ny := 0.16 * y
    } else if r < 86 then {
	nx := 0.85 * x + 0.04 * y
	ny := -0.04 * x + 0.85 * y + 1.6
    } else if r < 93 then {
	nx := 0.2 * x - 0.26 * y
	ny := 0.23 * x + 0.22 * y + 1.6
    } else {
	nx := -0.15 * x + 0.28 * y
	ny := 0.26 * x + 0.24 * y + 0.44
    }

    x := nx
    y := ny
end

procedure map(v:real, a, b, c, d)
    return (v - a) / (b - a) * (d - c) + c;
end

procedure draw_point()
    local px, py

    px := map(x, -2.1820, 2.6558, 0.0, 400.0)
    py := map(y, 0.0, 9.9983, 400.0, 0.0)

    Fg("green")
    DrawPoint(px, py)
end

procedure draw()
    every i := 0 to 10000 do {
	draw_point()
	next_point()
    }
end


function binary_search(sequence s, object val, integer low, integer high)
    integer mid, cmp
    if high < low then
        return 0 -- not found
    else
        mid = floor( (low + high) / 2 )
        cmp = compare(s[mid], val)
        if  cmp > 0 then
            return binary_search(s, val, low, mid-1)
        elsif cmp < 0 then
            return binary_search(s, val, mid+1, high)
        else
            return mid
        end if
    end if
end function


Private Sub plot_coordinate_pairs(x As Variant, y As Variant)
    Dim chrt As Chart
    Set chrt = ActiveSheet.Shapes.AddChart.Chart
    With chrt
        .ChartType = xlXYScatter
        .HasLegend = False
        .SeriesCollection.NewSeries
        .SeriesCollection.Item(1).XValues = x
        .SeriesCollection.Item(1).Values = y
    End With
End Sub
Public Sub barnsley_fern()
    Const MAX = 50000
    Dim x(MAX) As Double
    Dim y(MAX) As Double
    x(0) = 0: y(0) = 0
    For i = 1 To MAX
        Select Case CInt(100 * Rnd)
            Case 0 To 1
                x(i) = 0
                y(i) = 0.16 * y(i - 1)
            Case 2 To 85
                x(i) = 0.85 * x(i - 1) + 0.04 * y(i - 1)
                y(i) = -0.04 * x(i - 1) + 0.85 * y(i - 1) + 1.6
            Case 86 To 92
                x(i) = 0.2 * x(i - 1) - 0.26 * y(i - 1)
                y(i) = 0.23 * x(i - 1) + 0.22 * y(i - 1) + 1.6
            Case 93 To 100
                x(i) = -0.15 * x(i - 1) + 0.28 * y(i - 1)
                y(i) = 0.26 * x(i - 1) + 0.24 * y(i - 1) + 0.44
        End Select
    Next i
    plot_coordinate_pairs x, y
End Sub


' Barnsley Fern - 11/11/2019
Public Class BarnsleyFern

    Private Sub BarnsleyFern_Paint(sender As Object, e As PaintEventArgs) Handles Me.Paint
        Const Height = 800
        Dim x, y, xn, yn As Double
        Dim f As Double = Height / 10.6
        Dim offset_x As UInteger = Height \ 4 - Height \ 40
        Dim n, r As UInteger
        Dim Bmp As New Drawing.Bitmap(Height \ 2, Height) 'x,y
	'In Form: xPictureBox As PictureBox(800,400)
        xPictureBox.Image = Bmp
        For n = 1 To Height * 50
            r = Int(Rnd() * 100)      ' f from 0 to 99
            Select Case r
                Case 0 To 84
                    xn = 0.85 * x + 0.04 * y
                    yn = -0.04 * x + 0.85 * y + 1.6
                Case 85 To 91
                    xn = 0.2 * x - 0.26 * y
                    yn = 0.23 * x + 0.22 * y + 1.6
                Case 92 To 98
                    xn = -0.15 * x + 0.28 * y
                    yn = 0.26 * x + 0.24 * y + 0.44
                Case Else
                    xn = 0
                    yn = 0.16 * y
            End Select
            x = xn : y = yn
            Bmp.SetPixel(offset_x + x * f, Height - y * f, Color.FromArgb(0, 255, 0)) 'x,y  'r,g,b
        Next n
    End Sub 'Paint

End Class 'BarnsleyFern


let rec binarySearch (myArray:array<IComparable>, low:int, high:int, value:IComparable) =
    if (high < low) then
        null
    else
        let mid = (low + high) / 2

        if (myArray.[mid] > value) then
            binarySearch (myArray, low, mid-1, value)
        else if (myArray.[mid] < value) then
            binarySearch (myArray, mid+1, high, value)
        else
            myArray.[mid]


import "graphics" for Canvas, Color
import "dome" for Window
import "random" for Random

var Rand = Random.new()

class BarnsleyFern {
    construct new(width, height, points) {
        Window.title = "Barnsley Fern"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
        _n = points
    }

    init() {
        createFern()
    }

    createFern() {
        var x = 0
        var y = 0
        var c = Color.hex("#32cd32")
        for (i in 0..._n) {
            var tx
            var ty
            var r = Rand.float()
            if (r <= 0.01) {
                tx = 0
                ty = 0.16 * y
            } else if (r <= 0.86) {
                tx =  0.85 * x + 0.04 * y
                ty = -0.04 * x + 0.85 * y + 1.6
            } else if (r <= 0.93) {
                tx = 0.2  * x - 0.26 * y
                ty = 0.23 * x + 0.22 * y + 1.6
            } else {
                tx = -0.15 * x + 0.28 * y
                ty =  0.26 * x + 0.24 * y + 0.44
            }
            x = tx
            y = ty
            Canvas.pset((_w/2 + x * _w/11).round, (_h - y * _h/11).round, c)
        }
    }

    update() {}

    draw(alpha) {}
}

var Game = BarnsleyFern.new(640, 640, 200000)


USING: binary-search kernel math.order ;

: binary-search ( seq elt -- index/f )
    [ [ <=> ] curry search ] keep = [ drop f ] unless ;