; The array Frame1%x%_%y% holds the current frame. frame2%x%_%y%
; is then calculated from this, and printed. frame2 is then copied to frame1.
; Two arrays are necessary so that each cell advances at the same time
; T=Tree, #=Fire, O=Empty cell
; Size holds the width and height of the map and is used as the # of iterations in loops
; This will save the map as forest_fire.txt in its working directory
; ======================================================================================

Size := 10
Generation := 0
Tree := "T"
Fire := "#"
Cell := "O"

; --Define probabilities--
    New_Tree := 5
    ; 20 percent chance (1 in 5). A random number will be generated from 1 to New_tree. If this number is 1,
    ; A tree will be created in the current cell

    Spontaneous := 10
    ; 10 percent chance (1 in 10). A random number will be generated from 1 to Spontaneous. If this number is 1,
    ; and the current cell contains a tree, the tree in the current cell will become fire.

GoSub, Generate

; ----------------------Main Loop------------------------------
loop
{
    Generation++
    GoSub, Calculate
    GoSub, Copy
    GoSub, Display
    msgbox, 4, Forest Fire, At Generation %generation%. Continue?
    IfMsgbox, No
        ExitApp
}
return
; -------------------------------------------------------------

Generate:      ; Randomly initializes the map.
loop % size    ; % forces expression mode.
{
	x := A_Index
	Loop % size
	{
		Y := A_Index
		Random, IsTree, 1, 2 ;         -- Roughly half of the spaces will contain trees
		If ( IsTree = 1 )
			Frame1%x%_%y% := Tree
		Else
			Frame1%x%_%y% := Cell
	}
}
return

Calculate:
Loop % size
{
	x := A_Index
	Loop % size
	{
		Y := A_Index
		If ( Frame1%x%_%y% = Cell )
		{
			Random, tmp, 1, New_Tree
			If ( tmp = 1 )
				Frame2%x%_%y% := tree
			Else
				Frame2%x%_%y% := Cell
		}
		Else If ( Frame1%x%_%y% = Tree )
		{
			BoolCatch := PredictFire(x,y)
			If (BoolCatch)
				Frame2%x%_%y% := Fire
			Else
				Frame2%x%_%y% := Tree
		}
		Else If ( Frame1%x%_%y% = Fire )
			Frame2%x%_%y% := Cell
		Else
		{
			contents := Frame1%x%_%y%
			Msgbox Error! Cell %x% , %y% contains %contents% ; This has never happened
			ExitApp
		}
	}
}
return

Copy:
Loop % size
{
	x := A_Index
	Loop % size
	{
		y := A_Index
		frame1%x%_%y% := Frame2%x%_%y%
	}
}
return

Display:
ToPrint := ""
ToPrint .= "=====Generation " . Generation . "=====`n"
Loop % size
{
	x := A_Index
	Loop % size
	{
		y := A_Index
		ToPrint .= Frame1%x%_%y%
	}
	ToPrint .= "`n"
}
FileAppend, %ToPrint%, Forest_Fire.txt
Return

PredictFire(p_x,p_y){
    Global ; allows access to all frame1*_* variables (the pseudo-array)
    A := p_x-1
    B := p_y-1
    C := p_x+1
    D := p_y+1
    If ( Frame1%A%_%p_Y% = fire )
        return 1
    If ( Frame1%p_X%_%B% = fire )
        return 1
    If ( Frame1%C%_%p_Y% = fire )
        return 1
    If ( Frame1%p_X%_%D% = fire )
        return 1

    If ( Frame1%A%_%B% = Fire )
        return 1
    If ( Frame1%A%_%D% = fire )
        return 1
    If ( Frame1%C%_%B% = fire )
        return 1
    If ( Frame1%C%_%D% = Fire )
        return 1

    Random, tmp, 1, spontaneous
    if ( tmp = 1 )
        return 1
    return 0
}


with: n

: num?  \ n f --   )
	if drop else . then ;

\ is m mod n 0? leave the result twice on the stack
: div? \ m n -- f f
	mod 0 = dup ;

: fizz? \ n -- n f
	dup 3
	div? if "Fizz" .  then ;

: buzz? \ n f -- n f
	over 5
	div? if "Buzz" .  then or ;

\ print a message as appropriate for the given number:
: fizzbuzz  \ n --
	fizz? buzz? num?
	space ;

\ iterate from 1 to 100:
' fizzbuzz 1 100 loop
cr bye


N = 150 : M = 150 : P = 0.03 : F = 0.00003

dim f(N+2,M+2) # 1 tree, 0 empty, 2 fire
dim fn(N+2,M+2)
graphsize N,M
fastgraphics

for x = 1 to N
	for y = 1 to M
		if rand<0.5 then f[x,y] = 1
	next y
next x

while True
	for x = 1 to N
		for y = 1 to M
			if not f[x,y] and rand<P then fn[x,y]=1
			if f[x,y]=2 then fn[x,y]=0
			if f[x,y]=1 then
				fn[x,y] = 1
				if f[x-1,y-1]=2 or f[x,y-1]=2 or f[x+1,y-1]=2 then fn[x,y]=2
				if f[x-1,y]=2 or f[x+1,y]=2 or rand<F then fn[x,y]=2
				if f[x-1,y+1]=2 or f[x,y+1]=2 or f[x+1,y+1]=2 then fn[x,y]=2
			end if
			# Draw
			if fn[x,y]=0 then color black
			if fn[x,y]=1 then color green
			if fn[x,y]=2 then color yellow
			plot x-1,y-1
		next y
	next x
	refresh
	for x = 1 to N
		for y = 1 to M
			f[x,y] = fn[x,y]
		next y
	next x
end while


m - length and width of the array
p - probability of a tree growing
f - probability of a tree catching on fire
i - iterations to output


use AppleScript version "2.4" -- Mac OS X 10.10. (Yosemite) or later.
use framework "Foundation"

on fivenum(listOfNumbers, l, r)
    script o
        property lst : missing value

        on medianFromRange(l, r)
            set m1 to (l + r) div 2
            set m2 to m1 + (l + r) mod 2
            set median to my lst's item m1
            if (m2 > m1) then set median to (median + (my lst's item m2)) / 2

            return {median, m1, m2}
        end medianFromRange
    end script

    if ((listOfNumbers is {}) or (r - l < 0)) then return missing value
    set o's lst to current application's class "NSMutableArray"'s arrayWithArray:(listOfNumbers)
    tell o's lst to sortUsingSelector:("compare:")
    set o's lst to o's lst as list

    set {median, m1, m2} to o's medianFromRange(l, r)
    set {lowerQuartile} to o's medianFromRange(l, m1)
    set {upperQuartile} to o's medianFromRange(m2, r)

    return {o's lst's beginning, lowerQuartile, median, upperQuartile, o's lst's end}
end fivenum

-- Test code:
set x to {15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43}
set y to {36, 40, 7, 39, 41, 15}
set z to {0.14082834, 0.0974879, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.4667597, -0.74621349, -0.72588772, ¬
    0.6390516, 0.61501527, -0.9898378, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578}
return {fivenum(x, 1, count x), fivenum(y, 1, count y), fivenum(z, 1, count z)}


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

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

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessFizz:        .asciz "Fizz\n"
szMessBuzz:        .asciz "Buzz\n"
szMessFizzBuzz:    .asciz "FizzBuzz\n"
szMessNumber:      .asciz "Number : @ "
szCarriageReturn:  .asciz "\n"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sZoneConv:         .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                           // entry of program
    mov x10,3                   // divisor 3
    mov x11,5                   // divisor 5
    mov x12,15                  // divisor 15
    mov x13,1                   // indice
1:                              // loop begin
    udiv x14,x13,x12            // multiple 15
    msub x15,x14,x12,x13        // remainder
    cbnz x15,2f                 // zero ?
    mov x0,x13
    ldr x1,qAdrszMessFizzBuzz
    bl displayResult
    b 4f
2:                              // multiple 3
    udiv x14,x13,x10
    msub x15,x14,x10,x13        // remainder
    cbnz x15,3f                 // zero ?
    mov x0,x13
    ldr x1,qAdrszMessFizz
    bl displayResult
    b 4f
3:                               // multiple 5
    udiv x14,x13,x11
    msub x15,x14,x11,x13         // remainder
    cbnz x15,4f                  // zero ?
    mov x0,x13
    ldr x1,qAdrszMessBuzz
    bl displayResult
4:
    add x13,x13,1                // increment indice
    cmp x13,100                  // maxi ?
    ble 1b

100:                            // standard end of the program
    mov x8,EXIT                 // request to exit program
    svc 0                       // perform the system call
qAdrszMessFizzBuzz:        .quad szMessFizzBuzz
qAdrszMessFizz:            .quad szMessFizz
qAdrszMessBuzz:            .quad szMessBuzz
/******************************************************************/
/*     Display résult                                            */
/******************************************************************/
/* x0 contains the number*/
/* x1 contains display string address    */
displayResult:
    stp x2,lr,[sp,-16]!            // save  registers
    mov x2,x1
    ldr x1,qAdrsZoneConv           // conversion number
    bl conversion10S               // decimal conversion
    ldr x0,qAdrszMessNumber
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at @ character
    bl affichageMess               // display message final
    mov x0,x2
    bl affichageMess

    ldp x2,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrsZoneConv:        .quad sZoneConv
qAdrszMessNumber:     .quad szMessNumber
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include <pthread.h>

#include <SDL.h>

// defaults
#define PROB_TREE 0.55
#define PROB_F 0.00001
#define PROB_P 0.001

#define TIMERFREQ 100

#ifndef WIDTH
#  define WIDTH 640
#endif
#ifndef HEIGHT
#  define HEIGHT 480
#endif
#ifndef BPP
#  define BPP 32
#endif

#if BPP != 32
  #warning This program could not work with BPP different from 32
#endif

uint8_t *field[2], swapu;
double prob_f = PROB_F, prob_p = PROB_P, prob_tree = PROB_TREE;

enum cell_state {
  VOID, TREE, BURNING
};

// simplistic random func to give [0, 1)
double prand()
{
  return (double)rand() / (RAND_MAX + 1.0);
}

// initialize the field
void init_field(void)
{
  int i, j;
  swapu = 0;
  for(i = 0; i < WIDTH; i++)
  {
    for(j = 0; j < HEIGHT; j++)
    {
      *(field[0] + j*WIDTH + i) = prand() > prob_tree ? VOID : TREE;
    }
  }
}

// the "core" of the task: the "forest-fire CA"
bool burning_neighbor(int, int);
pthread_mutex_t synclock = PTHREAD_MUTEX_INITIALIZER;
static uint32_t simulate(uint32_t iv, void *p)
{
  int i, j;

  /*
    Since this is called by SDL, "likely"(*) in a separated
    thread, we try to avoid corrupted updating of the display
    (done by the show() func): show needs the "right" swapu
    i.e. the right complete field. (*) what if it is not so?
    The following is an attempt to avoid unpleasant updates.
   */
  pthread_mutex_lock(&synclock);

  for(i = 0; i < WIDTH; i++) {
    for(j = 0; j < HEIGHT; j++) {
      enum cell_state s = *(field[swapu] + j*WIDTH + i);
      switch(s)
      {
      case BURNING:
	*(field[swapu^1] + j*WIDTH + i) = VOID;
	break;
      case VOID:
	*(field[swapu^1] + j*WIDTH + i) = prand() > prob_p ? VOID : TREE;
	break;
      case TREE:
	if (burning_neighbor(i, j))
	  *(field[swapu^1] + j*WIDTH + i) = BURNING;
	else
	  *(field[swapu^1] + j*WIDTH + i) = prand() > prob_f ? TREE : BURNING;
	break;
      default:
	fprintf(stderr, "corrupted field\n");
	break;
      }
    }
  }
  swapu ^= 1;
  pthread_mutex_unlock(&synclock);
  return iv;
}

// the field is a "part" of an infinite "void" region
#define NB(I,J) (((I)<WIDTH)&&((I)>=0)&&((J)<HEIGHT)&&((J)>=0) \
		 ? (*(field[swapu] + (J)*WIDTH + (I)) == BURNING) : false)
bool burning_neighbor(int i, int j)
{
  return NB(i-1,j-1) || NB(i-1, j) || NB(i-1, j+1) ||
    NB(i, j-1) || NB(i, j+1) ||
    NB(i+1, j-1) || NB(i+1, j) || NB(i+1, j+1);
}

// "map" the field into gfx mem
// burning trees are red
// trees are green
// "voids" are black;
void show(SDL_Surface *s)
{
  int i, j;
  uint8_t *pixels = (uint8_t *)s->pixels;
  uint32_t color;
  SDL_PixelFormat *f = s->format;

  pthread_mutex_lock(&synclock);
  for(i = 0; i < WIDTH; i++) {
    for(j = 0; j < HEIGHT; j++) {
      switch(*(field[swapu] + j*WIDTH + i)) {
      case VOID:
	color = SDL_MapRGBA(f, 0,0,0,255);
	break;
      case TREE:
	color = SDL_MapRGBA(f, 0,255,0,255);
	break;
      case BURNING:
	color = SDL_MapRGBA(f, 255,0,0,255);
	break;
      }
      *(uint32_t*)(pixels + j*s->pitch + i*(BPP>>3)) = color;
    }
  }
  pthread_mutex_unlock(&synclock);
}

int main(int argc, char **argv)
{
  SDL_Surface *scr = NULL;
  SDL_Event event[1];
  bool quit = false, running = false;
  SDL_TimerID tid;

  // add variability to the simulation
  srand(time(NULL));

  // we can change prob_f and prob_p
  // prob_f prob of spontaneous ignition
  // prob_p prob of birth of a tree
  double *p;
  for(argv++, argc--; argc > 0; argc--, argv++)
  {
    if ( strcmp(*argv, "prob_f") == 0 && argc > 1 )
    {
      p = &prob_f;
    } else if ( strcmp(*argv, "prob_p") == 0 && argc > 1 ) {
      p = &prob_p;
    } else if ( strcmp(*argv, "prob_tree") == 0 && argc > 1 ) {
      p = &prob_tree;
    } else  continue;

    argv++; argc--;
    char *s = NULL;
    double t = strtod(*argv, &s);
    if (s != *argv) *p = t;
  }

  printf("prob_f %lf\nprob_p %lf\nratio %lf\nprob_tree %lf\n",
	 prob_f, prob_p, prob_p/prob_f,
	 prob_tree);

  if ( SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER) != 0 ) return EXIT_FAILURE;
  atexit(SDL_Quit);

  field[0] = malloc(WIDTH*HEIGHT);
  if (field[0] == NULL) exit(EXIT_FAILURE);
  field[1] = malloc(WIDTH*HEIGHT);
  if (field[1] == NULL) { free(field[0]); exit(EXIT_FAILURE); }

  scr = SDL_SetVideoMode(WIDTH, HEIGHT, BPP, SDL_HWSURFACE|SDL_DOUBLEBUF);
  if (scr == NULL) {
    fprintf(stderr, "SDL_SetVideoMode: %s\n", SDL_GetError());
    free(field[0]); free(field[1]);
    exit(EXIT_FAILURE);
  }

  init_field();

  tid = SDL_AddTimer(TIMERFREQ, simulate, NULL); // suppose success
  running = true;

  event->type = SDL_VIDEOEXPOSE;
  SDL_PushEvent(event);

  while(SDL_WaitEvent(event) && !quit)
  {
    switch(event->type)
    {
    case SDL_VIDEOEXPOSE:
      while(SDL_LockSurface(scr) != 0) SDL_Delay(1);
      show(scr);
      SDL_UnlockSurface(scr);
      SDL_Flip(scr);
      event->type = SDL_VIDEOEXPOSE;
      SDL_PushEvent(event);
      break;
    case SDL_KEYDOWN:
      switch(event->key.keysym.sym)
      {
      case SDLK_q:
	quit = true;
	break;
      case SDLK_p:
	if (running)
	{
	  running = false;
	  pthread_mutex_lock(&synclock);
	  SDL_RemoveTimer(tid); // ignore failure...
	  pthread_mutex_unlock(&synclock);
	} else {
	  running = true;
	  tid = SDL_AddTimer(TIMERFREQ, simulate, NULL);
	  // suppose success...
	}
	break;
      }
    case SDL_QUIT:
      quit = true;
      break;
    }
  }

  if (running) {
    pthread_mutex_lock(&synclock);
    SDL_RemoveTimer(tid);
    pthread_mutex_unlock(&synclock);
  }
  free(field[0]); free(field[1]);
  exit(EXIT_SUCCESS);
}


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

double median(double *x, int start, int end_inclusive) {
    int size = end_inclusive - start + 1;
    if (size <= 0) {
        printf("Array slice cannot be empty\n");
        exit(1);
    }
    int m = start + size / 2;
    if (size % 2) return x[m];
    return (x[m - 1] + x[m]) / 2.0;
}

int compare (const void *a, const void *b) {
    double aa = *(double*)a;
    double bb = *(double*)b;
    if (aa > bb) return 1;
    if (aa < bb) return -1;
    return 0;
}

int fivenum(double *x, double *result, int x_len) {
    int i, m, lower_end;
    for (i = 0; i < x_len; i++) {
        if (x[i] != x[i]) {
           printf("Unable to deal with arrays containing NaN\n\n");
           return 1;
        }
    }
    qsort(x, x_len, sizeof(double), compare);
    result[0] = x[0];
    result[2] = median(x, 0, x_len - 1);
    result[4] = x[x_len - 1];
    m = x_len / 2;
    lower_end = (x_len % 2) ? m : m - 1;
    result[1] = median(x, 0, lower_end);
    result[3] = median(x, m, x_len - 1);
    return 0;
}

int show(double *result, int places) {
    int i;
    char f[7];
    sprintf(f, "%%.%dlf", places);
    printf("[");
    for (i = 0; i < 5; i++) {
        printf(f, result[i]);
        if (i < 4) printf(", ");
    }
    printf("]\n\n");
}

int main() {
    double result[5];

    double x1[11] = {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0};
    if (!fivenum(x1, result, 11)) show(result, 1);

    double x2[6] = {36.0, 40.0, 7.0, 39.0, 41.0, 15.0};
    if (!fivenum(x2, result, 6)) show(result, 1);

    double x3[20] = {
         0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
        -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
        -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
         0.75775634,  0.32566578
    };
    if (!fivenum(x3, result, 20)) show(result, 9);

    return 0;
}


DATA: tab TYPE TABLE OF string.

tab = VALUE #(
  FOR i = 1 WHILE i <= 100 (
    COND string( LET r3 = i MOD 3
                     r5 = i MOD 5 IN
                 WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|
                 WHEN r3 = 0            THEN |FIZZ|
                 WHEN r5 = 0            THEN |BUZZ|
                 ELSE i ) ) ).

cl_demo_output=>write( tab ).
cl_demo_output=>display( ).


using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Threading;
using System.Windows.Forms;

namespace ForestFire
{
    class Program : Form
    {
        private static readonly Random rand = new Random();
        private Bitmap img;

        public Program(int w, int h, int f, int p)
        {
            Size = new Size(w, h);
            StartPosition = FormStartPosition.CenterScreen;

            Thread t = new Thread(() => fire(f, p));
            t.Start();

            FormClosing += (object sender, FormClosingEventArgs e) => { t.Abort(); t = null; };
        }

        private void fire(int f, int p)
        {
            int clientWidth = ClientRectangle.Width;
            int clientHeight = ClientRectangle.Height;
            int cellSize = 10;

            img = new Bitmap(clientWidth, clientHeight);
            Graphics g = Graphics.FromImage(img);

            CellState[,] state = InitializeForestFire(clientWidth, clientHeight);

            uint generation = 0;

            do
            {
                g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);
                state = StepForestFire(state, f, p);

                for (int y = 0; y < clientHeight - cellSize; y += cellSize)
                {
                    for (int x = 0; x < clientWidth - cellSize; x += cellSize)
                    {
                        switch (state[y, x])
                        {
                            case CellState.Empty:
                                break;
                            case CellState.Tree:
                                g.FillRectangle(Brushes.DarkGreen, x, y, cellSize, cellSize);
                                break;
                            case CellState.Burning:
                                g.FillRectangle(Brushes.DarkRed, x, y, cellSize, cellSize);
                                break;
                        }
                    }
                }

                Thread.Sleep(500);

                Invoke((MethodInvoker)Refresh);

            } while (generation < uint.MaxValue);

            g.Dispose();
        }

        private CellState[,] InitializeForestFire(int width, int height)
        {
            // Create our state array, initialize all indices as Empty, and return it.
            var state = new CellState[height, width];
            state.Initialize();
            return state;
        }

        private enum CellState : byte
        {
            Empty = 0,
            Tree = 1,
            Burning = 2
        }

        private CellState[,] StepForestFire(CellState[,] state, int f, int p)
        {
            /* Clone our old state, so we can write to our new state
             * without changing any values in the old state. */
            var newState = (CellState[,])state.Clone();

            int numRows = state.GetLength(0);
            int numCols = state.GetLength(1);

            for (int r = 1; r < numRows - 1; r++)
            {
                for (int c = 1; c < numCols - 1; c++)
                {
                    /*
                     * Check the current cell.
                     *
                     * If it's empty, give it a 1/p chance of becoming a tree.
                     *
                     * If it's a tree, check to see if any neighbors are burning.
                     * If so, set the cell's state to burning, otherwise give it
                     * a 1/f chance of combusting.
                     *
                     * If it's burning, set it to empty.
                     */
                    switch (state[r, c])
                    {
                        case CellState.Empty:
                            if (rand.Next(0, p) == 0)
                                newState[r, c] = CellState.Tree;
                            break;

                        case CellState.Tree:
                            if (NeighborHasState(state, r, c, CellState.Burning) || rand.Next(0, f) == 0)
                                newState[r, c] = CellState.Burning;
                            break;

                        case CellState.Burning:
                            newState[r, c] = CellState.Empty;
                            break;
                    }
                }
            }

            return newState;
        }

        private bool NeighborHasState(CellState[,] state, int x, int y, CellState value)
        {
            // Check each cell within a 1 cell radius for the specified value.
            for (int r = -1; r <= 1; r++)
            {
                for (int c = -1; c <= 1; c++)
                {
                    if (r == 0 && c == 0)
                        continue;

                    if (state[x + r, y + c] == value)
                        return true;
                }
            }

            return false;
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.DrawImage(img, 0, 0);
        }

        [STAThread]
        static void Main(string[] args)
        {
            Application.Run(new Program(w: 500, h: 500, f: 2, p: 5));
        }
    }
}


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

namespace Fivenum {
    public static class Helper {
        public static string AsString<T>(this ICollection<T> c, string format = "{0}") {
            StringBuilder sb = new StringBuilder("[");
            int count = 0;
            foreach (var t in c) {
                if (count++ > 0) {
                    sb.Append(", ");
                }
                sb.AppendFormat(format, t);
            }
            return sb.Append("]").ToString();
        }
    }

    class Program {
        static double Median(double[] x, int start, int endInclusive) {
            int size = endInclusive - start + 1;
            if (size <= 0) throw new ArgumentException("Array slice cannot be empty");
            int m = start + size / 2;
            return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;
        }

        static double[] Fivenum(double[] x) {
            foreach (var d in x) {
                if (Double.IsNaN(d)) {
                    throw new ArgumentException("Unable to deal with arrays containing NaN");
                }
            }
            double[] result = new double[5];
            Array.Sort(x);
            result[0] = x.First();
            result[2] = Median(x, 0, x.Length - 1);
            result[4] = x.Last();
            int m = x.Length / 2;
            int lowerEnd = (x.Length % 2 == 1) ? m : m - 1;
            result[1] = Median(x, 0, lowerEnd);
            result[3] = Median(x, m, x.Length - 1);
            return result;
        }

        static void Main(string[] args) {
            double[][] x1 = new double[][]{
                new double[]{ 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
                new double[]{ 36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
                new double[]{
                     0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
                    -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
                    -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
                     0.75775634,  0.32566578
                },
            };
            foreach(var x in x1) {
                var result = Fivenum(x);
                Console.WriteLine(result.AsString("{0:F8}"));
            }
        }
    }
}


(defun fizzbuzz-r (i)
   (declare (xargs :measure (nfix (- 100 i))))
   (prog2$
    (cond ((= (mod i 15) 0) (cw "FizzBuzz~%"))
          ((= (mod i 5) 0) (cw "Buzz~%"))
          ((= (mod i 3) 0) (cw "Fizz~%"))
          (t (cw "~x0~%" i)))
    (if (zp (- 100 i))
        nil
        (fizzbuzz-r (1+ i)))))

(defun fizzbuzz () (fizzbuzz-r 1))


#include <windows.h>
#include <string>

//--------------------------------------------------------------------------------------------------
using namespace std;

//--------------------------------------------------------------------------------------------------
enum states { NONE, TREE, FIRE };
const int MAX_SIDE = 500;

//--------------------------------------------------------------------------------------------------
class myBitmap
{
public:
    myBitmap() : pen( NULL ) {}
    ~myBitmap()
    {
	DeleteObject( pen );
	DeleteDC( hdc );
	DeleteObject( bmp );
    }

    bool create( int w, int h )
    {
	BITMAPINFO	bi;
	ZeroMemory( &bi, sizeof( bi ) );

	bi.bmiHeader.biSize	   = sizeof( bi.bmiHeader );
	bi.bmiHeader.biBitCount	   = sizeof( DWORD ) * 8;
	bi.bmiHeader.biCompression = BI_RGB;
	bi.bmiHeader.biPlanes	   = 1;
	bi.bmiHeader.biWidth	   =  w;
	bi.bmiHeader.biHeight	   = -h;

	HDC dc = GetDC( GetConsoleWindow() );
	bmp = CreateDIBSection( dc, &bi, DIB_RGB_COLORS, &pBits, NULL, 0 );
	if( !bmp ) return false;

	hdc = CreateCompatibleDC( dc );
	SelectObject( hdc, bmp );
	ReleaseDC( GetConsoleWindow(), dc );

	width = w; height = h;

	return true;
    }

    void clear()
    {
	ZeroMemory( pBits, width * height * sizeof( DWORD ) );
    }

    void setPenColor( DWORD clr )
    {
	if( pen ) DeleteObject( pen );
	pen = CreatePen( PS_SOLID, 1, clr );
	SelectObject( hdc, pen );
    }

    void saveBitmap( string path )
    {
	BITMAPFILEHEADER fileheader;
	BITMAPINFO	 infoheader;
	BITMAP		 bitmap;
	DWORD		 wb;

	GetObject( bmp, sizeof( bitmap ), &bitmap );

	DWORD* dwpBits = new DWORD[bitmap.bmWidth * bitmap.bmHeight];
	ZeroMemory( dwpBits, bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD ) );
	ZeroMemory( &infoheader, sizeof( BITMAPINFO ) );
	ZeroMemory( &fileheader, sizeof( BITMAPFILEHEADER ) );

	infoheader.bmiHeader.biBitCount = sizeof( DWORD ) * 8;
	infoheader.bmiHeader.biCompression = BI_RGB;
	infoheader.bmiHeader.biPlanes = 1;
	infoheader.bmiHeader.biSize = sizeof( infoheader.bmiHeader );
	infoheader.bmiHeader.biHeight = bitmap.bmHeight;
	infoheader.bmiHeader.biWidth = bitmap.bmWidth;
	infoheader.bmiHeader.biSizeImage = bitmap.bmWidth * bitmap.bmHeight * sizeof( DWORD );

	fileheader.bfType    = 0x4D42;
	fileheader.bfOffBits = sizeof( infoheader.bmiHeader ) + sizeof( BITMAPFILEHEADER );
	fileheader.bfSize    = fileheader.bfOffBits + infoheader.bmiHeader.biSizeImage;

	GetDIBits( hdc, bmp, 0, height, ( LPVOID )dwpBits, &infoheader, DIB_RGB_COLORS );

	HANDLE file = CreateFile( path.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
	WriteFile( file, &fileheader, sizeof( BITMAPFILEHEADER ), &wb, NULL );
	WriteFile( file, &infoheader.bmiHeader, sizeof( infoheader.bmiHeader ), &wb, NULL );
	WriteFile( file, dwpBits, bitmap.bmWidth * bitmap.bmHeight * 4, &wb, NULL );
	CloseHandle( file );

	delete [] dwpBits;
    }

    HDC getDC() const     { return hdc; }
    int getWidth() const  { return width; }
    int getHeight() const { return height; }

private:
    HBITMAP bmp;
    HDC	    hdc;
    HPEN    pen;
    void	*pBits;
    int	    width, height;
};
//--------------------------------------------------------------------------------------------------
class forest
{
public:
    forest()
    {
	_bmp.create( MAX_SIDE, MAX_SIDE );
	initForest( 0.05f, 0.005f );
    }

    void initForest( float p, float f )
    {
	_p = p; _f = f;
	seedForest();
    }

    void mainLoop()
    {
	display();
	simulate();
    }

    void setHWND( HWND hwnd ) { _hwnd = hwnd; }

private:
    float probRand() { return ( float )rand() / 32768.0f; }

    void display()
    {
	HDC bdc = _bmp.getDC();
	DWORD clr;

	for( int y = 0; y < MAX_SIDE; y++ )
	{
	    for( int x = 0; x < MAX_SIDE; x++ )
	    {
		switch( _forest[x][y] )
		{
		    case FIRE: clr = 255; break;
		    case TREE: clr = RGB( 0, 255, 0 ); break;
		    default: clr = 0;
		}

		SetPixel( bdc, x, y, clr );
	    }
	}

	HDC dc = GetDC( _hwnd );
	BitBlt( dc, 0, 0, MAX_SIDE, MAX_SIDE, _bmp.getDC(), 0, 0, SRCCOPY );
	ReleaseDC( _hwnd, dc );
    }

    void seedForest()
    {
	ZeroMemory( _forestT, sizeof( _forestT ) );
	ZeroMemory( _forest, sizeof( _forest ) );
	for( int y = 0; y < MAX_SIDE; y++ )
	    for( int x = 0; x < MAX_SIDE; x++ )
		if( probRand() < _p ) _forest[x][y] = TREE;
    }

    bool getNeighbors( int x, int y )
    {
	int a, b;
	for( int yy = -1; yy < 2; yy++ )
	    for( int xx = -1; xx < 2; xx++ )
	    {
		if( !xx && !yy ) continue;
		a = x + xx; b = y + yy;
		if( a < MAX_SIDE && b < MAX_SIDE && a > -1 && b > -1 )
		if( _forest[a][b] == FIRE ) return true;
	    }

	return false;
    }

    void simulate()
    {
	for( int y = 0; y < MAX_SIDE; y++ )
	{
	    for( int x = 0; x < MAX_SIDE; x++ )
	    {
		switch( _forest[x][y] )
		{
		    case FIRE: _forestT[x][y] = NONE; break;
		    case NONE: if( probRand() < _p ) _forestT[x][y] = TREE; break;
		    case TREE: if( getNeighbors( x, y ) || probRand() < _f ) _forestT[x][y] = FIRE;
		}
	    }
	}

	for( int y = 0; y < MAX_SIDE; y++ )
	    for( int x = 0; x < MAX_SIDE; x++ )
		_forest[x][y] = _forestT[x][y];
    }

    myBitmap _bmp;
    HWND     _hwnd;
    BYTE     _forest[MAX_SIDE][MAX_SIDE], _forestT[MAX_SIDE][MAX_SIDE];
    float    _p, _f;
};
//--------------------------------------------------------------------------------------------------
class wnd
{
public:
    int wnd::Run( HINSTANCE hInst )
    {
	_hInst = hInst;
	_hwnd = InitAll();

	_ff.setHWND( _hwnd );
	_ff.initForest( 0.02f, 0.001f );

	ShowWindow( _hwnd, SW_SHOW );
	UpdateWindow( _hwnd );

	MSG msg;
	ZeroMemory( &msg, sizeof( msg ) );
	while( msg.message != WM_QUIT )
	{
	    if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) != 0 )
	    {
		TranslateMessage( &msg );
		DispatchMessage( &msg );
	    }
	    else
	    {
		_ff.mainLoop();
	    }
	}
	return UnregisterClass( "_FOREST_FIRE_", _hInst );
    }
private:
    static int WINAPI wnd::WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
    {
	switch( msg )
	{
	    case WM_DESTROY: PostQuitMessage( 0 ); break;
	    default:
		return DefWindowProc( hWnd, msg, wParam, lParam );
	}
	return 0;
    }

    HWND InitAll()
    {
	WNDCLASSEX wcex;
	ZeroMemory( &wcex, sizeof( wcex ) );
	wcex.cbSize	       = sizeof( WNDCLASSEX );
	wcex.style	       = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc   = ( WNDPROC )WndProc;
	wcex.hInstance     = _hInst;
	wcex.hCursor       = LoadCursor( NULL, IDC_ARROW );
	wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
	wcex.lpszClassName = "_FOREST_FIRE_";

	RegisterClassEx( &wcex );

	return CreateWindow( "_FOREST_FIRE_", ".: Forest Fire -- PJorente :.", WS_SYSMENU, CW_USEDEFAULT, 0, MAX_SIDE, MAX_SIDE, NULL, NULL, _hInst, NULL );
    }

    HINSTANCE _hInst;
    HWND      _hwnd;
    forest    _ff;
};
//--------------------------------------------------------------------------------------------------
int APIENTRY _tWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow )
{
    srand( GetTickCount() );
    wnd myWnd;
    return myWnd.Run( hInstance );
}
//--------------------------------------------------------------------------------------------------


#include <algorithm>
#include <iostream>
#include <ostream>
#include <vector>

/////////////////////////////////////////////////////////////////////////////
// The following is taken from https://cpplove.blogspot.com/2012/07/printing-tuples.html

// Define a type which holds an unsigned integer value
template<std::size_t> struct int_ {};

template <class Tuple, size_t Pos>
std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<Pos>) {
    out << std::get< std::tuple_size<Tuple>::value - Pos >(t) << ", ";
    return print_tuple(out, t, int_<Pos - 1>());
}

template <class Tuple>
std::ostream& print_tuple(std::ostream& out, const Tuple& t, int_<1>) {
    return out << std::get<std::tuple_size<Tuple>::value - 1>(t);
}

template <class... Args>
std::ostream& operator<<(std::ostream& out, const std::tuple<Args...>& t) {
    out << '(';
    print_tuple(out, t, int_<sizeof...(Args)>());
    return out << ')';
}

/////////////////////////////////////////////////////////////////////////////

template <class RI>
double median(RI beg, RI end) {
    if (beg == end) throw std::runtime_error("Range cannot be empty");
    auto len = end - beg;
    auto m = len / 2;
    if (len % 2 == 1) {
        return *(beg + m);
    }

    return (beg[m - 1] + beg[m]) / 2.0;
}

template <class C>
auto fivenum(C& c) {
    std::sort(c.begin(), c.end());

    auto cbeg = c.cbegin();
    auto cend = c.cend();

    auto len = cend - cbeg;
    auto m = len / 2;
    auto lower = (len % 2 == 1) ? m : m - 1;
    double r2 = median(cbeg, cbeg + lower + 1);
    double r3 = median(cbeg, cend);
    double r4 = median(cbeg + lower + 1, cend);

    return std::make_tuple(*cbeg, r2, r3, r4, *(cend - 1));
}

int main() {
    using namespace std;
    vector<vector<double>> cs = {
        { 15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0 },
        { 36.0, 40.0, 7.0, 39.0, 41.0, 15.0 },
        {
            0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
           -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
           -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
            0.75775634,  0.32566578
        }
    };

    for (auto & c : cs) {
        cout << fivenum(c) << endl;
    }

    return 0;
}


PROC Main()
  BYTE i,d3,d5

  d3=1 d5=1
  FOR i=1 TO 100
  DO
    IF d3=0 AND d5=0 THEN
      Print("FizzBuzz")
    ELSEIF d3=0 THEN
      Print("Fizz")
    ELSEIF d5=0 THEN
      Print("Buzz")
    ELSE
      PrintB(i)
    FI
    Put(32)

    d3==+1 d5==+1
    IF d3=3 THEN d3=0 FI
    IF d5=5 THEN d5=0 FI
  OD
RETURN


import ceylon.random { DefaultRandom }

abstract class Cell() of tree | dirt | burning {}
object tree extends Cell() { string => "A"; }
object dirt extends Cell() { string => " "; }
object burning extends Cell() { string => "#"; }

class Forest(Integer width, Integer height, Float f, Float p) {

    value random = DefaultRandom();
    function chance(Float probability) => random.nextFloat() < probability;
    value sparked => chance(f);
    value sprouted => chance(p);

    alias Point => Integer[2];
    interface Row => {Cell*};

    object doubleBufferedGrid satisfies
            Correspondence<Point, Cell> &
            KeyedCorrespondenceMutator<Point, Cell> {

        value grids = [
            Array {
                for (j in 0:height)
                Array {
                    for (i in 0:width)
                    chance(0.5) then tree else dirt
                }
            },
            Array {
                for (j in 0:height)
                Array.ofSize(width, dirt)
            }
        ];

        variable value showFirst = true;
        value currentState => showFirst then grids.first else grids.last;
        value nextState => showFirst then grids.last else grids.first;

        shared void swapStates() => showFirst = !showFirst;

        shared {Row*} rows => currentState;

        shared actual Boolean defines(Point key) =>
                let (x = key[0], y = key[1])
                0 <= x < width && 0 <= y < height;
        shared actual Cell? get(Point key) =>
                let (x = key[0], y = key[1])
                currentState.get(y)?.get(x);

        shared actual void put(Point key, Cell cell) {
            value [x, y] = key;
            nextState.get(y)?.set(x, cell);
        }
    }

    variable value evolutions = 0;
    shared Integer generation => evolutions + 1;

    shared void evolve() {

        evolutions++;

        function firesNearby(Integer x, Integer y) => {
            for (j in y - 1 : 3)
            for (i in x - 1 : 3)
            doubleBufferedGrid[[i, j]]
        }.coalesced.any(burning.equals);

        for(j->row in doubleBufferedGrid.rows.indexed) {
            for(i->cell in row.indexed) {
                switch (cell)
                case (burning) {
                    doubleBufferedGrid[[i, j]] = dirt;
                }
                case (dirt) {
                    doubleBufferedGrid[[i, j]] = sprouted then tree else dirt;
                }
                case (tree) {
                    doubleBufferedGrid[[i, j]] =
                            firesNearby(i, j) || sparked
                            then burning else tree;
                }
            }
        }

        doubleBufferedGrid.swapStates();
    }

    shared void display() {

        void drawLine() => print("-".repeat(width + 2));

        drawLine();
        for (row in doubleBufferedGrid.rows) {
            process.write("|");
            for (cell in row) {
                process.write(cell.string);
            }
            print("|");
        }
        drawLine();
    }
}

shared void run() {

    value forest = Forest(78, 38, 0.02, 0.03);

    while (true) {

        forest.display();

        print("Generation ``forest.generation``");
        print("Press enter for next generation or q and then enter to quit");

        value input = process.readLine();
        if (exists input, input.trimmed.lowercased == "q") {
            return;
        }

        forest.evolve();
    }
}


(def burn-prob 0.1)
(def new-tree-prob 0.5)

(defn grow-new-tree? [] (> new-tree-prob (rand)))
(defn burn-tree? [] (> burn-prob (rand)))
(defn tree-maker [] (if (grow-new-tree?) :tree :grass))

(defn make-forest
  ([] (make-forest 5))
  ([size]
  (take size (repeatedly #(take size (repeatedly tree-maker))))))

(defn tree-at [forest row col] (try (-> forest
                                   (nth row)
                                   (nth col))
                                    (catch Exception _ false)))

(defn neighbores-burning? [forest row col]
  (letfn [(burnt? [row col] (= :burnt (tree-at forest row col)))]
    (or
     (burnt? (inc row) col)
     (burnt? (dec row) col)
     (burnt? row (inc col))
     (burnt? row (dec col)))))

(defn lightning-strike [forest]
  (map (fn [forest-row]
         (map #(if (and (= % :tree) (burn-tree?))
                 :fire!
                 %)
              forest-row)
         )
       forest))

(defn burn-out-trees [forest]
  (map (fn [forest-row]
         (map #(case %
              :burnt :grass
              :fire! :burnt
              %)
              forest-row))
       forest))

(defn burn-neighbores [forest]
  (let [forest-size (count forest)
        indicies (partition forest-size (for [row (range forest-size) col (range forest-size)] (cons row (list col))))]
    (map (fn [forest-row indicies-row]
           (map #(if (and
                       (= :tree %)
                       (neighbores-burning? forest (first %2) (second %2)))
                    :fire!
                    %)
                forest-row indicies-row))
         forest indicies)))

(defn grow-new-trees [forest] (map (fn [forest-row]
                                     (map #(if (= % :grass)
                                             (tree-maker)
                                             %)
                                          forest-row))
                                     forest))

(defn forest-fire
  ([] (forest-fire 5))
  ([forest-size]
  (loop
      [forest (make-forest forest-size)]
    (pprint forest)
    (Thread/sleep 300)
    (-> forest
        (burn-out-trees)
        (lightning-strike)
        (burn-neighbores)
        (grow-new-trees)
        (recur)))))

(forest-fire)


for (var i:int = 1; i <= 100; i++) {
  if (i % 15 == 0)
    trace('FizzBuzz');
  else if (i % 5 == 0)
    trace('Buzz');
  else if (i % 3 == 0)
    trace('Fizz');
  else
    trace(i);
}


       IDENTIFICATION DIVISION.
       PROGRAM-ID. forest-fire.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       *> Probability represents a fraction of 10000.
       *> For instance, IGNITE-PROB means a tree has a 1 in 10000 chance
       *> of igniting.
       78  IGNITE-PROB                 VALUE 1.
       78  NEW-TREE-PROB               VALUE 100.

       78  EMPTY-PROB                  VALUE 3333.

       78  AREA-SIZE                   VALUE 40.

       01  sim-table.
           03  sim-row OCCURS AREA-SIZE TIMES INDEXED BY row-index.
               05  sim-area OCCURS AREA-SIZE TIMES
                   INDEXED BY col-index.
                   07  current-status  PIC 9.
                       *> The flags correspond to the colours they will
                       *> be displayed as.
                       88  empty       VALUE 0. *> Black
                       88  tree        VALUE 2. *> Green
                       88  burning     VALUE 4. *> Red

                   07  next-status     PIC 9.
                       88  empty       VALUE 0.
                       88  tree        VALUE 2.
                       88  burning     VALUE 4.

       01  rand-num                    PIC 9999.

       01  next-row                    PIC 9(4).
       01  next-col                    PIC 9(4).

       01  neighbours-row              PIC 9(4).
       01  neighbours-col              PIC 9(4).

       PROCEDURE DIVISION.
       main-line.
           *> Seed RANDOM with current time.
           MOVE FUNCTION RANDOM(FUNCTION CURRENT-DATE (9:8)) TO rand-num

           PERFORM initialise-table
           PERFORM FOREVER
               PERFORM show-simulation
               PERFORM step-simulation
           END-PERFORM

           GOBACK
           .

       initialise-table.
           PERFORM VARYING row-index FROM 1 BY 1
                   UNTIL AREA-SIZE < row-index
                   AFTER col-index FROM 1 BY 1
                       UNTIL AREA-SIZE < col-index
               PERFORM get-rand-num
               IF rand-num <= EMPTY-PROB
                   SET empty OF current-status (row-index, col-index)
                       TO TRUE
                   SET empty OF next-status (row-index, col-index)
                       TO TRUE
               ELSE
                   SET tree OF current-status (row-index, col-index)
                       TO TRUE
                   SET tree OF next-status (row-index, col-index)
                       TO TRUE
               END-IF
           END-PERFORM
           .

       show-simulation.
           PERFORM VARYING row-index FROM 1 BY 1
                   UNTIL AREA-SIZE < row-index
                   AFTER col-index FROM 1 BY 1
                       UNTIL AREA-SIZE < col-index
                DISPLAY SPACE AT LINE row-index COLUMN col-index
                    WITH BACKGROUND-COLOR
                        current-status (row-index, col-index)
           END-PERFORM
           .

       *> Updates the simulation.
       step-simulation.
            PERFORM VARYING row-index FROM 1 BY 1
                   UNTIL AREA-SIZE < row-index
                   AFTER col-index FROM 1 BY 1
                       UNTIL AREA-SIZE < col-index
                EVALUATE TRUE
                    WHEN empty OF current-status (row-index, col-index)
                        PERFORM get-rand-num
                        IF rand-num <= NEW-TREE-PROB
                            SET tree OF next-status
                                 (row-index, col-index) TO TRUE
                        END-IF

                    WHEN tree OF current-status (row-index, col-index)
                        PERFORM simulate-tree

                    WHEN burning OF current-status
                            (row-index, col-index)
                        SET empty OF next-status (row-index, col-index)
                            TO TRUE
                END-EVALUATE
            END-PERFORM

            PERFORM update-statuses.
            .

       *> Updates a tree tile, assuming row-index and col-index are at
       *> a tree area.
       simulate-tree.
           *> Find the row and column of the bottom-right neighbour.
           COMPUTE next-row = FUNCTION MIN(row-index + 1, AREA-SIZE)
           COMPUTE next-col = FUNCTION MIN(col-index + 1, AREA-SIZE)

           COMPUTE neighbours-row = FUNCTION MAX(row-index - 1, 1)
           COMPUTE neighbours-col = FUNCTION MAX(col-index - 1, 1)

           *> If a neighbour is burning, catch fire.
           PERFORM VARYING neighbours-row FROM neighbours-row BY 1
                   UNTIL next-row < neighbours-row
               *> Check if neighbours in a row are on fire.
               PERFORM VARYING neighbours-col FROM neighbours-col BY 1
                       UNTIL next-col < neighbours-col
                   IF neighbours-row = row-index
                           AND neighbours-col = col-index
                       EXIT PERFORM CYCLE
                   END-IF

                   IF burning OF current-status
                           (neighbours-row, neighbours-col)
                       SET burning OF next-status (row-index, col-index)
                           TO TRUE
                       EXIT PARAGRAPH
                   END-IF
               END-PERFORM

               *> Move neighbours-col back to starting position
               COMPUTE neighbours-col =
                   FUNCTION MAX(neighbours-col - 3, 1)
           END-PERFORM

           *> Otherwise, there is a random chance of
           *> catching fire.
           PERFORM get-rand-num
           IF rand-num <= IGNITE-PROB
               SET burning OF next-status (row-index, col-index) TO TRUE
           END-IF
           .

       update-statuses.
           PERFORM VARYING row-index FROM 1 BY 1
                   UNTIL AREA-SIZE < row-index
                   AFTER col-index FROM 1 BY 1
                       UNTIL AREA-SIZE < col-index
               MOVE next-status (row-index, col-index)
                   TO current-status (row-index, col-index)
           END-PERFORM
           .

       *> Puts a random value between 0 and 9999 in rand-num.
       get-rand-num.
           COMPUTE rand-num =
               FUNCTION MOD(FUNCTION RANDOM * 100000, 10000)
           .


var cube:Function = function(x) {
  return Math.pow(x, 3);
};
var cuberoot:Function = function(x) {
  return Math.pow(x, 1/3);
};

function compose(f:Function, g:Function):Function {
	return function(x:Number) {return f(g(x));};
}
var functions:Array = [Math.cos, Math.tan, cube];
var inverse:Array = [Math.acos, Math.atan, cuberoot];

function test() {
	for (var i:uint = 0; i < functions.length; i++) {
        // Applying the composition to 0.5
	trace(compose(functions[i], inverse[i])(0.5));
	}
}

test();


program Fivenum;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Generics.Collections;

function Median(x: TArray<Double>; start, endInclusive: Integer): Double;
var
  size, m: Integer;
begin
  size := endInclusive - start + 1;
  if (size <= 0) then
    raise EArgumentException.Create('Array slice cannot be empty');
  m := start + size div 2;
  if (odd(size)) then
    Result := x[m]
  else
    Result := (x[m - 1] + x[m]) / 2;
end;

function FiveNumber(x: TArray<Double>): TArray<Double>;
var
  m, lowerEnd: Integer;
begin
  SetLength(result, 5);
  TArray.Sort<double>(x);
  result[0] := x[0];
  result[2] := median(x, 0, length(x) - 1);
  result[4] := x[length(x) - 1];
  m := length(x) div 2;
  if odd(length(x)) then
    lowerEnd := m
  else
    lowerEnd := m - 1;
  result[1] := median(x, 0, lowerEnd);
  result[3] := median(x, m, length(x) - 1);
end;

function ArrayToString(x: TArray<double>): string;
var
  i: Integer;
begin
  Result := '[';
  for i := 0 to High(x) do
  begin
    if i > 0 then
      Result := Result + ',';
    Result := Result + format('%.4f', [x[i]]);
  end;
  Result := Result + ']';
end;

var
  xl: array of TArray<double> = [[15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0,
    39.0, 47.0, 43.0], [36.0, 40.0, 7.0, 39.0, 41.0, 15.0], [0.14082834,
    0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726,
    1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -
    1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634,
    0.32566578]];
  x: TArray<double>;

begin
  for x in xl do
    writeln(ArrayToString(FiveNumber(x)), #10);

  readln;
end.


with Ada.Text_IO; use Ada.Text_IO;

procedure Fizzbuzz is
begin
   for I in 1..100 loop
      if I mod 15 = 0 then
         Put_Line("FizzBuzz");
      elsif I mod 5 = 0 then
         Put_Line("Buzz");
      elsif I mod 3 = 0 then
         Put_Line("Fizz");
      else
         Put_Line(Integer'Image(I));
      end if;
   end loop;
end Fizzbuzz;


(defvar *dims* '(10 10))
(defvar *prob-t* 0.5)
(defvar *prob-f* 0.1)
(defvar *prob-p* 0.01)

(defmacro with-gensyms (names &body body)
  `(let ,(mapcar (lambda (n) (list n '(gensym))) names)
	 ,@body))

(defmacro traverse-grid (grid rowvar colvar (&rest after-cols) &body body)
  (with-gensyms (dims rows cols)
	`(let* ((,dims (array-dimensions ,grid))
		(,rows (car ,dims))
		(,cols (cadr ,dims)))
	   (dotimes (,rowvar ,rows ,grid)
		 (dotimes (,colvar ,cols ,after-cols)
		   ,@body)))))

(defun make-new-forest (&optional (dims *dims*))
  (let ((forest (make-array dims :element-type 'symbol :initial-element 'void)))
	(traverse-grid forest row col nil
	  (if (<= (random 1.0) *prob-t*)
		  (setf (aref forest row col) 'tree)))))

(defun print-forest (forest)
  (traverse-grid forest row col (terpri)
	(ecase (aref forest row col)
	  ((void) (write-char #\space))
	  ((tree) (write-char #\T))
	  ((fire) (write-char #\#))))
  (values))

(defvar *neighboring* '((-1 . -1) (-1 . 0) (-1 . 1)
			(0 . -1)           (0 . 1)
			(1 . -1)  (1 . 0)  (1 . 1)))

(defun neighbors (forest row col)
  (loop for n in *neighboring*
	for nrow = (+ row (car n))
        for ncol = (+ col (cdr n))
	when (array-in-bounds-p forest nrow ncol)
	collect (aref forest nrow ncol)))

(defun evolve-tree (forest row col)
  (let ((tree (aref forest row col)))
	(cond ((eq tree 'fire) ;; if the tree was on fire, it's dead Jim
		   'void)
	      ((and (eq tree 'tree) ;; if a neighbor is on fire, it's on fire too
		    (find 'fire (neighbors forest row col) :test #'eq))
		   'fire)
	      ((and (eq tree 'tree) ;; random chance of fire happening
		    (<= (random 1.0) *prob-f*))
		   'fire)
	      ((and (eq tree 'void) ;; random chance of empty space becoming a tree
		    (<= (random 1.0) *prob-p*))
		   'tree)
		  (t tree))))

(defun evolve-forest (forest)
  (let* ((dims (array-dimensions forest))
	 (new (make-array dims :element-type 'symbol :initial-element 'void)))
	(traverse-grid forest row col nil
	  (setf (aref new row col) (evolve-tree forest row col)))
	new))

(defun simulate (forest n &optional (print-all t))
  (format t "------ Initial forest ------~%")
  (print-forest forest)
  (dotimes (i n)
    (setf forest (evolve-forest forest))
    (when print-all
      (progn (format t "~%------ Generation ~d ------~%" (1+ i))
 	(print-forest forest)))))


with Ada.Float_Text_IO,
     Ada.Integer_Text_IO,
     Ada.Text_IO,
     Ada.Numerics.Elementary_Functions;

procedure First_Class_Functions is
   use Ada.Float_Text_IO,
       Ada.Integer_Text_IO,
       Ada.Text_IO,
       Ada.Numerics.Elementary_Functions;

   function Sqr (X : Float) return Float is
   begin
      return X ** 2;
   end Sqr;

   type A_Function is access function (X : Float) return Float;

   generic
      F, G : A_Function;
   function Compose (X : Float) return Float;

   function Compose (X : Float) return Float is
   begin
      return F (G (X));
   end Compose;

   Functions : array (Positive range <>) of A_Function := (Sin'Access,
                                                           Cos'Access,
                                                           Sqr'Access);
   Inverses  : array (Positive range <>) of A_Function := (Arcsin'Access,
                                                           Arccos'Access,
                                                           Sqrt'Access);
begin
   for I in Functions'Range loop
      declare
         function Identity is new Compose (Functions (I), Inverses (I));
         Test_Value : Float := 0.5;
         Result     : Float;
      begin
         Result := Identity (Test_Value);

         if Result = Test_Value then
            Put      ("Example ");
            Put      (I, Width => 0);
            Put_Line (" is perfect for the given test value.");
         else
            Put      ("Example ");
            Put      (I, Width => 0);
            Put      (" is off by");
            Put      (abs (Result - Test_Value));
            Put_Line (" for the given test value.");
         end if;
      end;
   end loop;
end First_Class_Functions;


import math

function compose (f, g) {
    return function (x) { return f(g(x)) }
}

var fn  = [Math.sin, Math.cos, function(x) { return x*x*x }]
var inv = [Math.asin, Math.acos, function(x) { return Math.pow(x, 1.0/3) }]

for (var i=0; i<3; i++) {
    var f = compose(inv[i], fn[i])
    println(f(0.5))    // 0.5
}


main:(
  FOR i TO 100 DO
    printf(($gl$,
      IF i %* 15 = 0 THEN
        "FizzBuzz"
      ELIF i %* 3 = 0 THEN
        "Fizz"
      ELIF i %* 5 = 0 THEN
        "Buzz"
      ELSE
        i
      FI
    ))
  OD
)


import std.stdio, std.random, std.string, std.algorithm;

enum treeProb = 0.55; // Original tree probability.
enum fProb =    0.01; // Auto combustion probability.
enum cProb =    0.01; // Tree creation probability.

enum Cell : char { empty=' ', tree='T', fire='#' }
alias World = Cell[][];

bool hasBurningNeighbours(in World world, in ulong r, in ulong c)
pure nothrow @safe @nogc {
    foreach (immutable rowShift; -1 .. 2)
        foreach (immutable colShift; -1 .. 2)
            if ((r + rowShift) >= 0 && (r + rowShift) < world.length &&
                (c + colShift) >= 0 && (c + colShift) < world[0].length &&
                world[r + rowShift][c + colShift] == Cell.fire)
                return true;
    return false;
}

void nextState(in World world, World nextWorld) /*nothrow*/ @safe /*@nogc*/ {
    foreach (r, row; world)
        foreach (c, elem; row)
            final switch (elem) with (Cell) {
                case empty:
                    nextWorld[r][c]= (uniform01 < cProb) ? tree : empty;
                    break;

                case tree:
                    if (world.hasBurningNeighbours(r, c))
                        nextWorld[r][c] = fire;
                    else
                        nextWorld[r][c] = (uniform01 < fProb) ? fire : tree;
                    break;

                case fire:
                    nextWorld[r][c] = empty;
                    break;
            }
}

void main() @safe {
    auto world = new World(8, 65);
    foreach (row; world)
        foreach (ref el; row)
            el = (uniform01 < treeProb) ? Cell.tree : Cell.empty;
    auto nextWorld = new World(world.length, world[0].length);

    foreach (immutable i; 0 .. 4) {
        nextState(world, nextWorld);
        writefln("%(%(%c%)\n%)\n", nextWorld);
        world.swap(nextWorld);
    }
}


MODE F = PROC (REAL)REAL;
OP ** = (REAL x, power)REAL: exp(ln(x)*power);

# Add a user defined function and its inverse #
PROC cube = (REAL x)REAL: x * x * x;
PROC cube root = (REAL x)REAL: x ** (1/3);

# First class functions allow run-time creation of functions from functions #
# return function compose(f,g)(x) == f(g(x)) #
PROC non standard compose = (F f1, f2)F: (REAL x)REAL: f1(f2(x)); # eg ELLA ALGOL 68RS #
PROC compose = (F f, g)F: ((F f2, g2, REAL x)REAL: f2(g2(x)))(f, g, );

# Or the classic "o" functional operator #
PRIO O = 5;
OP (F,F)F O = compose;

# first class functions should be able to be members of collection types #
[]F func list = (sin, cos, cube);
[]F arc func list = (arc sin, arc cos, cube root);

# Apply functions from lists as easily as integers #
FOR index TO UPB func list DO
  STRUCT(F f, inverse f) this := (func list[index], arc func list[index]);
  print(((inverse f OF this O f OF this)(.5), new line))
OD


-- Compose two functions, where each function is
-- a script object with a call(x) handler.
on compose(f, g)
    script
        on call(x)
            f's call(g's call(x))
        end call
    end script
end compose

script increment
    on call(n)
        n + 1
    end call
end script

script decrement
    on call(n)
        n - 1
    end call
end script

script twice
    on call(x)
        x * 2
    end call
end script

script half
    on call(x)
        x / 2
    end call
end script

script cube
    on call(x)
        x ^ 3
    end call
end script

script cuberoot
    on call(x)
        x ^ (1 / 3)
    end call
end script

set functions to {increment, twice, cube}
set inverses to {decrement, half, cuberoot}
set answers to {}
repeat with i from 1 to 3
    set end of answers to ¬
        compose(item i of inverses, ¬
            item i of functions)'s ¬
        call(0.5)
end repeat
answers -- Result: {0.5, 0.5, 0.5}


USING: combinators combinators.smart kernel math
math.statistics prettyprint sequences sorting ;
IN: rosetta-code.five-number

<PRIVATE

: bisect ( seq -- lower upper )
    dup length even? [ halves ]
    [ dup [email protected] 1 + [ head ] [ tail* ] 2bi ] if ;

: (fivenum) ( seq -- summary )
    natural-sort {
        [ infimum ]
        [ bisect drop median ]
        [ median ]
        [ bisect nip median ]
        [ supremum ]
    } cleave>array ;

PRIVATE>

ERROR: fivenum-empty data ;
ERROR: fivenum-nan data ;

: fivenum ( seq -- summary )
    {
        { [ dup empty? ] [ fivenum-empty ] }
        { [ dup [ fp-nan? ] any? ] [ fivenum-nan ] }
        [ (fivenum) ]
    } cond ;

: fivenum-demo ( -- )
    { 15 6 42 41 7 36 49 40 39 47 43 }
    { 36 40 7 39 41 15 }
    {  0.14082834  0.09748790  1.73131507  0.87636009
      -1.95059594  0.73438555 -0.03035726  1.46675970
      -0.74621349 -0.72588772  0.63905160  0.61501527
      -0.98983780 -1.00447874 -0.62759469  0.66206163
       1.04312009 -0.10305385  0.75775634  0.32566578 }
    [ fivenum . ] [email protected] ;

MAIN: fivenum-demo


BEGIN

INTEGER FUNCTION DIVBY(N, D);
INTEGER N;
INTEGER D;
BEGIN
  DIVBY := 1 - (N - D * (N / D));
END;

INTEGER I;
FOR I := 1 STEP 1 UNTIL 100 DO
BEGIN
  IF DIVBY(I, 15) = 1 THEN
    WRITE("FizzBuzz")
  ELSE IF DIVBY(I, 5) = 1 THEN
    WRITE("Buzz")
  ELSE IF DIVBY(I, 3) = 1 THEN
    WRITE("Fizz")
  ELSE
    WRITE(I);
END;

END


#chance of empty->tree
set :p 0.004
#chance of spontaneous tree combustion
set :f 0.001
#chance of tree in initial state
set :s 0.5
#height of world
set :H 10
#width of world
set :W 20

has-burning-neigbour state pos:
	for i range -- swap ++ dup &< pos:
		for j range -- swap ++ dup &> pos:
			& i j
			try:
				state!
			catch value-error:
				:empty
			if = :burning:
				return true
	false

evolve state pos:
	state! pos
	if = :tree dup:
		if has-burning-neigbour state pos:
			:burning drop
		elseif chance f:
			:burning drop
	elseif = :burning:
		:empty
	else:
		if chance p:
			:tree
		else:
			:empty

step state:
	local :next {}
	for k in keys state:
		set-to next k evolve state k
	next

local :(c) { :tree "T" :burning "B" :empty "." }
print-state state:
	for j range 0 H:
		for i range 0 W:
			!print\ (c)! state! & i j
		!print ""

init-state:
	local :first {}
	for j range 0 H:
		for i range 0 W:
			if chance s:
				:tree
			else:
				:empty
			set-to first & i j
	first

run:
	init-state
	while true:
		print-state dup
		!print ""
		step

run-slowly:
	init-state
	while true:
		print-state dup
		drop !prompt "Continue."
		step

run


p_fire = 0.00002
p_tree = 0.002
#
len f[] 102 * 102
len p[] len f[]
background 100
clear
for r range 100
  for c range 100
    i = r * 102 + c + 103
    if randomf < 0.5
      f[i] = 1
    .
  .
.
timer 0
#
subr show
  for r range 100
    for c range 100
      i = r * 102 + c + 103
      h = f[i]
      if h <> p[i]
        move c + 0.5 r + 0.5
        if h = 0
          color 100
          circle 0.6
        elif h = 1
          color 151
          circle 0.5
        else
          color 9 * 100 + (18 - 2 * h) * 10
          circle 0.5
        .
      .
    .
  .
.
subr update
  swap f[] p[]
  for r range 100
    for c range 100
      i = r * 102 + c + 103
      if p[i] = 0
        f[i] = 0
        if randomf < p_tree
          f[i] = 1
        .
      elif p[i] = 1
        f[i] = 1
        s = p[i - 103] + p[i - 102] + p[i - 101]
        s += p[i - 1] + p[i + 1]
        s += p[i + 101] + p[i + 102] + p[i + 103]
        if s >= 9 or randomf < p_fire
          f[i] = 9
        .
      elif p[i] = 4
        f[i] = 0
      else
        f[i] = p[i] - 1
      .
    .
  .
.
on timer
  call show
  call update
  timer 0.2
.


cube: function [x] -> x^3
croot: function [x] -> x^(1//3)

names: ["sin/asin", "cos/acos", "cube/croot"]
funclist: @[var 'sin, var 'cos, var 'cube]
invlist:  @[var 'asin, var 'acos, var 'croot]

num: 0.5

loop 0..2 'f [
    result: call funclist\[f] @[num]
    print [names\[f] "=>" call invlist\[f] @[result]]
]


#NoEnv
; Set the floating-point precision
SetFormat, Float, 0.15
; Super-global variables for function objects
Global F, G
; User-defined functions
Cube(X) {
   Return X ** 3
}
CubeRoot(X) {
   Return X ** (1/3)
}
; Function arrays, Sin/ASin and Cos/ACos are built-in
FuncArray1 := [Func("Sin"),  Func("Cos"),  Func("Cube")]
FuncArray2 := [Func("ASin"), Func("ACos"), Func("CubeRoot")]
; Compose
Compose(FN1, FN2) {
   Static FG := Func("ComposedFunction")
   F := FN1, G:= FN2
   Return FG
}
ComposedFunction(X) {
   Return F.(G.(X))
}
; Run
X := 0.5 + 0
Result := "Input:`n" . X . "`n`nOutput:"
For Index In FuncArray1
   Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X)
MsgBox, 0, First-Class Functions, % Result
ExitApp


class Fivenum {
    static double median(double[] x, int start, int endInclusive) {
        int size = endInclusive - start + 1
        if (size <= 0) {
            throw new IllegalArgumentException("Array slice cannot be empty")
        }
        int m = start + (int) (size / 2)
        return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0
    }

    static double[] fivenum(double[] x) {
        for (Double d : x) {
            if (d.isNaN()) {
                throw new IllegalArgumentException("Unable to deal with arrays containing NaN")
            }
        }
        double[] result = new double[5]
        Arrays.sort(x)
        result[0] = x[0]
        result[2] = median(x, 0, x.length - 1)
        result[4] = x[x.length - 1]
        int m = (int) (x.length / 2)
        int lowerEnd = (x.length % 2 == 1) ? m : m - 1
        result[1] = median(x, 0, lowerEnd)
        result[3] = median(x, m, x.length - 1)
        return result
    }

    static void main(String[] args) {
        double[][] xl = [
            [15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0],
            [36.0, 40.0, 7.0, 39.0, 41.0, 15.0],
            [
                0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,
                -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,
                -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,
                0.75775634, 0.32566578
            ]
        ]
        for (double[] x : xl) {
            println("${fivenum(x)}")
        }
    }
}


begin
    i_w := 1; % set integers to print in minimum space %
    for i := 1 until 100 do begin
        if      i rem 15 = 0 then write( "FizzBuzz" )
        else if i rem  5 = 0 then write( "Buzz" )
        else if i rem  3 = 0 then write( "Fizz" )
        else                      write( i )
    end for_i
end.


#!/usr/bin/env emacs -script
;; -*- lexical-binding: t -*-
;; run: ./forest-fire forest-fire.config
(require 'cl-lib)
;; (setq debug-on-error t)

(defmacro swap (a b)
  `(setq ,b (prog1 ,a (setq ,a ,b))))

(defconst burning ?B)
(defconst tree ?t)

(cl-defstruct world rows cols data)

(defun new-world (rows cols)
  ;; When allocating the vector add padding so the border will always be empty.
  (make-world :rows rows :cols cols :data (make-vector (* (1+ rows) (1+ cols)) nil)))

(defmacro world--rows (w)
  `(1+ (world-rows ,w)))

(defmacro world--cols (w)
  `(1+ (world-cols ,w)))

(defmacro world-pt (w r c)
  `(+ (* (mod ,r (world--rows ,w)) (world--cols ,w))
      (mod ,c (world--cols ,w))))

(defmacro world-ref (w r c)
  `(aref (world-data ,w) (world-pt ,w ,r ,c)))

(defun print-world (world)
  (dotimes (r (world-rows world))
    (dotimes (c (world-cols world))
      (let ((cell (world-ref world r c)))
        (princ (format "%c" (if (not (null cell))
                   cell
                 ?.)))))
    (terpri)))

(defun random-probability ()
  (/ (float (random 1000000)) 1000000))

(defun initialize-world (world p)
  (dotimes (r (world-rows world))
    (dotimes (c (world-cols world))
      (setf (world-ref world r c) (if (<= (random-probability) p) tree nil)))))

(defun neighbors-burning (world row col)
  (let ((n 0))
    (dolist (offset '((1 . 1) (1 . 0) (1 . -1) (0 . 1) (0 . -1) (-1 . 1) (-1 . 0) (-1 . -1)))
      (when (eq (world-ref world (+ row (car offset)) (+ col (cdr offset))) burning)
        (setq n (1+ n))))
    (> n 0)))

(defun advance (old new p f)
  (dotimes (r (world-rows old))
    (dotimes (c (world-cols old))
      (cond
       ((eq (world-ref old r c) burning)
        (setf (world-ref new r c) nil))
       ((null (world-ref old r c))
        (setf (world-ref new r c) (if (<= (random-probability) p) tree nil)))
       ((eq (world-ref old r c) tree)
        (setf (world-ref new r c) (if (or (neighbors-burning old r c)
                                          (<= (random-probability) f))
                                      burning
                                    tree)))))))

(defun read-config (file-name)
  (with-temp-buffer
    (insert-file-contents-literally file-name)
    (read (current-buffer))))

(defun get-config (key config)
  (let ((val (assoc key config)))
    (if (null val)
        (error (format "missing value for %s" key))
      (cdr val))))

(defun simulate-forest (file-name)
  (let* ((config (read-config file-name))
         (rows (get-config 'rows config))
         (cols (get-config 'cols config))
         (skip (get-config 'skip config))
         (a (new-world rows cols))
         (b (new-world rows cols)))
    (initialize-world a (get-config 'tree config))
    (dotimes (time (get-config 'time config))
      (when (or (and (> skip 0) (= (mod time skip) 0))
                (<= skip 0))
        (princ (format "* time %d\n" time))
        (print-world a))
      (advance a b (get-config 'p config) (get-config 'f config))
      (swap a b))))

(simulate-forest (elt command-line-args-left 0))


fns := [sin$Float, cos$Float, (x:Float):Float +-> x^3]
inv := [asin$Float, acos$Float, (x:Float):Float +-> x^(1/3)]
[(f*g) 0.5 for f in fns for g in inv]


      REM Create some functions and their inverses:
      DEF FNsin(a) = SIN(a)
      DEF FNasn(a) = ASN(a)
      DEF FNcos(a) = COS(a)
      DEF FNacs(a) = ACS(a)
      DEF FNcube(a) = a^3
      DEF FNroot(a) = a^(1/3)

      dummy = FNsin(1)

      REM Create the collections (here structures are used):
      DIM cA{Sin%, Cos%, Cube%}
      DIM cB{Asn%, Acs%, Root%}
      cA.Sin% = ^FNsin() : cA.Cos% = ^FNcos() : cA.Cube% = ^FNcube()
      cB.Asn% = ^FNasn() : cB.Acs% = ^FNacs() : cB.Root% = ^FNroot()

      REM Create some function compositions:
      AsnSin% = FNcompose(cB.Asn%, cA.Sin%)
      AcsCos% = FNcompose(cB.Acs%, cA.Cos%)
      RootCube% = FNcompose(cB.Root%, cA.Cube%)

      REM Test applying the compositions:
      x = 1.234567 : PRINT x, FN(AsnSin%)(x)
      x = 2.345678 : PRINT x, FN(AcsCos%)(x)
      x = 3.456789 : PRINT x, FN(RootCube%)(x)
      END

      DEF FNcompose(f%,g%)
      LOCAL f$, p%
      f$ = "(x)=" + CHR$&A4 + "(&" + STR$~f% + ")(" + \
      \             CHR$&A4 + "(&" + STR$~g% + ")(x))"
      DIM p% LEN(f$) + 4
      $(p%+4) = f$ : !p% = p%+4
      = p%


double acos (double d)	{ return Math.acos(d); }
double asin (double d)	{ return Math.asin(d); }
double cos (double d)	{ return Math.cos(d); }
double sin (double d)	{ return Math.sin(d); }
double croot (double d)	{ return Math.pow(d, 1/3); }
double cube (double x)	{ return x * x * x; }

Var compose (Var f, Var g, double x)
{
	Func ff = f;
	Func fg = g;
	return ff(fg(x));
}

void button1_onClick (Widget widget)
{
	Array arr1 = [ sin, cos, cube ];
	Array arr2 = [ asin, acos, croot ];

	str s;
	for (int i = 1; i <= 3; i++)
	{
		s << compose(arr1.get(i), arr2.get(i), 0.5) << str.newline;
	}
	label1.setText(s);
}


funsA ← ⟨⋆⟜2,-,•math.Sin,{𝕩×3}⟩
funsB ← ⟨√,-,•math.Asin,{𝕩÷3}⟩

comp ← funsA {𝕎∘𝕏}¨ funsB

•Show comp {𝕎𝕩}¨<0.5


midpts=: (1 + #) <:@(] , -:@[ , -) -:@<[email protected]:@(3 + #) NB. mid points of y
quartiles=: -:@(+/)@((<. ,: >.)@midpts { /:[email protected]])  NB. quartiles of y
fivenum=: <./ , quartiles , >./                  NB. fivenum summary of y


n:{1+ x}map range[100]
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n
echo map s


-module( forest_fire ).

-export( [task/0] ).

-record( state, {neighbours=[], position, probability_burn, probability_grow, tree} ).

task() ->
       erlang:spawn( fun() ->
             Pid_positions = forest_create( 5, 5, 0.5, 0.3, 0.2 ),
             Pids = [X || {X, _} <- Pid_positions],
             [X ! {tree_pid_positions, Pid_positions} || X <- Pids],
             Start = forest_status( Pids ),
             Histories = [Start | [forest_step( Pids ) || _X <- lists:seq(1, 2)]],
             [io:fwrite("~p~n~n", [X]) || X <- Histories]
         end ).

forest_create( X_max, Y_max, Init, Grow, Burn ) ->
       [{tree_create(tree_init(Init, random:uniform()), X, Y, Grow, Burn), {X,Y}} || X <- lists:seq(1, X_max), Y<- lists:seq(1, Y_ma\
x)].

forest_status( Pids ) ->
       [X ! {status_request, erlang:self()} || X <- Pids],
       [receive {status, Tree, Position, X} -> {Tree, Position} end || X <- Pids].

forest_step( Pids ) ->
       [X ! {step} || X <- Pids],
       forest_status( Pids ).

is_neighbour({X, Y}, {X, Y} ) -> false; % Myself
is_neighbour({Xn, Yn}, {X, Y} ) when abs(Xn - X) =< 1, abs(Yn - Y) =< 1 -> true;
is_neighbour( _Position_neighbour, _Position ) -> false.

loop( State ) ->
        receive
        {tree_pid_positions, Pid_positions} ->
                loop( loop_neighbour(Pid_positions, State) );
        {step} ->
               [X ! {tree, State#state.tree, erlang:self()} || X <- State#state.neighbours],
               loop( loop_step(State) );
        {status_request, Pid} ->
                Pid ! {status, State#state.tree, State#state.position, erlang:self()},
                loop( State )
        end.

loop_neighbour(	Pid_positions, State ) ->
	My_position = State#state.position,
        State#state{neighbours=[Pid || {Pid, Position} <- Pid_positions, is_neighbour( Position, My_position)]}.

loop_step( State ) ->
        Is_burning = lists:any( fun loop_step_burning/1, [loop_step_receive(X) || X <- State#state.neighbours] ),
        Tree = loop_step_next( Is_burning, random:uniform(), State ),
        State#state{tree=Tree}.

loop_step_burning( Tree ) -> Tree =:= burning.

loop_step_next( _Is_burning, Probablility, #state{tree=empty, probability_grow=Grow} ) when Grow > Probablility -> tree;
loop_step_next( _Is_burning, _Probablility, #state{tree=empty} ) -> empty;
loop_step_next( _Is_burning, _Probablility, #state{tree=burning} ) -> empty;
loop_step_next( true, _Probablility, #state{tree=tree} ) -> burning;
loop_step_next( false, Probablility, #state{tree=tree, probability_burn=Burn} ) when Burn > Probablility  -> burning;
loop_step_next( false, _Probablility, #state{tree=tree} ) -> tree.

loop_step_receive( Pid ) -> receive {tree, Tree, Pid} -> Tree end.

tree_create( Tree, X, Y, Grow, Burn ) ->
        State = #state{position={X, Y}, probability_burn=Burn, probability_grow=Grow, tree=Tree},
        erlang:spawn_link( fun() -> random:seed( X, Y, 0 ), loop( State ) end ).

tree_init( Tree_probalility, Random ) when Tree_probalility > Random -> tree;
tree_init( _Tree_probalility, _Random ) -> empty.


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

/* declare a typedef for a function pointer */
typedef double (*Class2Func)(double);

/*A couple of functions with the above prototype */
double functionA( double v)
{
   return v*v*v;
}
double functionB(double v)
{
   return exp(log(v)/3);
}

/* A function taking a function as an argument */
double Function1( Class2Func f2, double val )
{
    return f2(val);
}

/*A function returning a function */
Class2Func WhichFunc( int idx)
{
   return (idx < 4) ? &functionA : &functionB;
}

/* A list of functions */
Class2Func funcListA[] = {&functionA, &sin, &cos, &tan };
Class2Func funcListB[] = {&functionB, &asin, &acos, &atan };

/* Composing Functions */
double InvokeComposed( Class2Func f1, Class2Func f2, double val )
{
   return f1(f2(val));
}

typedef struct sComposition {
   Class2Func f1;
   Class2Func f2;
} *Composition;

Composition Compose( Class2Func f1, Class2Func f2)
{
   Composition comp = malloc(sizeof(struct sComposition));
   comp->f1 = f1;
   comp->f2 = f2;
   return comp;
}

double CallComposed( Composition comp, double val )
{
    return comp->f1( comp->f2(val) );
}
/** * * * * * * * * * * * * * * * * * * * * * * * * * * */

int main(int argc, char *argv[])
{
   int ix;
   Composition c;

   printf("Function1(functionA, 3.0) = %f\n", Function1(WhichFunc(0), 3.0));

   for (ix=0; ix<4; ix++) {
       c = Compose(funcListA[ix], funcListB[ix]);
       printf("Compostion %d(0.9) = %f\n", ix, CallComposed(c, 0.9));
   }

   return 0;
}


import java.util.Arrays;

public class Fivenum {

    static double median(double[] x, int start, int endInclusive) {
        int size = endInclusive - start + 1;
        if (size <= 0) throw new IllegalArgumentException("Array slice cannot be empty");
        int m = start + size / 2;
        return (size % 2 == 1) ? x[m] : (x[m - 1] + x[m]) / 2.0;
    }

    static double[] fivenum(double[] x) {
        for (Double d : x) {
            if (d.isNaN())
                throw new IllegalArgumentException("Unable to deal with arrays containing NaN");
        }
        double[] result = new double[5];
        Arrays.sort(x);
        result[0] = x[0];
        result[2] = median(x, 0, x.length - 1);
        result[4] = x[x.length - 1];
        int m = x.length / 2;
        int lowerEnd = (x.length % 2 == 1) ? m : m - 1;
        result[1] = median(x, 0, lowerEnd);
        result[3] = median(x, m, x.length - 1);
        return result;
    }

    public static void main(String[] args) {
        double xl[][] = {
            {15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0},
            {36.0, 40.0, 7.0, 39.0, 41.0, 15.0},
            {
                 0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
                -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
                -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
                 0.75775634,  0.32566578
            }
        };
        for (double[] x : xl) System.out.printf("%s\n\n", Arrays.toString(fivenum(x)));
    }
}


for(integer i=1; i <= 100; i++){
    String output = '';
    if(math.mod(i, 3) == 0) output += 'Fizz';
    if(math.mod(i, 5) == 0) output += 'Buzz';
    if(output != ''){
        System.debug(output);
    } else {
        System.debug(i);
    }
}


open System
open System.Diagnostics
open System.Drawing
open System.Drawing.Imaging
open System.Runtime.InteropServices
open System.Windows.Forms

module ForestFire =

    type Cell = Empty | Tree | Fire

    let rnd = new System.Random()
    let initial_factor = 0.35
    let ignition_factor = 1e-5 // rate of lightning strikes (f)
    let growth_factor = 2e-3   // rate of regrowth (p)
    let width = 640            // width of the forest region
    let height = 480           // height of the forest region

    let make_forest =
        Array2D.init height width
            (fun _ _ -> if rnd.NextDouble() < initial_factor then Tree else Empty)

    let count (forest:Cell[,]) row col =
        let mutable n = 0
        let h,w = forest.GetLength 0, forest.GetLength 1
        for r in row-1 .. row+1 do
            for c in col-1 .. col+1 do
                if r >= 0 && r < h && c >= 0 && c < w && forest.[r,c] = Fire then
                    n <- n + 1
        if forest.[row,col] = Fire then n-1 else n

    let burn (forest:Cell[,]) r c =
        match forest.[r,c] with
        | Fire -> Empty
        | Tree -> if rnd.NextDouble() < ignition_factor then Fire
                    else if (count forest r c) > 0 then Fire else Tree
        | Empty -> if rnd.NextDouble() < growth_factor then Tree else Empty

    // All the functions below this point are drawing the generated images to screen.
    let make_image (pixels:int[]) =
        let bmp = new Bitmap(width, height)
        let bits = bmp.LockBits(Rectangle(0,0,width,height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb)
        Marshal.Copy(pixels, 0, bits.Scan0, bits.Height*bits.Width) |> ignore
        bmp.UnlockBits(bits)
        bmp

    // This function is run asynchronously to avoid blocking the main GUI thread.
    let run (box:PictureBox) (label:Label) = async {
        let timer = new Stopwatch()
        let forest = make_forest |> ref
        let pixel = Array.create (height*width) (Color.Black.ToArgb())
        let rec update gen =
            timer.Start()
            forest := burn !forest |> Array2D.init height width
            for y in 0..height-1 do
                for x in 0..width-1 do
                    pixel.[x+y*width] <- match (!forest).[y,x] with
                                            | Empty -> Color.Gray.ToArgb()
                                            | Tree -> Color.Green.ToArgb()
                                            | Fire -> Color.Red.ToArgb()
            let img = make_image pixel
            box.Invoke(MethodInvoker(fun () -> box.Image <- img)) |> ignore
            let msg = sprintf "generation %d @ %.1f fps" gen (1000./timer.Elapsed.TotalMilliseconds)
            label.Invoke(MethodInvoker(fun () -> label.Text <- msg )) |> ignore
            timer.Reset()
            update (gen + 1)
        update 0 }

    let main args =
        let form = new Form(AutoSize=true,
                            Size=new Size(800,600),
                            Text="Forest fire cellular automata")
        let box = new PictureBox(Dock=DockStyle.Fill,Location=new Point(0,0),SizeMode=PictureBoxSizeMode.StretchImage)
        let label = new Label(Dock=DockStyle.Bottom, Text="Ready")
        form.FormClosed.Add(fun eventArgs -> Async.CancelDefaultToken()
                                             Application.Exit())
        form.Controls.Add(box)
        form.Controls.Add(label)
        run box label |> Async.Start
        form.Show()
        Application.Run()
        0

#if INTERACTIVE
ForestFire.main [|""|]
#else
[<System.STAThread>]
[<EntryPoint>]
let main args = ForestFire.main args
#endif


using System;

class Program
{
    static void Main(string[] args)
    {
        var cube = new Func<double, double>(x => Math.Pow(x, 3.0));
        var croot = new Func<double, double>(x => Math.Pow(x, 1 / 3.0));

        var functionTuples = new[]
        {
            (forward: Math.Sin, backward: Math.Asin),
            (forward: Math.Cos, backward: Math.Acos),
            (forward: cube,     backward: croot)
        };

        foreach (var ft in functionTuples)
        {
            Console.WriteLine(ft.backward(ft.forward(0.5)));
        }
    }
}


#include <functional>
#include <algorithm>
#include <iostream>
#include <vector>
#include <cmath>

using std::cout;
using std::endl;
using std::vector;
using std::function;
using std::transform;
using std::back_inserter;

typedef function<double(double)> FunType;

vector<FunType> A = {sin, cos, tan, [](double x) { return x*x*x; } };
vector<FunType> B = {asin, acos, atan, [](double x) { return exp(log(x)/3); } };

template <typename A, typename B, typename C>
function<C(A)> compose(function<C(B)> f, function<B(A)> g) {
    return [f,g](A x) { return f(g(x)); };
}

int main() {
    vector<FunType> composedFuns;
    auto exNums = {0.0, 0.2, 0.4, 0.6, 0.8, 1.0};

    transform(B.begin(), B.end(),
                A.begin(),
                back_inserter(composedFuns),
                compose<double, double, double>);

    for (auto num: exNums)
        for (auto fun: composedFuns)
            cout << u8"f\u207B\u00B9.f(" << num << ") = " << fun(num) << endl;

    return 0;
}


USING: combinators grouping kernel literals math math.matrices
math.vectors prettyprint random raylib.ffi sequences ;
IN: rosetta-code.forest-fire

! The following private vocab builds up to a useful combinator,
! matrix-map-neighbors, which takes a matrix, a quotation, and
! inside the quotation makes available each element of the
! matrix as well as its neighbors, mapping the result of the
! quotation to a new matrix.

<PRIVATE

CONSTANT: neighbors {
    { -1 -1 } { -1  0 } { -1  1 }
    {  0 -1 }           {  0  1 }
    {  1 -1 } {  1  0 } {  1  1 }
}

: ?i,j ( i j matrix -- elt/f ) swapd ?nth ?nth ;

: ?i,jths ( seq matrix -- newseq )
    [ [ first2 ] dip ?i,j ] curry map ;

: neighbor-coords ( loc -- seq )
    [ neighbors ] dip [ v+ ] curry map ;

: get-neighbors ( loc matrix -- seq )
    [ neighbor-coords ] dip ?i,jths ;

: matrix>neighbors ( matrix -- seq )
    dup dim matrix-coordinates concat
    [ swap get-neighbors sift ] with map ;

: matrix-map-neighbors ( ... matrix quot: ( ... neighbors elt -- ... newelt ) -- ... newmatrix )
    [ [ dim first ] [ matrix>neighbors ] [ concat ] tri ] dip
    2map swap group ; inline

PRIVATE>

! ##### Simulation code #####

! In our forest,
! 0 = empty
! 1 = tree
! 2 = fire

CONSTANT: ignite-probability 1/12000
CONSTANT: grow-probability 1/100

: make-forest ( m n probability -- matrix )
    [ random-unit > 1 0 ? ] curry make-matrix ;

: ?ignite ( -- 1/2 ) ignite-probability random-unit > 2 1 ? ;
: ?grow ( -- 0/1 ) grow-probability random-unit > 1 0 ? ;

: next-plot ( neighbors elt -- n )
    {
        { [ dup 2 = ] [ 2drop 0 ] }
        { [ 2dup [ [ 2 = ] any? ] [ 1 = ] bi* and ] [ 2drop 2 ] }
        { [ 1 = ] [ drop ?ignite ] }
        [ drop ?grow ]
    } cond ;

: next-forest ( forest -- newforest )
    [ next-plot ] matrix-map-neighbors ;

! ##### Display code #####

CONSTANT: colors ${ GRAY GREEN RED }

: draw-forest ( matrix -- )
    dup dim matrix-coordinates [ concat ] [email protected] swap [
        [ first2 [ 5 * ] [email protected] 5 5 ] dip colors nth draw-rectangle
    ] 2each ;

500 500 "Forest Fire" init-window 100 100 1/2 make-forest
60 set-target-fps
[ window-should-close ] [
    begin-drawing
        BLACK clear-background dup draw-forest
    end-drawing
    next-forest
] until drop close-window


30             CONSTANT WIDTH
30             CONSTANT HEIGHT
WIDTH HEIGHT * CONSTANT SIZE

1 VALUE SEED
: (RAND) ( -- u)  \ xorshift generator
   SEED DUP 13 LSHIFT XOR
        DUP 17 RSHIFT XOR
        DUP  5 LSHIFT XOR
        DUP TO SEED ;
10000 CONSTANT RANGE
100   CONSTANT GROW
1     CONSTANT BURN
: RAND ( -- u)  (RAND) RANGE MOD ;

\ Create buffers for world state
CREATE A  SIZE ALLOT  A SIZE ERASE
CREATE B  SIZE ALLOT  B SIZE ERASE

0 CONSTANT NONE  1 CONSTANT TREE  2 CONSTANT FIRE
: NEARBY-FIRE? ( addr u -- t|f)
   2 -1 DO
     2 -1 DO
       J WIDTH * I + OVER +  \ calculate an offset
       DUP 0> OVER SIZE < AND IF
         >R OVER R> + [email protected]     \ fetch state of the offset cell
         FIRE = IF UNLOOP UNLOOP DROP DROP TRUE EXIT THEN
       ELSE DROP THEN
     LOOP
   LOOP  DROP DROP FALSE ;
: GROW?   RAND GROW <= ;  \ spontaneously sprout?
: BURN?   RAND BURN <= ;  \ spontaneously combust?
: STEP ( prev next --)  \ Given state in PREV, put next in NEXT
   >R 0 BEGIN DUP SIZE <
   WHILE
      2DUP + [email protected] CASE
      FIRE OF NONE ENDOF
      TREE OF 2DUP NEARBY-FIRE? BURN? OR IF FIRE ELSE TREE THEN ENDOF
      NONE OF GROW? IF TREE ELSE NONE THEN ENDOF
      ENDCASE
      ( i next-cell-state) OVER [email protected] + C!        \ commit to next
   1+ REPEAT  R> DROP DROP DROP ;

: (ESCAPE)   27 EMIT [CHAR] [ EMIT ;
: ESCAPE"   POSTPONE (ESCAPE) POSTPONE S" POSTPONE TYPE ;  IMMEDIATE
: CLEAR   ESCAPE" H" ;
: RETURN   ESCAPE" E" ;
: RESET   ESCAPE" m" ;
: .FOREST ( addr --)  CLEAR
   HEIGHT 0 DO
     WIDTH 0 DO
       DUP [email protected] CASE
       NONE OF SPACE ENDOF
       TREE OF ESCAPE" 32m" [CHAR] T EMIT RESET ENDOF
       FIRE OF ESCAPE" 31m" [CHAR] # EMIT RESET ENDOF
       ENDCASE  1+
     LOOP  RETURN
   LOOP RESET DROP ;

: (GO) ( buffer buffer' -- buffer' buffer)
   2DUP STEP    \ step the simulation
   DUP .FOREST  \ print the current state
   SWAP ;       \ prepare for next iteration
: GO   A B  BEGIN (GO) AGAIN ;


module rosetta "1.0.0" {
	import ceylon.numeric "1.2.1";
}


(use 'clojure.contrib.math)
(let [fns [#(Math/sin %) #(Math/cos %) (fn [x] (* x x x))]
      inv [#(Math/asin %) #(Math/acos %) #(expt % 1/3)]]
  (map #(% 0.5) (map #(comp %1 %2) fns inv)))


# Functions as values of a variable
cube = (x) -> Math.pow x, 3
cuberoot = (x) -> Math.pow x, 1 / 3

# Higher order function
compose = (f, g) -> (x) -> f g(x)

# Storing functions in a array
fun = [Math.sin, Math.cos, cube]
inv = [Math.asin, Math.acos, cuberoot]

# Applying the composition to 0.5
console.log compose(inv[i], fun[i])(0.5) for i in [0..2]


// version 1.2.21

fun median(x: DoubleArray, start: Int, endInclusive: Int): Double {
    val size = endInclusive - start + 1
    require (size > 0) { "Array slice cannot be empty" }
    val m = start + size / 2
    return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0
}

fun fivenum(x: DoubleArray): DoubleArray {
    require(x.none { it.isNaN() }) { "Unable to deal with arrays containing NaN" }
    val result = DoubleArray(5)
    x.sort()
    result[0] = x[0]
    result[2] = median(x, 0, x.size - 1)
    result[4] = x[x.lastIndex]
    val m = x.size / 2
    var lowerEnd = if (x.size % 2 == 1) m else m - 1
    result[1] = median(x, 0, lowerEnd)
    result[3] = median(x, m, x.size - 1)
    return result
}

fun main(args: Array<String>) {
    var xl = listOf(
        doubleArrayOf(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0),
        doubleArrayOf(36.0, 40.0, 7.0, 39.0, 41.0, 15.0),
        doubleArrayOf(
             0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
            -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
            -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
             0.75775634,  0.32566578
        )
    )
    xl.forEach { println("${fivenum(it).asList()}\n") }
}


property outputText: ""
repeat with i from 1 to 100
  if i mod 15 = 0 then
    set outputText to outputText & "FizzBuzz"
  else if i mod 3 = 0 then
    set outputText to outputText & "Fizz"
  else if i mod 5 = 0 then
    set outputText to outputText & "Buzz"
  else
    set outputText to outputText & i
  end if
  set outputText to outputText & linefeed
end repeat
outputText


module ForestFireModel
  implicit none

  type :: forestfire
     integer, dimension(:,:,:), allocatable :: field
     integer :: width, height
     integer :: swapu
     real :: prob_tree, prob_f, prob_p
  end type forestfire

  integer, parameter :: &
       empty = 0, &
       tree = 1, &
       burning = 2

  private :: bcheck, set, oget, burning_neighbor ! cset, get

contains

  ! create and initialize the field(s)
  function forestfire_new(w, h, pt, pf, pp) result(res)
    type(forestfire) :: res
    integer, intent(in) :: w, h
    real, intent(in), optional :: pt, pf, pp

    integer :: i, j
    real :: r

    allocate(res%field(2,w,h)) ! no error check
    res%prob_tree = 0.5
    res%prob_f = 0.00001
    res%prob_p = 0.001
    if ( present(pt) ) res%prob_tree = pt
    if ( present(pf) ) res%prob_f = pf
    if ( present(pp) ) res%prob_p = pp

    res%width = w
    res%height = h
    res%swapu = 0

    res%field = empty

    do i = 1,w
       do j = 1,h
          call random_number(r)
          if ( r <= res%prob_tree ) call cset(res, i, j, tree)
       end do
    end do

  end function forestfire_new

  ! destroy the field(s)
  subroutine forestfire_destroy(f)
    type(forestfire), intent(inout) :: f

    if ( allocated(f%field) ) deallocate(f%field)

  end subroutine forestfire_destroy

  ! evolution
  subroutine forestfire_evolve(f)
    type(forestfire), intent(inout) :: f

    integer :: i, j
    real :: r

    do i = 1, f%width
       do j = 1, f%height
          select case ( get(f, i, j) )
          case (burning)
             call set(f, i, j, empty)
          case (empty)
             call random_number(r)
             if ( r > f%prob_p ) then
                call set(f, i, j, empty)
             else
                call set(f, i, j, tree)
             end if
          case (tree)
             if ( burning_neighbor(f, i, j) ) then
                call set(f, i, j, burning)
             else
                call random_number(r)
                if ( r > f%prob_f ) then
                   call set(f, i, j, tree)
                else
                   call set(f, i, j, burning)
                end if
             end if
          end select
       end do
    end do
    f%swapu = ieor(f%swapu, 1)
  end subroutine forestfire_evolve

  ! helper funcs/subs
  subroutine set(f, i, j, t)
    type(forestfire), intent(inout) :: f
    integer, intent(in) :: i, j, t

    if ( bcheck(f, i, j) ) then
       f%field(ieor(f%swapu,1), i, j) = t
    end if
  end subroutine set

  subroutine cset(f, i, j, t)
    type(forestfire), intent(inout) :: f
    integer, intent(in) :: i, j, t

    if ( bcheck(f, i, j) ) then
       f%field(f%swapu, i, j) = t
    end if
  end subroutine cset

  function bcheck(f, i, j)
    logical :: bcheck
    type(forestfire), intent(in) :: f
    integer, intent(in) :: i, j

    bcheck = .false.
    if ( (i >= 1) .and. (i <= f%width) .and. &
         (j >= 1) .and. (j <= f%height) ) bcheck = .true.

  end function bcheck

  function get(f, i, j) result(r)
    integer :: r
    type(forestfire), intent(in) :: f
    integer, intent(in) :: i, j

    if ( .not. bcheck(f, i, j) ) then
       r = empty
    else
       r = f%field(f%swapu, i, j)
    end if
  end function get

  function oget(f, i, j) result(r)
    integer :: r
    type(forestfire), intent(in) :: f
    integer, intent(in) :: i, j

    if ( .not. bcheck(f, i, j) ) then
       r = empty
    else
       r = f%field(ieor(f%swapu,1), i, j)
    end if
  end function oget

  function burning_neighbor(f, i, j) result(r)
    logical :: r
    type(forestfire), intent(in) :: f
    integer, intent(in) :: i, j

    integer, dimension(3,3) :: s

    s = f%field(f%swapu, i-1:i+1, j-1:j+1)
    s(2,2) = empty
    r = any(s == burning)
  end function burning_neighbor

  subroutine forestfire_print(f)
    type(forestfire), intent(in) :: f

    integer :: i, j

    do j = 1, f%height
       do i = 1, f%width
          select case(get(f, i, j))
          case (empty)
             write(*,'(A)', advance='no') '.'
          case (tree)
             write(*,'(A)', advance='no') 'Y'
          case (burning)
             write(*,'(A)', advance='no') '*'
          end select
       end do
       write(*,*)
    end do
  end subroutine forestfire_print

end module ForestFireModel


(defun compose (f g) (lambda (x) (funcall f (funcall g x))))
(defun cube (x) (expt x 3))
(defun cube-root (x) (expt x (/ 3)))

(loop with value = 0.5
      for func in (list #'sin  #'cos  #'cube     )
      for inverse  in (list #'asin #'acos #'cube-root)
      for composed = (compose inverse func)
      do (format t "~&(~A ∘ ~A)(~A) = ~A~%"
                 inverse
                 func
                 value
                 (funcall composed value)))


void main() {
    import std.stdio, std.math, std.typetuple, std.functional;

    alias dir = TypeTuple!(sin,  cos,  x => x ^^ 3);
    alias inv = TypeTuple!(asin, acos, cbrt);
    // foreach (f, g; staticZip!(dir, inv))
    foreach (immutable i, f; dir)
        writefln("%6.3f", compose!(f, inv[i])(0.5));
}


fizzbuzz():
  for x in [1..100]
    if x%5==0 and x%3==0
      return "FizzBuzz"
    else
      if x%3==0
        return "Fizz"
      else
        if x%5==0
          return "Buzz"
        else
           return x

main():
  fizzbuzz() -> io


package main

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

const (
    rows = 20
    cols = 30
    p    = .01
    f    = .001
)

const rx = rows + 2
const cx = cols + 2

func main() {
    odd := make([]byte, rx*cx)
    even := make([]byte, rx*cx)
    for r := 1; r <= rows; r++ {
        for c := 1; c <= cols; c++ {
            if rand.Intn(2) == 1 {
                odd[r*cx+c] = 'T'
            }
        }
    }
    for {
        print(odd)
        step(even, odd)
        fmt.Scanln()

        print(even)
        step(odd, even)
        fmt.Scanln()
    }
}

func print(model []byte) {
    fmt.Println(strings.Repeat("__", cols))
    fmt.Println()
    for r := 1; r <= rows; r++ {
        for c := 1; c <= cols; c++ {
            if model[r*cx+c] == 0 {
                fmt.Print("  ")
            } else {
                fmt.Printf(" %c", model[r*cx+c])
            }
        }
        fmt.Println()
    }
}

func step(dst, src []byte) {
    for r := 1; r <= rows; r++ {
        for c := 1; c <= cols; c++ {
            x := r*cx + c
            dst[x] = src[x]
            switch dst[x] {
            case '#':
                // rule 1. A burning cell turns into an empty cell
                dst[x] = 0
            case 'T':
                // rule 2. A tree will burn if at least one neighbor is burning
                if src[x-cx-1]=='#'  || src[x-cx]=='#' || src[x-cx+1]=='#' ||
                    src[x-1] == '#'  ||                   src[x+1] == '#'  ||
                    src[x+cx-1]=='#' || src[x+cx]=='#' || src[x+cx+1] == '#' {
                    dst[x] = '#'

                    // rule 3. A tree ignites with probability f
                    // even if no neighbor is burning
                } else if rand.Float64() < f {
                    dst[x] = '#'
                }
            default:
                // rule 4. An empty space fills with a tree with probability p
                if rand.Float64() < p {
                    dst[x] = 'T'
                }
            }
        }
    }
}


import 'dart:math' as Math;
cube(x) => x*x*x;
cuberoot(x)  => Math.pow(x, 1/3);
compose(f,g) => ((x)=>f(g(x)));
main(){
  var functions = [Math.sin, Math.exp, cube];
  var inverses = [Math.asin, Math.log, cuberoot];
  for (int i = 0; i < 3; i++){
    print(compose(functions[i], inverses[i])(0.5));
  }
}


program First_class_functions;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.Math;

type
  TFunctionTuple = record
    forward, backward: TFunc<Double, Double>;
    procedure Assign(forward, backward: TFunc<Double, Double>);
  end;

  TFunctionTuples = array of TFunctionTuple;

var
  cube, croot, fsin, fcos, faSin, faCos: TFunc<Double, Double>;
  FunctionTuples: TFunctionTuples;
  ft: TFunctionTuple;

{ TFunctionTuple }

procedure TFunctionTuple.Assign(forward, backward: TFunc<Double, Double>);
begin
  self.forward := forward;
  self.backward := backward;
end;

begin
  cube :=
    function(x: Double): Double
    begin
      result := x * x * x;
    end;

  croot :=
    function(x: Double): Double
    begin
      result := Power(x, 1 / 3.0);
    end;

  fsin :=
    function(x: Double): Double
    begin
      result := Sin(x);
    end;

  fcos :=
    function(x: Double): Double
    begin
      result := Cos(x);
    end;

  faSin :=
    function(x: Double): Double
    begin
      result := ArcSin(x);
    end;

  faCos :=
    function(x: Double): Double
    begin
      result := ArcCos(x);
    end;

  SetLength(FunctionTuples, 3);
  FunctionTuples[0].Assign(fsin, faSin);
  FunctionTuples[1].Assign(fcos, faCos);
  FunctionTuples[2].Assign(cube, croot);

  for ft in FunctionTuples do
    Writeln(ft.backward(ft.forward(0.5)):2:2);

  readln;
end.


function r = fivenum(x)
	r = quantile(x,[0:4]/4);
end;


import Control.Monad (replicateM, unless)
import Data.List (tails, transpose)
import System.Random (randomRIO)

data Cell
  = Empty
  | Tree
  | Fire
  deriving (Eq)

instance Show Cell where
  show Empty = " "
  show Tree = "T"
  show Fire = "$"

randomCell :: IO Cell
randomCell = fmap ([Empty, Tree] !!) (randomRIO (0, 1) :: IO Int)

randomChance :: IO Double
randomChance = randomRIO (0, 1.0) :: IO Double

rim :: a -> [[a]] -> [[a]]
rim b = fmap (fb b) . (fb =<< rb)
  where
    fb = (.) <$> (:) <*> (flip (++) . return)
    rb = fst . unzip . zip (repeat b) . head

take3x3 :: [[a]] -> [[[a]]]
take3x3 = concatMap (transpose . fmap take3) . take3
  where
    take3 = init . init . takeWhile (not . null) . fmap (take 3) . tails

list2Mat :: Int -> [a] -> [[a]]
list2Mat n = takeWhile (not . null) . fmap (take n) . iterate (drop n)

evolveForest :: Int -> Int -> Int -> IO ()
evolveForest m n k = do
  let s = m * n
  fs <- replicateM s randomCell
  let nextState xs = do
        ts <- replicateM s randomChance
        vs <- replicateM s randomChance
        let rv [r1, [l, c, r], r3] newTree fire
              | c == Fire = Empty
              | c == Tree && Fire `elem` concat [r1, [l, r], r3] = Fire
              | c == Tree && 0.01 >= fire = Fire
              | c == Empty && 0.1 >= newTree = Tree
              | otherwise = c
        return $ zipWith3 rv xs ts vs
      evolve i xs =
        unless (i > k) $
        do let nfs = nextState $ take3x3 $ rim Empty $ list2Mat n xs
           putStrLn ("\n>>>>>> " ++ show i ++ ":")
           mapM_ (putStrLn . concatMap show) $ list2Mat n xs
           nfs >>= evolve (i + 1)
  evolve 1 fs

main :: IO ()
main = evolveForest 6 50 3


func apply(fun, x) { y => fun(x, y) }

func sum(x, y) { x + y }

let sum2 = apply(sum, 2)


negate:
	- 0

set :A [ @++ $ @negate @-- ]

set :B [ @-- $ @++ @negate ]

test n:
	for i range 0 -- len A:
		if /= n call compose @B! i @A! i n:
			return false
	true

test to-num !prompt "Enter a number: "
if:
	!print "f^-1(f(x)) = x"
else:
	!print "Something went wrong."