set_time_limit(300);
header("Content-Type: image/png");

class Julia {

	static private $started = false;

	public static function start() {
		if (!self::$started) {
			self::$started = true;
			new self;
		}
	}

	const AXIS_REAL 	= 0;
	const AXIS_IMAGINARY 	= 1;
	const C 		= [-0.75, 0.1];
	const RADII 		= [1, 0.5];
	const CENTER 		= [0, 0];
	const MAX_ITERATIONS 	= 100;
	const TICK_SPACING 	= 0.001;

	private $maxDistance;
	private $imageResource;
	private $whiteColorResource;
	private $z0 = [];

	private function __construct() {
		$this->maxDistance = max($this->distance(self::C), 2);
		$this->imageResource = imagecreate(
			$this->coordinateToPixel(self::RADII[self::AXIS_REAL], self::AXIS_REAL),
			$this->coordinateToPixel(self::RADII[self::AXIS_IMAGINARY], self::AXIS_IMAGINARY)
		);
		imagecolorallocate($this->imageResource, 0, 0, 0);
		$this->whiteColorResource = imagecolorallocate($this->imageResource, 255, 255, 255);

		for ($x = self::CENTER[self::AXIS_REAL] - self::RADII[self::AXIS_REAL];
		$x <= self::CENTER[self::AXIS_REAL] + self::RADII[self::AXIS_REAL]; $x += self::TICK_SPACING) {
			$z0[self::AXIS_REAL] = $x;

			for ($y = self::CENTER[self::AXIS_IMAGINARY] - self::RADII[self::AXIS_IMAGINARY];
			$y <= self::CENTER[self::AXIS_IMAGINARY] + self::RADII[self::AXIS_IMAGINARY]; $y += self::TICK_SPACING) {
				$z0[self::AXIS_IMAGINARY] = $y;
				$iterations = 1;
				do {
					$z0 = $this->q($z0);
					$iterations++;
				} while($iterations < self::MAX_ITERATIONS && $this->distance($z0) <= $this->maxDistance);

				if ($iterations !== self::MAX_ITERATIONS) {
					imagesetpixel(
						$this->imageResource,
						$this->coordinateToPixel($x, self::AXIS_REAL),
						$this->coordinateToPixel($y, self::AXIS_IMAGINARY),
						$this->whiteColorResource
					);
				}
				$z0[self::AXIS_REAL] = $x;
			}
		}
	}

	public function __destruct() {
		imagepng($this->imageResource);
		imagedestroy($this->imageResource);
	}

	private function q($z) {
		return [ ($z[self::AXIS_REAL] ** 2) - ($z[self::AXIS_IMAGINARY] ** 2) + self::C[self::AXIS_REAL],
                       (2 * $z[self::AXIS_REAL] * $z[self::AXIS_IMAGINARY]) + self::C[self::AXIS_IMAGINARY] ];
	}

	private function distance($z) {
		return sqrt( ($z[self::AXIS_REAL] ** 2) + ($z[self::AXIS_IMAGINARY] ** 2) );
	}

	private function coordinateToPixel($coordinate, $axis) {
		return ($coordinate + self::RADII[$axis]) * (self::TICK_SPACING ** -1);
	}
}

Julia::start();


float cX = -0.7;
float cY = 0.27015;
float zx, zy;
float maxIter = 300;

void setup() {
  size(640, 480);
}

void draw() {
  for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
      zx = 1.5 * (x - width / 2) / (0.5 * width);
      zy = (y - height / 2) / (0.5 * height);
      float i = maxIter;
      while (zx * zx + zy * zy < 4 && i > 0) {
        float tmp = zx * zx - zy * zy + cX;
        zy = 2.0 * zx * zy + cY;
        zx = tmp;
        i -= 1;
      }
     colorMode(HSB);
     color c = color(i / maxIter * 255, 255,  i > 1 ? 255 : 0);
     set(x, y, c);
    }
  }
  noLoop();
}


from PIL import Image

if __name__ == "__main__":
	w, h, zoom = 800,600,1
	bitmap = Image.new("RGB", (w, h), "white")
	pix = bitmap.load()

	cX, cY = -0.7, 0.27015
	moveX, moveY = 0.0, 0.0
	maxIter = 255

	for x in range(w):
		for y in range(h):
			zx = 1.5*(x - w/2)/(0.5*zoom*w) + moveX
			zy = 1.0*(y - h/2)/(0.5*zoom*h) + moveY
			i = maxIter
			while zx*zx + zy*zy < 4 and i > 1:
				tmp = zx*zx - zy*zy + cX
				zy,zx = 2.0*zx*zy + cY, tmp
				i -= 1
			# convert byte to RGB (3 bytes), kinda magic to get nice colors
			pix[x][y] = (i << 21) + (i << 10) + i*8

	bitmap.show()


;; Based on Mandelbrot code (GPL) from:
;;  https://github.com/hebr3/Mandelbrot-Set-Racket/blob/master/Mandelbrot.v6.rkt
;; Julia set algoithm (and coloring) from:
;;  http://lodev.org/cgtutor/juliamandelbrot.html
;; HSV code (GPL) based on:
;;  https://github.com/takikawa/pict-utils/blob/master/pict-utils/hsv.rkt

#lang racket

;; Required to generate image
(require picturing-programs)

;; CONSTANTS - NUMBERS
(define DEPTH  300)
(define WIDTH  800)
(define HEIGHT 600)

;; Structures
(struct posn [x y] #:transparent)

;; CONSTANTS - GRAPHIC
(define BACKGROUND (rectangle WIDTH HEIGHT 'solid 'grey))
(define jcnst (posn -0.7 0.27015))

;; PROCEDURES
;; make an RGB color from HSV values
(define (make-color/hsv hue saturation value)
  (define chroma (* saturation value))
  (define hue* (/ (remainder* hue (* 2 pi)) (/ pi 3)))
  (define X (* chroma (- 1 (abs (- (remainder* hue* 2) 1)))))
  (define-values (r1 g1 b1)
    (cond [(and (<= 0 hue*) (< hue* 1)) (values chroma X 0)]
          [(and (<= 1 hue*) (< hue* 2)) (values X chroma 0)]
          [(and (<= 2 hue*) (< hue* 3)) (values 0 chroma X)]
          [(and (<= 3 hue*) (< hue* 4)) (values 0 X chroma)]
          [(and (<= 4 hue*) (< hue* 5)) (values X 0 chroma)]
          [(and (<= 5 hue*) (< hue* 6)) (values chroma 0 X)]))
  (define m (- value chroma))
  (apply make-color (map (λ (x) (exact-round (* 255 (+ x m))))
                         (list r1 g1 b1))))

;; general remainder
(define (remainder* n1 n2)
  (define num-divides (/ n1 n2))
  (- n1 (* (floor num-divides) n2)))

;; Posn -> Number
;; Returns the magnitude of the posn
(define (posn-mag pt)
  (let ([pt-x (posn-x pt)]
        [pt-y (posn-y pt)])
    (sqrt (+ (* pt-x pt-x)
                 (* pt-y pt-y)))))

;; Posn Posn -> Posn
;; Posn addition
(define (posn+ pt1 pt2)
  (let ([pt1-x (posn-x pt1)]
        [pt1-y (posn-y pt1)]
        [pt2-x (posn-x pt2)]
        [pt2-y (posn-y pt2)])
    (posn (+ pt1-x pt2-x)
          (+ pt1-y pt2-y))))

;; Posn Posn -> Posn
;; Posn multiplication
(define (posn* pt1 pt2)
  (let ([x1 (posn-x pt1)]
        [y1 (posn-y pt1)]
        [x2 (posn-x pt2)]
        [y2 (posn-y pt2)])
    (posn (- (* x1 x2) (* y1 y2))
          (+ (* x1 y2) (* x2 y1)))))

;; Posn -> Posn
;; Posn square
(define (posn-sqr pt)
  (posn* pt pt))

;; Posn -> Number
;; Returns the julia set  escape number for a given complex number
;; given in rectangular coordinates.
(define (julia-set-number  start)
  (define (iter result count)
    (cond [(> (posn-mag result) 2) (sub1 count)]
          [(> count DEPTH) DEPTH]
          [else (iter (posn+ jcnst (posn-sqr result))
                      (add1 count))]))
  (iter start 1))

;; Number -> Number
;; Returns the scaled location of a point
(define (scaled-x x)
  (/ (* 1.5 (- x (/ WIDTH 2))) (* 0.5 WIDTH)))
(define (scaled-y y)
  (/ (- y (/ HEIGHT 2)) (* 0.5 HEIGHT)))

;; Generates image
(define M-Image
  (map-image
   (λ (x y c)
     (let* ([ref (julia-set-number  (posn (scaled-x x) (scaled-y y)))])
       (cond [(= ref DEPTH) (name->color 'black)]
             [else (make-color/hsv (* 2 (* pi (/ ref DEPTH))) 1 1)]) ))
 BACKGROUND))

M-Image ;show image if using drracket

(save-image M-Image "julias.png")


/*REXX program  displays  an  ASCII plot   (character plot)   of a  Julia set.          */
parse arg real imag fine .                       /*obtain optional arguments from the CL*/
if real=='' | real==","  then real= -0.8         /*Not specified?  Then use the default.*/
if imag=='' | imag==","  then imag=  0.156       /* "      "         "   "   "     "    */
if fine=='' | fine==","  then fine= 50           /* "      "         "   "   "     "    */
_=scrsize(); parse var _ sd sw; sd=sd-4; sw=sw-1 /*obtain useable area for the terminal.*/
                                                 /*$:  the plot line that is constructed*/
         do   v= -sd%2  to sd%2;     $=          /*step through  vertical   axis values.*/
           do h= -sw%2  to sw%2                  /*  "     "    horizontal    "     "   */
           x=h/sw*2                              /*calculate the initial   X   value.   */
           y=v/sd*2                              /*    "      "     "      Y     "      */
           @='■';    do fine                     /*FINE: is the "fineness" for the plot.*/
                     zr=x*x - y*y + real         /*calculate a new   real   Julia point.*/
                     zi=x*y*2     + imag         /*    "     "  "  imaginal   "     "   */
                     if zr**2>10000  then do; @=' '; leave; end    /*is  ZR  too large? */
                     x=zr;    y=zi                                 /*use this new point.*/
                     end   /*50*/
           $=$ || @                              /*append the plot char to the plot line*/
           end            /*h*/
         if $\=''  then say strip($, 'T')        /*only display a plot line if non-blank*/
         end   /*v*/                             /*stick a fork in it,  we're all done. */


# Project : Julia Set

load "guilib.ring"

new qapp
        {
        win1 = new qwidget() {
                  setwindowtitle("Julia set")
                  setgeometry(100,100,500,400)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,400,400)
                              settext("")
                  }
                  new qpushbutton(win1) {
                          setgeometry(150,300,100,30)
                          settext("draw")
                          setclickevent("draw()")
                  }
                  show()
        }
        exec()
        }

func draw
        p1 = new qpicture()
               color = new qcolor() {
               setrgb(0,0,255,255)
        }
        pen = new qpen() {
                 setcolor(color)
                 setwidth(1)
        }
        paint = new qpainter() {
                  begin(p1)
                  setpen(pen)

        creal=-0.8
        cimag=0.156
        for v=-16 to 16
             for h=-64 to 64
                   x=h/40
                   y=v/20
                   for i=1 to 50
                         flag = 1
                         zreal=x*x-y*y+creal
                         zimag=x*y*2+cimag
                         if zreal*zreal>1000 flag = 0 loop ok
                         x=zreal
                         y=zimag
                  next
                  if flag = 1
                     drawpoint(h+100,150-v)
                  ok
             next
        next
        endpaint()
        }
        label1 { setpicture(p1) show() }


def julia(c_real, c_imag)
  puts Complex(c_real, c_imag)
  -1.0.step(1.0, 0.04) do |v|
    puts -1.4.step(1.4, 0.02).map{|h| judge(c_real, c_imag, h, v)}.join
  end
end

def judge(c_real, c_imag, x, y)
  50.times do
    z_real = (x * x - y * y) + c_real
    z_imag = x * y * 2 + c_imag
    return " "  if z_real**2 > 10000
    x, y = z_real, z_imag
  end
  "#"
end

julia(-0.8, 0.156)


extern crate image;

use image::{ImageBuffer, Pixel, Rgb};

fn main() {
    // 4 : 3 ratio is nice
    let width = 8000;
    let height = 6000;

    let mut img = ImageBuffer::new(width as u32, height as u32);

    // constants to tweak for appearance
    let cx = -0.9;
    let cy = 0.27015;
    let iterations = 110;

    for x in 0..width {
        for y in 0..height {
            let inner_height = height as f32;
            let inner_width = width as f32;
            let inner_y = y as f32;
            let inner_x = x as f32;

            let mut zx = 3.0 * (inner_x - 0.5 * inner_width) / (inner_width);
            let mut zy = 2.0 * (inner_y - 0.5 * inner_height) / (inner_height);

            let mut i = iterations;

            while zx * zx + zy * zy < 4.0 && i > 1 {
                let tmp = zx * zx - zy * zy + cx;
                zy = 2.0 * zx * zy + cy;
                zx = tmp;
                i -= 1;
            }

            // guesswork to make the rgb color values look okay
            let r = (i << 3) as u8;
            let g = (i << 5) as u8;
            let b = (i << 4) as u8;
            let pixel = Rgb::from_channels(r, g, b, 0);
            img.put_pixel(x as u32, y as u32, pixel);
        }
    }

    let _ = img.save("output.png");

}


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

import javax.swing._

object JuliaSet extends App {
  SwingUtilities.invokeLater(() =>
    new JFrame("Julia Set") {

      class JuliaSet() extends JPanel {
        private val (maxIter, zoom) = (300, 1)

        override def paintComponent(gg: Graphics): Unit = {
          val g = gg.asInstanceOf[Graphics2D]

          def drawJuliaSet(g: Graphics2D): Unit = {
            val (w, h) = (getWidth, getHeight)
            val image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB)
            val (cX, cY) = (-0.7, 0.27015)
            val moveX, moveY = 0
            var zx, zy = 0.0

            for (x <- 0 until w;
                 y <- 0 until h) {
              zx = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX
              zy = (y - h / 2) / (0.5 * zoom * h) + moveY
              var i: Float = maxIter
              while (zx * zx + zy * zy < 4 && i > 0) {
                val tmp = zx * zx - zy * zy + cX
                zy = 2.0 * zx * zy + cY
                zx = tmp
                i -= 1
              }
              val c = Color.HSBtoRGB((maxIter / i) % 1, 1, if (i > 0) 1 else 0)
              image.setRGB(x, y, c)
            }
            g.drawImage(image, 0, 0, null)
          }

          super.paintComponent(gg)
          g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
          drawJuliaSet(g)
        }

        setBackground(Color.white)
        setPreferredSize(new Dimension(800, 600))
      }

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

}


require('Imager')

var (w, h) = (640, 480)
var img = %s'Imager'.new(xsize => w, ysize => h, channels => 3)

var maxIter = 50
var c = Complex(-0.388, 0.613)

var color = %s'Imager::Color'.new('#000000')

for x,y in (^w ~X ^h) {
    var i = maxIter
    var z = Complex((x - w/2) / w * 3, (y - h/2) / h * 2)
    while (z.abs < 2 && --i) {
        z = (z*z + c)
    }
    color.set(hsv => [i / maxIter * 360, 1, i])
    img.setpixel(x => x, y => y, color => color)
}

img.write(file => "JuliaSet_sidef.png")


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

var MaxIters = 300
var Zoom = 1
var MoveX = 0
var MoveY = 0
var CX = -0.7
var CY = 0.27015

class JuliaSet {
    construct new(width, height) {
        Window.title = "Julia Set"
        Window.resize(width, height)
        Canvas.resize(width, height)
        _w = width
        _h = height
    }

    init() {
        Canvas.cls(Color.white)
        createJulia()
    }

    createJulia() {
        for (x in 0..._w) {
            for (y in 0..._h) {
                var zx = 1.5 * (x - _w / 2) / (0.5 * Zoom * _w) + MoveX
                var zy = (y - _h / 2) / (0.5 * Zoom * _h) + MoveY
                var i = MaxIters
                while (zx * zx + zy * zy < 4 && i > 0) {
                    var tmp = zx * zx - zy * zy + CX
                    zy = 2 * zx * zy + CY
                    zx = tmp
                    i = i - 1
                }
                var c = Color.rgb(i % 256, i % 256, (i*8) % 256)
                Canvas.pset(x, y, c)
            }
        }
    }

    update() {}

    draw(alpha) {}
}

var Game = JuliaSet.new(800, 600)


fcn juliaSet{
   w,h,zoom:=800,600, 1;
   bitmap:=PPM(w,h,0xFF|FF|FF);  // White background

   cX,cY:=-0.7, 0.27015;
   moveX,moveY:=0.0, 0.0;
   maxIter:=255;

   foreach x,y in (w,h){
      zx:=1.5*(x - w/2)/(0.5*zoom*w) + moveX;
      zy:=1.0*(y - h/2)/(0.5*zoom*h) + moveY;
      i:=maxIter;
      while(zx*zx + zy*zy < 4 and i > 1){
	 tmp:=zx*zx - zy*zy + cX;
	 zy,zx=2.0*zx*zy + cY, tmp;
	 i-=1;
      }
      // convert byte to RGB (3 bytes), kinda magic to get nice colors
      bitmap[x,y]=i.shiftLeft(21) + i.shiftLeft(10) + i*8;
   }

   bitmap.writeJPGFile("juliaSet.jpg",True);
}();


BYTE lastStick=[255]
BYTE lastTrig=[255]

PROC DrawCross(BYTE s)
  BYTE size=[5]
  CARD x
  BYTE y

  IF s>=9 AND s<=11 THEN
    x=size
  ELSEIF s>=5 AND s<=7 THEN
    x=159-size
  ELSE
    x=79
  FI

  IF s=6 OR s=10 OR s=14 THEN
    y=size
  ELSEIF s=5 OR s=9 OR s=13 THEN
    y=79-size
  ELSE
    y=39
  FI

  Plot(x-size,y)
  DrawTo(x+size,y)
  Plot(x,y-size)
  DrawTo(x,y+size)
RETURN

PROC UpdateStatus(BYTE currStick,currTrig)
  IF currStick#lastStick THEN
    Color=0 DrawCross(lastStick)
    Color=1 DrawCross(currStick)
    lastStick=currStick
  FI

  IF currTrig#lastTrig THEN
    Print("Button pressed: ")
    IF currTrig THEN
      PrintE("no ")
    ELSE
      PrintE("yes")
    FI
    Put(28) ;move cursor up
    lastTrig=currTrig
  FI
RETURN

PROC Main()
  BYTE CH=$02FC,COLOR1=$02C5,COLOR2=$02C6,
    CRSINH=$02F0 ;Controls visibility of cursor
  BYTE currStick,currTrig

  Graphics(7)
  Color=1
  COLOR1=$0C
  COLOR2=$02
  CRSINH=1 ;hide cursor

  DO
    currStick=Stick(0)
    currTrig=STrig(0)
    UpdateStatus(currStick,currTrig)
  UNTIL CH#$FF
  OD
  CH=$FF
RETURN


100 GOSUB 400
110 P2 = PDL(2) : IF P2 <> O2 THEN O2 = P2 : VTAB 23 : HTAB 33 : PRINT P2; TAB(37);
120 B2 = FNB(2) : IF B2 <> N2 THEN N2 = B2 : VTAB 24 : HTAB 15 : PRINT P$(B2);
130 P3 = PDL(3) : IF P3 <> O3 THEN O3 = P3 : VTAB 23 : HTAB 37 : PRINT P3; : CALL -868
140 X = INT(P3 * RX) : Y = INT(P2 * RY(F))
150 O = (X1 = X2 AND Y1 = Y2) + 1
160 N = (X = X1 AND Y = Y1) + 1
170 IF X <> X2 OR Y <> Y2 THEN XDRAW N AT X, Y : XDRAW O AT X2, Y2 : X2 = X : Y2 = Y : O = N
200 P0 = PDL(0) : IF P0 <> O0 THEN O0 = P0 : VTAB 22 : HTAB 33 : PRINT P0; TAB(37);
210 B0 = FNB(0) : IF B0 <> N0 THEN N0 = B0 : VTAB 22 : HTAB 15 : PRINT P$(B0);
220 P1 = PDL(1) : IF P1 <> O1 THEN O1 = P1 : VTAB 22 : HTAB 37 : PRINT P1; : CALL -868
230 B1 = FNB(1) : IF B1 <> N1 THEN N1 = B1 : VTAB 23 : HTAB 15 : PRINT P$(B1);
240 X = INT(P0 * RX) : Y = INT(P1 * RY(F))
250 O = (X1 = X2 AND Y1 = Y2) + 1
260 N = (X = X2 AND Y = Y2) + 1
270 IF X <> X1 OR Y <> Y1 THEN XDRAW N AT X, Y : XDRAW O AT X1, Y1 : X1 = X : Y1 = Y
300 K = PEEK(-16384) : IF K < 128 THEN 110
310 POKE-16368,0
320 IF K = 198 OR K = 200 THEN F = PEEK(-16302) ^ 0 : GOTO 110HIDE
330 IF K = 155 OR K = 211 THEN F = PEEK(-16301) * 0 : GOTO 110SHOW
340 TEXT : END
400 HOME : HGR
410 DEF FN B(B) = PEEK(49249 + B) > 127
420 P$(0) = "NOT PRESSED" : P$(1) = "PRESSED    "
430 VTAB 21 : PRINT "BUTTON:";
440 PRINT TAB(28); "JOYSTICK:"
450 PRINT "   OPEN APPLE "P$(0);
460 PRINT TAB(29); "ONE"
470 PRINT " CLOSED APPLE "P$(0);
480 PRINT TAB(29); "TWO"
490 PRINT TAB(9); "SHIFT "P$(0);
500 RX = 35 / 32 : RY(0) = 5 / 8 : RY(1) = 3 / 4
510 DATA2,0,6,0,3,0,29,15,20,6,0
520 FOR I = 768 TO 778 : READ B
530 POKE I, B : NEXT : POKE 232, 0 : POKE 233, 3
550 ROT = 0 : SCALE = 7 : XDRAW 1 AT X1, Y1
560 O0 = -1 : O1 = O0 : O2 = O0 : O3 = O0
570 RETURN


; Uncomment if Gdip.ahk is not in your standard library
; #Include, Gdip.ahk

; Comment for lower CPU usage
SetBatchLines, -1

JoystickNumber := 0     ; (1-16) or (0 = Auto-detect)
CrosshairSize := 100
BarWidth := 50
BarSpacing := BarWidth + 8
Color1 := 0x99000000
Color2 := 0x99ffffff
Color3 := 0x99ff6600
Color4 := 0xff0066ff
Color5 := 0xffff6600
Font := "Arial"
FontSize1 := 20
FontSize2 := 30
Lineweight1 := 8
Lineweight2 := 3
Lineweight3 := 2
Lineweight4 := 4
Show2ndCrosshair := true
AxisLabelHeight := 47

#SingleInstance, Force
#NoEnv
OnExit, Exit
SysGet, MWA, MonitorWorkArea
CrosshairOffset := CrosshairSize // 2
, CircleOffset := CrosshairOffset - 5
, CircleSize := CrosshairSize - 10
, TaskBarHeight := A_ScreenHeight - MWABottom + Lineweight1 // 2
, ScaleX := A_ScreenWidth / 100
, ScaleY1 := (A_ScreenHeight - TaskBarHeight - AxisLabelHeight) / 100
, ScaleY2 := A_ScreenHeight / 100
, BarCenter := (MWABottom - AxisLabelHeight) // 2 + AxisLabelHeight
, BorderBot := MWABottom - Lineweight1 // 2 + 2
, PieSize := 400
, PieX := (A_ScreenWidth - PieSize) // 2
, PieY := (A_ScreenHeight - PieSize) // 2
, BarHeight := A_ScreenHeight - AxisLabelHeight - TaskBarHeight
, AxisTextOffset := BarWidth > 32 ? (BarWidth - 32) // 2 : 0
, Axis_Array := {"X": "X", "Y": "Y"}
, MaxI :=  2

; Auto-detect the joystick number if called for
if (JoystickNumber < 1) {
    Loop, 16 {
        GetKeyState, Joy_Name, %A_Index%JoyName
        if (Joy_Name) {
            JoystickNumber := A_Index
            break
        }
    }
    if (!JoystickNumber) {
        MsgBox The system does not appear to have any joysticks.
        ExitApp
    }
}
else {
    GetKeyState, Joy_Name, %JoystickNumber%JoyName
    if (!Joy_Name) {
        MsgBox The system does not appear to have a joystick number %JoystickNumber%.
        ExitApp
    }
}

if (!pToken := Gdip_Startup()) {
    MsgBox, 48, Gdiplus error!, Gdiplus failed to start. Please ensure you have Gdiplus on your system.
    ExitApp
}

If (!Gdip_FontFamilyCreate(Font)) {
   MsgBox, 48, Font error!, The font you have specified does not exist on your system.
   ExitApp
}

; Get joystick information
SetFormat, FloatFast, 03.2
GetKeyState, Joy_Buttons, % JoystickNumber "JoyButtons"
GetKeyState, Joy_Info, % JoystickNumber "JoyInfo"
Loop, Parse, Joy_Info
    if (A_LoopField != "C" && A_LoopField != "D" && A_LoopField != "P")
        Axis_Array[A_LoopField] := A_LoopField
        , %A_LoopField% := true
        , MaxI++
    else
        %A_LoopField% := true

; Setup Gdip
Gui, 1: -Caption +E0x80000 +LastFound +AlwaysOnTop +ToolWindow +OwnDialogs
Gui, 1: Show, NA
hwnd1 := WinExist()
, hbm := CreateDIBSection(A_ScreenWidth, A_ScreenHeight)
, hdc := CreateCompatibleDC()
, obm := SelectObject(hdc, hbm)
, G1 := Gdip_GraphicsFromHDC(hdc)
, Gdip_SetSmoothingMode(G1, 4)
, pPen1 := Gdip_CreatePen(Color1, Lineweight1)
, pPen2 := Gdip_CreatePen(Color2, Lineweight2)
, pPen3 := Gdip_CreatePen(Color4, Lineweight3)
, pPen4 := Gdip_CreatePen(Color5, Lineweight4)
, pBrush1 := Gdip_BrushCreateSolid(Color1)
, pBrush2 := Gdip_BrushCreateSolid(Color3)

; Crosshair 2
if ((R || U) && Show2ndCrosshair) {
    pPen5 := Gdip_CreatePen(Color5, Lineweight3)
    , pPen6 := Gdip_CreatePen(Color4, Lineweight4)
    , joy_r := joy_u := 50
}

; Bar X-offsets
for key, val in Axis_Array
    %val%X := A_ScreenWidth - MaxI * BarSpacing + BarSpacing * (A_Index - 1) + 3

; Info box
IBH1 := 150
, IBW1 := 450
, IBX1 := A_ScreenWidth - MaxI * BarSpacing - IBW1
, IBY1 := A_ScreenHeight - TaskBarHeight - IBH1 + Lineweight1 // 2
, IBH2 := IBH1 - 8
, IBW2 := IBW1 - 8
, IBX2 := IBX1 + 4
, IBY2 := IBY1 + 4
, FontOptions1 := "x" (IBX1 + 8) " y" (IBY1 + 8) " w" IBW1 - 20 " Left c" SubStr(Color2, 3) " r4 s" FontSize1 " Bold"

; Axis box
ABH1 := AxisLabelHeight + 4
, ABW1 := MaxI * BarSpacing
, ABX1 := A_ScreenWidth - MaxI * BarSpacing
, ABY1 := 0
, ABH2 := ABH1 - 16
, ABW2 := ABW1 - 8
, ABX2 := ABX1 + 4
, ABY2 := ABY1 + 4
, FontOptions2 := " y" ABY1 + AxisLabelHeight - 40 " w" ABW1 - 10 " Left c" SubStr(Color2, 3) " r4 s" FontSize2 " Bold"

; Update graphics
Loop, {
    Buttons_Down := ""
    Loop, %Joy_Buttons% {
        GetKeyState, joy%A_Index%, %JoystickNumber%joy%A_Index%
        if (joy%A_Index% = "D")
            Buttons_Down .= " " A_Index
    }

    ; Info & axis boxes
    InfoText := Joy_Name " (#" JoystickNumber "):`n" Axis_Info "`nButtons Down: " Buttons_Down "`n`n(Ctrl+Esc to exit)"
    , Gdip_FillRoundedRectangle(G1, pBrush1, IBX1, IBY1, IBW1, IBH1, 5)
    , Gdip_DrawRoundedRectangle(G1, pPen2, IBX2, IBY2, IBW2, IBH2, 5)
    , Gdip_TextToGraphics(G1, InfoText, FontOptions1, Font, A_ScreenWidth, A_ScreenHeight)
    , Gdip_FillRoundedRectangle(G1, pBrush1, ABX1, ABY1, ABW1, ABH1, 5)
    , Gdip_DrawRoundedRectangle(G1, pPen2, ABX2, ABY2, ABW2, ABH2, 5)

    ; Axis bars
    Axis_Info := ""
    for key, val in Axis_Array {
        GetKeyState, joy_%val%, % JoystickNumber "Joy" val
        Axis_Info .= val joy_%val% "  "
        if (joy_%val% > 50)
            %val%Y := BarCenter
            , %val%h1 := (joy_%val% - 50) * ScaleY1
        else
            %val%Y := AxisLabelHeight + joy_%val% * ScaleY1  ;
            , Sc - (joy_%val% - 50) * ScaleY1
            , %val%h1 := BarCenter - %val%Y
        Gdip_FillRoundedRectangle(G1, pBrush2, %val%X, %val%Y, BarWidth, %val%h1, 2)
        , Gdip_DrawRoundedRectangle(G1, pPen1, %val%X, AxisLabelHeight, BarWidth, BarHeight, 5)
        , Gdip_DrawRoundedRectangle(G1, pPen2, %val%X, AxisLabelHeight, BarWidth, BarHeight, 5)
        , Gdip_TextToGraphics(G1, val, "x" (%val%X + AxisTextOffset) FontOptions2, Font, A_ScreenWidth, A_ScreenHeight)
    }

    ; POV hat
    If (P) {
        GetKeyState, Joy_P, %JoystickNumber%JoyPOV
        Axis_Info .= "  POV" Joy_P
        if (Joy_P > -1) {
			StartAngle := (Joy_P > 33750 || Joy_P <= 2250) ? 247.5 	; up
			: Joy_P > 29250 ? 202.5		; up left
			: Joy_P > 24750 ? 157.5 	; left
			: Joy_P > 20250 ? 112.5 	; down left
			: Joy_P > 15750 ? 67.5 		; down
			: Joy_P > 11250 ? 22.5 		; down right
			: Joy_P > 6750 ? 337.5		; right
			: 292.5 					; up right
            , Gdip_FillPie(G1, pBrush2, PieX, PieY, PieSize, PieSize, StartAngle, 45)
            , Gdip_DrawPie(G1, pPen1, PieX, PieY, PieSize, PieSize, StartAngle, 45)
            , Gdip_DrawPie(G1, pPen2, PieX, PieY, PieSize, PieSize, StartAngle, 45)
        }
    }

    ; Crosshair 1
    CenterX := ScaleX * joy_x
    , CenterY := ScaleY2 * joy_y
    , Gdip_DrawLine(G1, pPen3, CenterX-CrosshairOffset, CenterY, CenterX+CrosshairOffset, CenterY)
    , Gdip_DrawLine(G1, pPen3, CenterX, CenterY-CrosshairOffset, CenterX, CenterY+CrosshairOffset)
    , Gdip_DrawEllipse(G1, pPen4, CenterX-CircleOffset, CenterY-CircleOffset, CircleSize, CircleSize)
    , Gdip_DrawEllipse(G1, pPen4, CenterX-3, CenterY-3, 6, 6)

    ; Crosshair 2
    if ((R || U) && Show2ndCrosshair)
        CenterU := ScaleX * joy_u
        , CenterR := ScaleY2 * joy_r
        , Gdip_DrawLine(G1, pPen5, CenterU-CrosshairOffset, CenterR, CenterU+CrosshairOffset, CenterR)
        , Gdip_DrawLine(G1, pPen5, CenterU, CenterR-CrosshairOffset, CenterU, CenterR+CrosshairOffset)
        , Gdip_DrawEllipse(G1, pPen6, CenterU-CircleOffset, CenterR-CircleOffset, CircleSize, CircleSize)
        , Gdip_DrawEllipse(G1, pPen6, CenterU-3, CenterR-3, 6, 6)

    UpdateLayeredWindow(hwnd1, hdc, 0, 0, A_ScreenWidth, A_ScreenHeight)
    , Gdip_GraphicsClear(G1)
}
return

^Esc::
Exit:
Gdip_Shutdown(pToken)
ExitApp


      VDU 23,22,512;512;8,16,16,0
      VDU 5

      GCOL 4,15
      REPEAT
        B% = ADVAL(0)
        X% = ADVAL(1) / 64
        Y% = 1023 - ADVAL(2) / 64
        PROCjoy(B%,X%,Y%)
        WAIT 4
        PROCjoy(B%,X%,Y%)
      UNTIL FALSE
      END

      DEF PROCjoy(B%,X%,Y%)
      LOCAL I%
      LINE X%-32,Y%,X%+32,Y% : LINE X%,Y%-32,X%,Y%+32
      VDU 30
      FOR I% = 0 TO 15
        IF B% AND 1<<I% THEN PRINT "Button "; I%+1 " pressed";
        VDU 10,13
      NEXT
      ENDPROC


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

void clear() {
	for(int n = 0;n < 10; n++) {
		printf("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\r\n\r\n\r\n");
	}
}

#define UP    "00^00\r\n00|00\r\n00000\r\n"
#define DOWN  "00000\r\n00|00\r\n00v00\r\n"
#define LEFT  "00000\r\n<--00\r\n00000\r\n"
#define RIGHT "00000\r\n00-->\r\n00000\r\n"
#define HOME  "00000\r\n00+00\r\n00000\r\n"

int main() {
	clear();
	system("stty raw");

	printf(HOME);
	printf("space to exit; wasd to move\r\n");
	char c = 1;

	while(c) {
		c = getc(stdin);
		clear();

		switch (c)
		{
			case 'a':
				printf(LEFT);
				break;
			case 'd':
				printf(RIGHT);
				break;
			case 'w':
				printf(UP);
				break;
			case 's':
				printf(DOWN);
				break;
			case ' ':
				c = 0;
				break;
			default:
				printf(HOME);
		};

		printf("space to exit; wasd key to move\r\n");
	}

	system("stty cooked");
	system("clear");
	return 1;
}


5 rem joystick - commodore vic-20 (expanded)
6 rem for rosetta code
10 print chr$(147);:poke 37154,peek(37154) and 127
15 j1=37137:j2=37152:sc=4118:co=37910:x=11:y=11
20 poke sc+x+y*22,43:poke co+x+y*22,0
25 j=(not peek(j1) and28)/4
30 j=j+(not peek(j1) and32)/2
35 j=j+(not peek(j2) and128)/16
40 print chr$(19);"joy: ";
45 get k$:if k$="q" then print chr$(147):poke 37154,peek(37154)or128:end
50 ox=x:oy=y
60 if(j and 1) then y=1:ud$="u"
61 if(j and 2) then y=21:ud$="d"
62 if(j and 3)=0 then y=11:ud$=" "
63 if(j and 4) then x=0:lr$="l"
64 if(j and 8) then x=21:lr$="r"
65 if(j and 12)=0 then x=11:lr$=" "
66 if(j and 16) then f$="fire!":c=24
67 if(j and 16)=0 then f$="     ":c=43
70 print tab(5);ud$;tab(7);lr$;tab(9);f$;
75 poke sc+x+y*22,c:poke co+x+y*22,0
80 if (ox=x) and (oy=y) then goto 100
85 poke sc+ox+oy*22,32
100 goto 25


unit uMain;

interface

uses
  Winapi.Windows, System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms,
  Vcl.ExtCtrls, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    tmr1: TTimer;
    lblPosition: TLabel;
    procedure tmr1Timer(Sender: TObject);
    procedure FormPaint(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure DrawCrosshair(X, Y: Integer);
  end;

var
  Form1: TForm1;
  X: Integer = 0;
  Y: Integer = 0;

implementation

uses
  mmSystem, Vcl.Graphics;

{$R *.dfm}

procedure TForm1.DrawCrosshair(X, Y: Integer);
const
  RADIUS = 10;
  CROSS = 3;
begin
  Canvas.Brush.Color := clblack;
  Canvas.FillRect(ClientRect);
  with Canvas do
  begin
    Pen.Color := clWhite;
    pen.Width := 1;
    Ellipse(X - RADIUS, Y - RADIUS, X + RADIUS, Y + RADIUS);
    pen.Width := 2;
    MoveTo(X - CROSS * RADIUS, Y);
    LineTo(X + CROSS * RADIUS, Y);
    MoveTo(X, Y - CROSS * RADIUS);
    LineTo(X, Y + CROSS * RADIUS);
  end;
end;

procedure TForm1.FormPaint(Sender: TObject);
begin
  DrawCrosshair(X, Y);
end;

procedure TForm1.tmr1Timer(Sender: TObject);
var
  info: TJoyInfo;
begin
  if (joyGetPos(0, @info) = 0) then
  begin
    X := Round(ClientWidth * info.wXpos / MAXWORD);
    Y := Round(ClientHeight * info.wYpos / MAXWORD);
    lblPosition.Caption := Format('(%3d,%3d)', [X, Y]);
    Invalidate;
  end;
end;

end.


Screen 12

Dim As Single x, y
Dim As Integer buttons, result

Const JoystickID = 0

'This line checks to see if the joystick is ok.
If Getjoystick(JoystickID, buttons, x, y) Then
    Print "Joystick doesn't exist or joystick error."
    Print !"\nPress any key to continue."
    Sleep
    End
End If

Do
    result = Getjoystick(JoystickID, buttons, x, y)

    Locate 1,1
    Print ; "result:"; result; " x:"; x; " y:"; y; " Buttons:"; buttons, "", "", ""

    'This tests to see which buttons from 1 to 27 are pressed.
    For a As Integer = 0 To 26
        If (buttons And (1 Shl a)) Then
            Print "Button "; a; " pressed.    "
        Else
            Print "Button "; a; " not pressed."
        End If
    Next a
Loop


package main

import (
    "fmt"
    "github.com/nsf/termbox-go"
    "github.com/simulatedsimian/joystick"
    "log"
    "os"
    "strconv"
    "time"
)

func printAt(x, y int, s string) {
    for _, r := range s {
        termbox.SetCell(x, y, r, termbox.ColorDefault, termbox.ColorDefault)
        x++
    }
}

func readJoystick(js joystick.Joystick, hidden bool) {
    jinfo, err := js.Read()
    check(err)

    w, h := termbox.Size()
    tbcd := termbox.ColorDefault
    termbox.Clear(tbcd, tbcd)
    printAt(1, h-1, "q - quit")
    if hidden {
        printAt(11, h-1, "s - show buttons:")
    } else {
        bs := ""
        printAt(11, h-1, "h - hide buttons:")
        for button := 0; button < js.ButtonCount(); button++ {
            if jinfo.Buttons&(1<<uint32(button)) != 0 {
                // Buttons assumed to be numbered from 1, not 0.
                bs += fmt.Sprintf(" %X", button+1)
            }
        }
        printAt(28, h-1, bs)
    }

    // Map axis values in range -32767 to +32768 to termbox co-ordinates.
    x := int(float64((jinfo.AxisData[0]+32767)*(w-1)) / 65535)
    y := int(float64((jinfo.AxisData[1]+32767)*(h-2)) / 65535)
    printAt(x, y, "+") // display crosshair
    termbox.Flush()
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    // Under Linux the id is used to construct the joystick device name.
    // For example: id 0 will open device: "/dev/input/js0"
    // Under Windows the id is the actual numeric id of the joystick.
    jsid := 0
    // Optionally pass joystick id to be used as a command line argument.
    if len(os.Args) > 1 {
        i, err := strconv.Atoi(os.Args[1])
        check(err)
        jsid = i
    }

    js, jserr := joystick.Open(jsid)
    check(jserr)

    err := termbox.Init()
    check(err)
    defer termbox.Close()

    eventQueue := make(chan termbox.Event)
    go func() {
        for {
            eventQueue <- termbox.PollEvent()
        }
    }()

    ticker := time.NewTicker(time.Millisecond * 40)
    hidden := false // Controls whether button display hidden or not.

    for doQuit := false; !doQuit; {
        select {
        case ev := <-eventQueue:
            if ev.Type == termbox.EventKey {
                if ev.Ch == 'q' {
                    doQuit = true
                } else if ev.Ch == 'h' {
                    hidden = true
                } else if ev.Ch == 's' {
                    hidden = false
                }
            }
            if ev.Type == termbox.EventResize {
                termbox.Flush()
            }
        case <-ticker.C:
            readJoystick(js, hidden)
        }
    }
}


Start,Control Panel, Game Controllers, List:installed controllers,Click:Joystick,
Button:Properties,Button:Test


import qualified Graphics.UI.GLFW as GLFW -- cabal install GLFW-b
import Graphics.Win32.Key
import Control.Monad.RWS.Strict  (liftIO)

main = do
    liftIO $ do
          _ <- GLFW.init
          GLFW.pollEvents
          (jxrot, jyrot) <- liftIO $ getJoystickDirections GLFW.Joystick'1
          putStrLn $ (show jxrot) ++ " " ++ (show jyrot)
          w <- getAsyncKeyState 27 -- ESC pressed?
          if (w<1) then main else do
                     GLFW.terminate
                     return ()

getJoystickDirections :: GLFW.Joystick -> IO (Double, Double)

getJoystickDirections js = do
    maxes <- GLFW.getJoystickAxes js
    return $ case maxes of
      (Just (x:y:_)) -> (-y, x)
      _ -> ( 0, 0)


100 CLEAR SCREEN
110 DO
120   LET J=JOY(0) OR JOY(1) OR JOY(2)
130   PRINT AT 1,1:"                           ";:PRINT AT 1,1:"";
140   IF J BAND 1 THEN PRINT "right ";
150   IF J BAND 2 THEN PRINT "left ";
160   IF J BAND 4 THEN PRINT "down ";
170   IF J BAND 8 THEN PRINT "up ";
180   IF J BAND 16 THEN PRINT "fire ";
190 LOOP


using CSFML.LibCSFML, Gtk.ShortNames, Colors, Graphics, Cairo

#------------ input code ----------------------#

mutable struct Joystick
    devnum::Int
    isconnected::Bool
    hasXaxis::Bool
    nbuttons::Int
    pressed::Vector{Bool}
    ypos::Int
    xpos::Int
    name::String
    Joystick(n, b=2, c=false, x=true) = new(n, c, x, b, fill(false, b), 0, 0)
end

const devnum = 0
const buttons = 2
const jstick = Joystick(devnum, buttons)

function polljoystick(jstick, sleepinterval=0.05)
    while !sfJoystick_isConnected(jstick.devnum)
        sleep(0.25) # wait till connected
        sfJoystick_update()
    end
    jstick.name =  sfJoystick_getIdentification(jstick.devnum).name
    jstick.isconnected = true
    jstick.hasXaxis = sfJoystick_hasAxis(jstick.devnum, 0)
    jstick.nbuttons = sfJoystick_getButtonCount(jstick.devnum)
    while true
        sfJoystick_update()
        for i in 1:jstick.nbuttons
            jstick.pressed[i] =  sfJoystick_isButtonPressed(jstick.devnum, i - 1)
        end
        jstick.ypos = sfJoystick_getAxisPosition(jstick.devnum, 1)
        jstick.xpos = sfJoystick_getAxisPosition(joystick.devnum, 0)
        yield()
        sleep(sleepinterval)
    end
end

#------------ output code -------------------#

makelabel() = "Button 1: " * (jstick.pressed[1] ? "DOWN" : "UP") *
    "  Button 2: " * (jstick.pressed[2] ? "DOWN" : "UP")

const fontpointsize = 80
const wid = 500
const hei = 500
win = Window("Cursor Task", wid, hei) |> (Frame() |> (vbox = Box(:v)))
set_gtk_property!(vbox, :expand, true)
can = Canvas(wid, hei)
label = Label(makelabel())
push!(vbox, can, label)

joytoxpos() = div((jstick.xpos + 100) * width(can), 200)
joytoypos() = div((jstick.ypos + 100) * height(can), 200)
Gtk.showall(win)

@guarded draw(can) do widget
    ctx = getgc(can)
    select_font_face(ctx, "Courier", Cairo.FONT_SLANT_NORMAL, Cairo.FONT_WEIGHT_BOLD)
    set_font_size(ctx, fontpointsize)
    set_source(ctx, colorant"red")
    move_to(ctx, joytoxpos(), joytoypos())
    show_text(ctx, "+")
    set_gtk_property!(label, :label, makelabel())
end

@async polljoystick(jstick)

while true
    draw(can)
    sleep(0.2)
    yield()
end


    'disable text window
    nomainwin

    'set window size
    WindowWidth  = 308
    WindowHeight = 331

    'center window on screen
    UpperLeftX = int((DisplayWidth-WindowWidth)/2)
    UpperLeftY = int((DisplayHeight-WindowHeight)/2)

    'open graphics window
    open "Joystick Position" for graphics_nf_nsb as #m

    'trap window closing
    #m "trapclose [quit]"

    'put pen down
    #m "down"

    'get center of graphics window
    #m "home"
    #m "posxy CenterX CenterY"

    'draw sprite for crosshair
    #m "backcolor black; color black"
    #m "place 0 20;boxfilled 20 40"
    #m "line  0 10 20 10"
    #m "line 10  0 10 20"
    #m "place 10 10; circle 10"
    #m "backcolor white; color red"
    #m "line  0 30 20 30"
    #m "line 10 20 10 40"
    #m "place 10 30; circle 10"
    #m "flush"

    'get sprite image
    #m "getbmp plus 0 0 20 40"
    #m "cls"

    'create sprite from image
    #m "addsprite crosshair plus"
    #m "centersprite crosshair"
    #m "spritexy crosshair "; CenterX; " "; CenterY
    #m "drawsprites"

    'check joystick every 100 milliseconds
    timer 100, [CheckJoystick]
    wait

[CheckJoystick]
    readjoystick 1

    'calculate crosshair position
    PosX = int(CenterX*Joy1x/32767)
    PosY = int(CenterY*Joy1y/32767)

    'update crosshair position
    #m "spritexy crosshair "; PosX; " "; PosY
    #m "drawsprites"

    'display button information
    if Joy1button1 > 0 then #m "place 0 0;\\Button 1 pressed"
    if Joy1button2 > 0 then #m "place 0 0;\\\Button 2 pressed"

    wait

[quit]
    timer 0
    close #m
    unloadbmp "plus"
    end


10 MODE 1:BORDER 14:x=320:y=200:d=1
20 a=JOY(0)  ' read state of first joystick
30 IF d THEN q$="*" ELSE q$=" "
40 IF a THEN MOVE x-8,y+8:TAG:PRINT q$;:TAGOFF
50 IF (a AND 1) AND y<380 THEN y=y+10
60 IF (a AND 2) AND y>20  THEN y=y-10
70 IF (a AND 4) AND x>20  THEN x=x-10
80 IF (a AND 8) AND x<620 THEN x=x+10
90 IF a AND 16 THEN LOCATE 1,1:PRINT "Fire1 pressed":d=1
100 IF a AND 32 THEN LOCATE 1,2:PRINT "Fire2 pressed":d=0
110 IF a<16 THEN LOCATE 1,1:PRINT "             ":PRINT "             "
120 MOVE x-8,y+8:TAG:PRINT "X";:TAGOFF
130 GOTO 20


Slider2D[Dynamic[ControllerState[{"X", "Y"}]], ImageSize -> {500, 500}]


let remove x = List.filter (fun y -> y <> x)
let buttons_string b =
  String.concat " " (List.map string_of_int b)

let position app x y =
  let view = SFRenderWindow.getView app in
  let width, height = SFView.getSize view in
  let hw = width /. 2.0 in
  let hh = height /. 2.0 in
  (hw +. ((x /. 100.0) *. hw),
   hh +. ((y /. 100.0) *. hh))

let cross =
  [|  1.0,   1.0;  10.0,   1.0;  10.0, -1.0;    1.0, -1.0;
      1.0, -10.0;  -1.0, -10.0;  -1.0, -1.0;  -10.0, -1.0;
    -10.0,   1.0;  -1.0,   1.0;  -1.0, 10.0;    1.0, 10.0; |]

let () =
  let app = SFRenderWindow.make (800, 600) "Joystick Position" in
  let text = SFText.make "" in
  let shape = SFShape.create cross in
  SFShape.setFillColor shape SFColor.white;
  SFShape.setOutlineColor shape SFColor.white;
  SFShape.setOutlineThickness shape 1.0;
  let rec display ((x, y), b) =
    SFText.setString text (buttons_string b);
    let x, y = position app x y in
    SFShape.setPosition shape (x, y);
    SFRenderWindow.clear app SFColor.black;
    SFRenderWindow.drawText app text ();
    SFRenderWindow.drawShape app shape ();
    SFRenderWindow.display app;
  and loop joyd =
    let get_joystick (((x, y), b) as joyd) = function
    | SFEvent.JoystickButtonPressed (0, button) -> ((x, y), button::b)
    | SFEvent.JoystickButtonReleased (0, button) -> ((x, y), remove button b)
    | SFEvent.JoystickMoved (0, SFJoystick.X, av) -> ((av, y), b)
    | SFEvent.JoystickMoved (0, SFJoystick.Y, av) -> ((x, av), b)
    | _ -> joyd
    in
    let rec proc_event joyd =
      match SFRenderWindow.pollEvent app with
      | Some SFEvent.KeyPressed (SFKey.Escape,_,_,_,_)
      | Some SFEvent.Closed -> ()
      | Some event ->
          let joyd = get_joystick joyd event in
          proc_event joyd
      | None ->
          display joyd;
          loop joyd
    in
    proc_event joyd
  in
  loop ((0.0, 0.0), [])


without js
-- Joystick library for Euphoria (Windows)
-- /Mic, 2002
--
-- integer joy_init()
--  returns the number of joysticks attached to the computer
--
-- sequence joy_get_state(integer joy_num)
--  returns the current state of joystick #joy_num (can be either 1 or 2).
--  the format of the return sequence is:
--    {X_direction, Y_direction, Z_direction, buttons}
--  the X,Y and Z directions have 3 possible values; 0 (negative), 32768 (neutral) or 65535 (positive)
--  the buttons' status are represented by a single bit (button up, button down). e.g. to get the status
--  of button #3 on joystick #1 you'd use:
--    sequence state
--    state = joy_get_state(1)
--    if and_bits(state[4],4) then ... end if
--
include dll.e
include machine.e

constant joyinfo = allocate(32)
atom winmm
integer joyGetNumDevs,joyGetPos

winmm = open_dll("winmm.dll")
if (winmm <= 0) then
    puts(1,"Unable to open winmm.dll")
    abort(0)
end if

joyGetNumDevs   = define_c_func(winmm,"joyGetNumDevs",{},C_UINT)
joyGetPos   = define_c_func(winmm,"joyGetPos",{C_INT,C_POINTER},C_INT)
if (joyGetNumDevs<0) or (joyGetPos<0) then
    puts(1,"Unable to link functions")
    abort(0)
end if

global function joy_init()
    integer joy1Attached,joy2Attached
    integer numDevs = c_func(joyGetNumDevs,{})
    if numDevs=0 then
        return 0
    end if

    joy1Attached = (c_func(joyGetPos,{0,joyinfo}) != 167)
    joy2Attached = (numDevs=2) and (c_func(joyGetPos,{1,joyinfo}) != 167)

    return joy1Attached + (joy2Attached*2)
end function

global function joy_get_state(integer joy_num)
    if joy_num=1 or joy_num=2 then
        joy_num -= 1
        if c_func(joyGetPos,{joy_num,joyinfo+(joy_num*16)}) then
            -- ERROR
            return {}
        end if
        return peek4u({joyinfo+(joy_num*16),4})
    end if
    return {}
end function


(load "@lib/openGl.l")

(setq *JoyX 0.0  *JoyY 0.0)

(glutInit)
(glutInitDisplayMode (| GLUT_RGBA GLUT_DOUBLE GLUT_ALPHA GLUT_DEPTH))
(glutInitWindowSize 400 400)
(glutCreateWindow "Joystick")

(glClearColor 0.3 0.3 0.5 0)

(displayPrg
   (glClear GL_COLOR_BUFFER_BIT)
   (glBegin GL_LINES)
   (glVertex2f *JoyX (- *JoyY 0.1))  # Draw crosshair
   (glVertex2f *JoyX (+ *JoyY 0.1))
   (glVertex2f (- *JoyX 0.1) *JoyY)
   (glVertex2f (+ *JoyX 0.1) *JoyY)
   (glEnd)
   (glFlush)
   (glutSwapBuffers) )

# Track joystick position
(native `*GlutLib "glutJoystickFunc" NIL
   (lisp 'joystickFunc
      '((Btn X Y Z)
         (msg                          # Display buttons
            (make
               (for (B 1 (n0 Btn) (inc B))
                  (and (bit? 1 Btn) (link B))
                  (setq Btn (>> 1 Btn)) ) ) )
         (setq                         # Move crosshair
            *JoyX (*/ X 1.0 1000)
            *JoyY (*/ Y 1.0 1000) )
         (glutPostRedisplay) ) )
   100 )

# Exit upon mouse click
(mouseFunc '((Btn State X Y) (bye)))
(glutMainLoop)


If InitJoystick() = 0
  MessageRequester("Error!", "Need to connect a joystick", #PB_MessageRequester_Ok)
  End
EndIf

;some constants for Window positioning
#WindowW = 100: #WindowH = 100
#CrossW = 10
#p1 = (#WindowW - #CrossW) / 2
#p2 = (#WindowW / 2 - #CrossW)

If OpenWindow(0, 0, 0, #WindowW * 2 + 10, #WindowH, "Joystick Position", #PB_Window_SystemMenu)
  CreateImage(0, #WindowW, #WindowW)
  ImageGadget(0, 0, 0, 0, 0, ImageID(0))
  TextGadget(2, #WindowW + 5, 10, #WindowW, 20, "Buttons Pressed:")
  CreateImage(1, #WindowW, 40)
  ImageGadget(1,  #WindowW + 5, 30, 0, 0, ImageID(1))

  AddKeyboardShortcut(0, #PB_Shortcut_Escape, 0)
  Define event, x_movement, y_movement
  Repeat
    Repeat
      event = WindowEvent()
      Select event
        Case #PB_Event_Menu
          If EventMenu() = 0
            End
          EndIf
        Case #PB_Event_CloseWindow
          End
      EndSelect
    Until event = 0

    Define pressed.s, buttonNum, buttonX, buttonY, buttonText.s, buttonColor
    pressed.s = ""
    If ExamineJoystick(0)
      x_movement = JoystickAxisX(0)
      y_movement = JoystickAxisY(0)

      StartDrawing(ImageOutput(1))
        DrawingMode(#PB_2DDrawing_Transparent)
        Box(0, 0, #WindowW, 50, RGB($D4, $D0, $C8)) ;a Gray
        ; check to see if any of the buttons have been pressed
        For buttonNum = 1 To 10
          buttonX = ((buttonNum - 1) * 20 + 10) % #WindowW
          buttonY = ((buttonNum - 1) / 5) * 20 + 10
          If JoystickButton(0, buttonNum)
            buttonColor = RGB($FF, 0, 0) ;Red
          Else
            buttonColor = RGB($80, $80, $80) ;Gray
          EndIf
          Circle(buttonX, buttonY, 9, buttonColor)
          buttonText = Str(buttonNum)
          DrawText(buttonX - TextWidth(buttonText) / 2, buttonY - TextHeight(buttonText) / 2, buttonText, RGB($FF, $FF, $FF)) ;White
        Next
      StopDrawing()

      SetGadgetState(1, ImageID(1))
    EndIf

    StartDrawing(ImageOutput(0))
      Box(0,0, #WindowW, #WindowW, RGB($FF, $FF, $FF)) ;White
      Line(#p1 + x_movement * #p2, #WindowW / 2 + y_movement * #p2, #CrossW, 1, RGB($FF, 0, 0)) ;Red
      Line(#WindowW / 2 + x_movement * #p2, #p1 + y_movement * #p2, 1, #CrossW, RGB($FF, 0, 0)) ;Red
    StopDrawing()

    SetGadgetState(0, ImageID(0))

    Delay(10)
  Until event = #PB_Event_CloseWindow
EndIf


import sys
import pygame

pygame.init()

# Create a clock (for framerating)
clk = pygame.time.Clock()

# Grab joystick 0
if pygame.joystick.get_count() == 0:
    raise IOError("No joystick detected")
joy = pygame.joystick.Joystick(0)
joy.init()

# Create display
size = width, height = 600, 600
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Joystick Tester")

# Frame XHair zone
frameRect = pygame.Rect((45, 45), (510, 510))

# Generate crosshair
crosshair = pygame.surface.Surface((10, 10))
crosshair.fill(pygame.Color("magenta"))
pygame.draw.circle(crosshair, pygame.Color("blue"), (5,5), 5, 0)
crosshair.set_colorkey(pygame.Color("magenta"), pygame.RLEACCEL)
crosshair = crosshair.convert()

# Generate button surfaces
writer = pygame.font.Font(pygame.font.get_default_font(), 15)
buttons = {}
for b in range(joy.get_numbuttons()):
    buttons[b] = [
        writer.render(
            hex(b)[2:].upper(),
            1,
            pygame.Color("red"),
            pygame.Color("black")
        ).convert(),
        # Get co-ords: ((width*slot)+offset, offset). Offsets chosen
        #                                             to match frames.
        ((15*b)+45, 560)
    ]

while True:
    # Pump and check the events queue
    pygame.event.pump()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Black the screen
    screen.fill(pygame.Color("black"))

    # Get joystick axes
    x = joy.get_axis(0)
    y = joy.get_axis(1)

    # Blit to the needed coords:
    # x*amplitude+(centre offset (window size/2))-(xhair offset (xh size/2))
    screen.blit(crosshair, ((x*250)+300-5, (y*250)+300-5))
    pygame.draw.rect(screen, pygame.Color("red"), frameRect, 1)

    # Get and display the joystick buttons
    for b in range(joy.get_numbuttons()):
        if joy.get_button(b):
            screen.blit(buttons[b][0], buttons[b][1])

    # Write the display
    pygame.display.flip()
    clk.tick(40) # Limit to <=40 FPS


use experimental :pack;

# Joysticks generally show up in the /dev/input/ directory as js(n) where n is
# the number assigned by the OS. E.G. /dev/input/js1 . In my particular case:

my $device = '/dev/input/js0';

my $exit = 0;

my $event-stream = $device.IO.open(:bin);
my $js = $event-stream.Supply(:8size);

my %config; # joystick configuration: number of axes and buttons
my %event;  # global "joystick event"

%config<button>.push: 0;

my $callback = sub { update };

sub get-js-event ( $ev, &callback ) {
    exit if $exit;
    # 32 bit timestamp milliseconds. Allows easy checking for "double-click" button presses
    %event<timestamp> = $ev.subbuf(0, 4).reverse.unpack('N');

    # 16 bit (signed int16) value of current control
    %event<value> = (my $v = $ev.subbuf(4, 2).unpack('S')) > 32767 ?? -65536 + $v !! $v;

    # Two 8 bit integers, current event: control type, and control ID
    (%event<type>, %event<number>) = $ev.subbuf(6).unpack('CC');

    # Process the event
    if %event<type> +& 128 {       # initialing
        given %event<type> +& 3  { # enumeration of control inputs
            when 1 { %config<button>.push: %event<number> }
            when 2 { %config<axis>.push: %event<number> }
        }
    } else {
        # Optional callback subroutine to run every time a js event is received
        callback
    }
}

# read events from the joystick driver asynchronously
start react whenever $js { $js.act: { get-js-event($_, $callback) } }

# allow a short delay while driver initializes
sleep .5;

# clean up on exit
signal(SIGINT).tap: {
    print "\e[0m", "\n" xx 50, "\e[H\e[J\e[?25hWaiting for one more joystick event...\n";
    $exit = 1;
    exit(0);
}

use Terminal::ANSIColor;

my ($rows, $cols) = qx/stty size/.words; # get the terminal size

my $xhair = '╺╋╸';
my $axis  = '█';
my @btext = %config<button>.map: { sprintf( "%2d", $_) };
my @button = @btext.map: {color('bold white on_blue ') ~ $_ ~ color('reset')};
my ($x, $y, $z) = ($rows/2).floor, ($cols/2).floor, 0;

sub update {
    given %event<type> {
        when 1 { # button event
            given %event<value> {
                when 0 { @button[%event<number>] = color('bold white on_blue ') ~ @btext[%event<number>] ~ color('reset') }
                when 1 { @button[%event<number>] = color('bold white on_green') ~ @btext[%event<number>] ~ color('reset') }
            }
        }
        when 2 { # axis events
            given %event<number> {
                when 0 { $y = ($cols / 2 + %event<value> / 32767 * $cols / 2).Int max 1 }
                when 1 { $x = ($rows / 2 + %event<value> / 32767 * $rows / 2).Int max 2 }
                when 2 { $z = (%event<value> / 32767 * 100).Int }
                default { } # only using the first 3 axes, ignore ant others
            }
            $x min= $rows - 1;
            $y min= $cols - 1;
        }
    }
    print "\e[H\e[J\e[1;1H";
    print "  ", join "  ", flat @button, "Axis 0: $x", "Axis 1: $y" , "Axis 2: $z%\n";
    my $bar = ($z / 100 * $cols / 2).floor;
    if $bar < 0 {
        print ' ' x ($bar + $cols / 2).floor, color('bold green') ~ $axis x -$bar ~ color('reset');
    } else {
        print ' ' x $cols / 2, color('bold green') ~ $axis x $bar ~ color('reset');
    }
    print "\e[{$x};{$y}H", color('bold yellow') ~ $xhair ~ color('reset');
}

print "\e[?25l"; # hide the cursor
update; # initial update

# Main loop, operates independently of the joystick event loop
loop {
    once say " Joystick has {%config<axis>.elems} axes and {%config<button>.elems} buttons";
    sleep 1;
    ($rows, $cols) = qx/stty size/.words;
}


package require Tk 8.6
package require mkLibsdl

# This code assumes we're dealing with the first pair of axes on the first
# joystick; modern joysticks are complex...

# Callback for all joystick activity
proc display {joyDict} {
    global x y buttons message
    set axis -1
    dict with joyDict {
	if {$joystick != 0} return
	if {[info exist button]} {
	    # Handle button presses...
	    set buttons($button) $value
	    set message "Buttons:"
	    foreach b [lsort -integer [array names buttons]] {
		if {$buttons($b)} {
		    lappend message $b
		}
	    }
	} else {
	    # Handle joystick movement...
	    if {$axis == -1} return
	    set value [expr {$value / 32768.0 * 100 + 120}]
	    if {$axis == 0} {
		set x $value
	    } elseif {$axis == 1} {
		set y $value
	    }
	    .c coords xhairV $x [expr {$y-5}] $x [expr {$y+5}]
	    .c coords xhairH [expr {$x-5}] $y [expr {$x+5}] $y
	}
    }
}

# Make a GUI
set message "Buttons:"
pack [canvas .c -width 240 -height 240] [label .l -textvariable message]
set x [set y 120]
.c create line {120 115 120 125} -tags xhairV
.c create line {115 120 125 120} -tags xhairH
joystick event eval {display [joystick event peek]}


import "input" for Keyboard, GamePad
import "graphics" for Canvas, Color
import "dome" for Window

var Buttons = [
    "left", "right", "up", "down", "A", "B", "X", "Y",
    "back", "start", "guide", "leftshoulder", "rightshoulder"
]

var Symbols = ["L", "R", "U", "D", "A", "B", "X", "Y", "BK", "S", "G", "LS", "RS"]

class Main {
    construct new(width, height) {
        Window.resize(width, height)
        Canvas.resize(width, height)
        Window.title = "Joystick position"
        _w = width
        _h = height
        _dx = (width/100).floor
        _dy = (height/100).floor
        _gpd = GamePad.next
    }

    init() {
        // start in center
        _x = _w / 2
        _y = _h / 2
        Canvas.cls(Color.yellow)
        showButtonStatus()
        Canvas.print("+", _x, _y, Color.red)
    }

    update() {
        var dx = 0
        var dy = 0
        if (Keyboard.isKeyDown("left")         || _gpd.getAnalogStick("left").x < -0.25) {
            dx = -_dx
        } else if (Keyboard.isKeyDown("right") || _gpd.getAnalogStick("left").x > 0.25)  {
            dx = _dx
        } else if (Keyboard.isKeyDown("up")    || _gpd.getAnalogStick("left").y < -0.25) {
            dy =  -_dy
        } else if (Keyboard.isKeyDown("down")  || _gpd.getAnalogStick("left").y > 0.25)  {
            dy = _dy
        }
        moveCrossHair(dx, dy)
    }

    moveCrossHair(dx, dy) {
        _x = _x + dx
        _y = _y + dy
        if (_x < 0) _x = 0
        if (_x > _w - 5) _x = _w - 5
        if (_y < 0) _y = 0
        if (_y > _h * 0.96 - 5) _y = _h * 0.96 - 5
    }

    // show whether other gamepad keys are pressed by printing the corresponding symbol if they are.
    showButtonStatus() {
        Canvas.rectfill(0, _h * 0.96, _w, _h, Color.blue)
        var s = ""
        for (i in 0...Buttons.count) {
            var button = Buttons[i]
            if (_gpd.isButtonPressed(button)) s = s + "  " + Symbols[i]
        }
        Canvas.print(s, 0, _h * 0.98, Color.white)
    }

    draw(alpha) {
        Canvas.cls(Color.yellow)
        showButtonStatus()
        Canvas.print("+", _x, _y, Color.red)
    }
}

var Game = Main.new(600, 600)


10 DIM o$(5)
20 LET xm=0: LET xx=31: REM screen limits
30 LET ym=0: LET yx=18
40 LET xo=16: LET yo=9: REM origin
50 LET xc=xo: LET yc=yo
60 PRINT AT yc,xc;" ": REM entry point for scan loop - blank cursor
70 LET xc=xo: LET yc=yo
80 LET t=IN 31
90 IF t=1 OR t=5 OR t=9 OR t=17 OR t=21 OR t=25 THEN LET xc=xx: LET o$(2)="R": REM right
100 IF t=2 OR t=6 OR t=10 OR t=18 OR t=22 OR t=26 THEN LET xc=xm: LET o$(1)="L": REM left
110 IF t=4 OR t=5 OR t=6 OR t=20 OR t=21 OR t=22 THEN LET yc=yx: LET o$(4)="D": REM down
120 IF t=8 OR t=9 OR t=10 OR t=24 OR t=25 OR t=26 THEN LET yc=ym: LET o$(3)="U": REM up
130 IF t>=16 THEN LET o$(5)="F": REM fire
140 PRINT AT 21,0;"Input:";o$
150 PRINT AT yc,xc;"+"
160 LET o$="     ": REM five spaces to blank output line again
170 GO TO 60


F jortsort(sequence)
   R Array(sequence) == sorted(sequence)

F print_for_seq(seq)
   print(‘jortsort(#.) is #.’.format(seq, jortsort(seq)))

print_for_seq([1, 2, 4, 3])
print_for_seq([14, 6, 8])
print_for_seq([‘a’, ‘c’])
print_for_seq(‘CVGH’)
print_for_seq(‘PQRST’)


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

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

/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessOk:         .asciz "Ok, the list is sorted. \n"
szMessNotOk:      .asciz "Ouah!! this list is unsorted.\n"
szCarriageReturn:  .asciz "\n"
tbNumber:           .quad 3
                    .quad 4
                    .quad 20
                    .quad 5
                    .equ LGTBNUMBER, (. - tbNumber)/8  // number element of area
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sZoneConversion:        .skip 100
.align 4
tbNumberSorted:      .skip 8 * LGTBNUMBER
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                             // entry of program
    ldr x0,qAdrtbNumber
    ldr x1,qAdrtbNumberSorted
    mov x2,LGTBNUMBER
    bl insertionSort              // sort area
    ldr x0,qAdrtbNumber
    ldr x1,qAdrtbNumberSorted
    mov x2,LGTBNUMBER
    bl comparArea                // control area
    cbz x0,1f
    ldr x0,qAdrszMessNotOk       // not sorted
    bl affichageMess
    b 100f
1:                               // ok it is good
    ldr x0,qAdrszMessOk
    bl affichageMess
100:                             // standard end of the program
    mov x0, #0                   // return code
    mov x8, #EXIT                // request to exit program
    svc 0                        // perform the system call

qAdrtbNumber:          .quad tbNumber
qAdrtbNumberSorted:    .quad tbNumberSorted
qAdrszMessNotOk:       .quad szMessNotOk
qAdrszMessOk:          .quad szMessOk
qAdrszCarriageReturn:  .quad szCarriageReturn
/******************************************************************/
/*     insertion sort                                             */
/******************************************************************/
/* x0 contains the address of area to sort  */
/* x1 contains the address of area sorted   */
/* x2 contains the number of element */
insertionSort:
    stp x1,lr,[sp,-16]!         // save  registers
    stp x2,x3,[sp,-16]!         // save  registers
    mov x3,0
1:                              // copy area unsorted to other area
    ldr x4,[x0,x3,lsl 3]
    str x4,[x1,x3,lsl 3]
    add x3,x3,1
    cmp x3,x2
    blt 1b

    mov x3,1                   // and sort area
2:
    ldr x4,[x1,x3,lsl 3]
    subs x5,x3,1
3:
    cbz x5,4f
    ldr x6,[x1,x5,lsl 3]
    cmp x6,x4
    ble 4f
    add x7,x5,1
    str x6,[x1,x7,lsl 3]
    subs x5,x5,1
    b 3b
4:
    add x5,x5,1
    str x4,[x1,x5,lsl 3]
    add x3,x3,1
    cmp x3,x2
    blt 2b
100:
    ldp x2,x3,[sp],16           // restaur  2 registers
    ldp x1,lr,[sp],16           // restaur  2 registers
    ret
/******************************************************************/
/*     Comparaison elements of two areas                          */
/******************************************************************/
/* x0 contains the address of area to sort  */
/* x1 contains the address of area sorted   */
/* x2 contains the number of element */
comparArea:
    stp x1,lr,[sp,-16]!         // save  registers
    stp x2,x3,[sp,-16]!         // save  registers
    mov x3,0
1:
    ldr x4,[x0,x3,lsl 3]        // load element area 1
    ldr x5,[x1,x3,lsl 3]        // load element area 2
    cmp x4,x5                   // equal ?
    bne 99f                     // no -> error
    add x3,x3,1                 // yes increment indice
    cmp x3,x2                   // maxi ?
    blt 1b                      // no -> loop
    mov x0,0                    // yes -> it is ok
    b 100f
99:
    mov x0,1
100:
    ldp x2,x3,[sp],16           // restaur  2 registers
    ldp x1,lr,[sp],16           // restaur  2 registers
    ret

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC PrintArray(INT ARRAY a INT size)
  INT i

  Put('[)
  FOR i=0 TO size-1
  DO
    IF i>0 THEN Put(' ) FI
    PrintI(a(i))
  OD
  Put('])
RETURN

PROC InsertionSort(INT ARRAY a INT size)
  INT i,j,value

  FOR i=1 TO size-1
  DO
    value=a(i)
    j=i-1
    WHILE j>=0 AND a(j)>value
    DO
      a(j+1)=a(j)
      j==-1
    OD
    a(j+1)=value
  OD
RETURN

BYTE FUNC IsSorted(INT ARRAY a INT n)
  INT ARRAY b(20)
  INT i

  IF n=0 THEN
    RETURN (1)
  FI

  MoveBlock(b,a,n*2)
  InsertionSort(b,n)
  FOR i=0 TO n-1
  DO
    IF b(i)#a(i) THEN
      RETURN (0)
    FI
  OD
RETURN (1)

PROC Test(INT ARRAY a INT n)
  BYTE sorted

  sorted=IsSorted(a,n)
  PrintArray(a,n)
  IF sorted THEN
    PrintE(" is sorted")
  ELSE
    PrintE(" is not sorted")
  FI
RETURN

PROC Main()
  INT ARRAY
    a=[65530 0 1 2 10 13 16],
    b=[2 3 6 4],
    c=[3 3 3 3 3 3],
    d=[7]

  Test(a,7)
  Test(b,4)
  Test(c,6)
  Test(d,1)
  Test(d,0)
RETURN


with Ada.Text_IO, Ada.Containers.Generic_Array_Sort;

procedure Jortsort is

   function Jort_Sort(List: String) return Boolean is
      procedure Sort is new Ada.Containers.Generic_Array_Sort
	(Positive, Character, Array_Type => String);
      Second_List: String := List;
   begin
      Sort(Second_List);
      return Second_List = List;
   end Jort_Sort;

   use Ada.Text_IO;
begin
   Put_Line("""abbigail"" sorted: " & Boolean'Image(Jort_Sort("abbigail")));
   Put_Line("""abbey"" sorted: " & Boolean'Image(Jort_Sort("abbey")));
end Jortsort;


use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

------------------------- JORTSORT -------------------------

-- jortSort :: Ord a => [a] -> Bool
on jortSort(xs)
    xs = sort(xs)
end jortSort

--------------------------- TEST ---------------------------
on run
    map(jortSort, {{4, 5, 1, 3, 2}, {1, 2, 3, 4, 5}})

    --> {false, true}
end run

------------------------- GENERIC --------------------------

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

-- mReturn :: First-class m => (a -> b) -> m (a -> b)
on mReturn(f)
    -- 2nd class handler function lifted into 1st class script wrapper.
    if script is class of f then
        f
    else
        script
            property |λ| : f
        end script
    end if
end mReturn

-- sort :: Ord a => [a] -> [a]
on sort(xs)
    ((current application's NSArray's arrayWithArray:xs)'s ¬
        sortedArrayUsingSelector:"compare:") as list
end sort


jortSort?: function [a]->
    a = sort a

test: function [a]->
    print [a "is" (jortSort? a)? -> "sorted" -> "not sorted"]

test [1 2 3]
test [2 3 1]

print ""

test ["a" "b" "c"]
test ["c" "a" "b"]


JortSort(Array){
	sorted:=[]
	for index, val in Array
		sorted[val]:=1
	for key, val in sorted
		if (key<>Array[A_Index])
			return 0
	return 1
}


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

int number_of_digits(int x){
    int NumberOfDigits;
    for(NumberOfDigits=0;x!=0;NumberOfDigits++){
        x=x/10;
    }
    return NumberOfDigits;
}

int* convert_array(char array[], int NumberOfElements)  //converts integer arguments from char to int
{
    int *convertedArray=malloc(NumberOfElements*sizeof(int));
    int originalElement, convertedElement;

    for(convertedElement=0, originalElement=0; convertedElement<NumberOfElements; convertedElement++)
    {
       convertedArray[convertedElement]=atoi(&array[originalElement]);
       originalElement+=number_of_digits(convertedArray[convertedElement])+1; //computes where is the beginning of the next element

    }
    return convertedArray;
}

int isSorted(int array[], int numberOfElements){
    int sorted=1;
    for(int counter=0;counter<numberOfElements;counter++){
        if(counter!=0 && array[counter-1]>array[counter]) sorted--;

    }
    return sorted;
}
int main(int argc, char* argv[])
{
    int* convertedArray;

    convertedArray=convert_array(*(argv+1), argc-1);

    if(isSorted(convertedArray, argc-1)==1) printf("Did you forgot to turn on your brain?! This array is already sorted!\n");
    else if(argc-1<=10) printf("Am I really supposed to sort this? Sort it by yourself!\n");
    else printf("Am I really supposed to sort this? Bhahahaha!\n");
    free(convertedArray);
    return 0;

}


using System;

class Program
{
  public static bool JortSort<T>(T[] array) where T : IComparable, IEquatable<T>
  {
    // sort the array
    T[] originalArray = (T[]) array.Clone();
    Array.Sort(array);

    // compare to see if it was originally sorted
    for (var i = 0; i < originalArray.Length; i++)
    {
      if (!Equals(originalArray[i], array[i]))
      {
        return false;
      }
    }

    return true;
  }
}


#include <algorithm>
#include <string>
#include <iostream>
#include <iterator>

class jortSort {
public:
    template<class T>
    bool jort_sort( T* o, size_t s ) {
        T* n = copy_array( o, s );
        sort_array( n, s );
        bool r = false;

        if( n ) {
            r = check( o, n, s );
            delete [] n;
        }
        return r;
    }

private:
    template<class T>
    T* copy_array( T* o, size_t s ) {
        T* z = new T[s];
        memcpy( z, o, s * sizeof( T ) );
        //std::copy( o, o + s, z );
        return z;
    }
    template<class T>
    void sort_array( T* n, size_t s ) {
        std::sort( n, n + s );
    }
    template<class T>
    bool check( T* n, T* o, size_t s ) {
        for( size_t x = 0; x < s; x++ )
            if( n[x] != o[x] ) return false;
        return true;
    }
};

jortSort js;

template<class T>
void displayTest( T* o, size_t s ) {
    std::copy( o, o + s, std::ostream_iterator<T>( std::cout, " " ) );
    std::cout << ": -> The array is " << ( js.jort_sort( o, s ) ? "sorted!" : "not sorted!" ) << "\n\n";
}

int main( int argc, char* argv[] ) {
    const size_t s = 5;
    std::string oStr[] = { "5", "A", "D", "R", "S" };
    displayTest( oStr, s );
    std::swap( oStr[0], oStr[1] );
    displayTest( oStr, s );

    int oInt[] = { 1, 2, 3, 4, 5 };
    displayTest( oInt, s );
    std::swap( oInt[0], oInt[1] );
    displayTest( oInt, s );

    return 0;
}


(defun jort-sort (x)
  (equalp x (sort (copy-seq x) #'<)))


def jort_sort(array)
  array == array.sort
end


module jortsort;

import std.algorithm : sort, SwapStrategy;

bool jortSort(T)(T[] array) {
	auto originalArray = array.dup;
	sort!("a < b", SwapStrategy.stable)(array);
	return originalArray == array;
}

unittest {
	assert(jortSort([1, 2, 3]));
	assert(!jortSort([1, 6, 3]));
	assert(jortSort(["apple", "banana", "orange"]));
	assert(!jortSort(["two", "one", "three"]));
}


program JortSort;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils,
  System.Generics.Collections,
  System.Generics.Defaults;

type
  TArrayHelper = class helper for TArray
  public
    class function JortSort<T>(const original: TArray<T>): Boolean; static;
  end;

{ TArrayHelper }

class function TArrayHelper.JortSort<T>(const original: TArray<T>): Boolean;
var
  sorted: TArray<T>;
  i: Integer;
begin
  SetLength(sorted, Length(original));
  copy<T>(original, sorted, Length(original));
  Sort<T>(sorted);

  for i := 0 to High(original) do
    if TComparer<T>.Default.Compare(sorted[i], original[i]) <> 0 then
      exit(False);
  Result := True;
end;

var
  test: TArray<Integer>;
begin
  // true
  test := [1, 2, 3, 4, 5];
  Writeln(TArray.JortSort<Integer>(test));

  // false
  test := [5, 4, 3, 2, 1];
  Writeln(TArray.JortSort<Integer>(test));

  Readln;
end.


iex(1)> jortsort = fn list -> list == Enum.sort(list) end
#Function<6.90072148/1 in :erl_eval.expr/5>
iex(2)> jortsort.([1,2,3,4])
true
iex(3)> jortsort.([1,2,5,4])
false


let jortSort n=n=Array.sort n
printfn "%A %A" (jortSort [|1;23;42|]) (jortSort [|23;42;1|])


USING: kernel sorting ;
: jortsort ( seq -- ? ) dup natural-sort = ;


' FB 1.05.0 Win64

' Although it's possible to create generic sorting routines using macros in FreeBASIC
' here we will just use Integer arrays.

Sub quicksort(a() As Integer, first As Integer, last As Integer)
  Dim As Integer length = last - first + 1
  If length < 2 Then Return
  Dim pivot As Integer = a(first + length\ 2)
  Dim lft As Integer = first
  Dim rgt As Integer = last
  While lft <= rgt
    While a(lft) < pivot
      lft +=1
    Wend
    While a(rgt) > pivot
      rgt -= 1
    Wend
    If lft <= rgt Then
       Swap a(lft), a(rgt)
       lft += 1
       rgt -= 1
    End If
  Wend
  quicksort(a(), first, rgt)
  quicksort(a(), lft, last)
End Sub

Function jortSort(a() As Integer) As Boolean
  ' copy the array
  Dim lb As Integer = LBound(a)
  Dim ub As Integer = UBound(a)
  Dim b(lb To ub) As Integer
  ' this could be done more quickly using memcpy
  ' but we just copy element by element here
  For i As Integer = lb To ub
    b(i) = a(i)
  Next
  ' sort "b"
  quickSort(b(), lb, ub)
  ' now compare with "a" to see if it's already sorted
  For i As Integer = lb To ub
    If a(i) <> b(i) Then Return False
  Next
  Return True
End Function

Sub printResults(a() As Integer)
  For i As Integer = LBound(a) To UBound(a)
    Print a(i); " ";
  Next
  Print " => "; IIf(jortSort(a()), "sorted", "not sorted")
End Sub

Dim a(4) As Integer = {1, 2, 3, 4, 5}
printResults(a())
Print
Dim b(4) As Integer = {2, 1, 3, 4, 5}
PrintResults(b())
Print
Print "Press any key to quit"
Sleep


package main

import (
  "log"
  "sort"
)

func main() {
  log.Println(jortSort([]int{1, 2, 1, 11, 213, 2, 4})) //false
  log.Println(jortSort([]int{0, 1, 0, 0, 0, 0}))       //false
  log.Println(jortSort([]int{1, 2, 4, 11, 22, 22}))    //true
  log.Println(jortSort([]int{0, 0, 0, 1, 2, 2}))       //true
}

func jortSort(a []int) bool {
  c := make([]int, len(a))
  copy(c, a)
  sort.Ints(a)
  for k, v := range c {
    if v == a[k] {
      continue
    } else {
      return false
    }
  }
  return true
}


import Data.List (sort)

jortSort :: (Ord a) => [a] -> Bool
jortSort list = list == sort list


(defn jortsort [xs]
  (deep= xs (sorted xs)))

(print (jortsort @[1 2 3 4 5])) # true
(print (jortsort @[2 1 3 4 5])) # false


public class JortSort {
    public static void main(String[] args) {
        System.out.println(jortSort(new int[]{1, 2, 3}));
    }

    static boolean jortSort(int[] arr) {
        return true;
    }
}


var jortSort = function( array ) {

  // sort the array
  var originalArray = array.slice(0);
  array.sort( function(a,b){return a - b} );

  // compare to see if it was originally sorted
  for (var i = 0; i < originalArray.length; ++i) {
    if (originalArray[i] !== array[i]) return false;
  }

  return true;
};


/* jortSort in Jsish, based on the original satire, modified for jsish */
var jortSort = function(arr:array):boolean {
    // make a copy
    var originalArray = arr.slice(0);
    // sort
    arr.sort( function(a,b) { return a - b; } );
    // compare to see if it was originally sorted
    for (var i = 0; i < originalArray.length; ++i) {
        if (originalArray[i] !== arr[i]) return false;
    }
    // yes, the data came in sorted
    return true;
};

if (Interp.conf('unitTest')) {
;    jortSort([1,2,3]);
;    jortSort([3,2,1]);
;    jortSort([1, 'snort', 'sort', [1,2], {1:2}]);
;    jortSort(['snort', 'sort', 1, [1,2], {1:2}]);
}

/*
=!EXPECTSTART!=
jortSort([1,2,3]) ==> true
jortSort([3,2,1]) ==> false
jortSort([1, 'snort', 'sort', [1,2], {1:2}]) ==> true
jortSort(['snort', 'sort', 1, [1,2], {1:2}]) ==> false
=!EXPECTEND!=
*/


// version 1.0.6

fun <T> jortSort(a: Array<T>): Boolean {
    val b = a.copyOf()
    b.sort()
    for (i in 0 until a.size)
        if (a[i] != b[i]) return false
    return true
}

fun <T> printResults(a: Array<T>) {
    println(a.joinToString(" ") + " => " + if (jortSort(a)) "sorted" else "not sorted")
}

fun main(args: Array<String>) {
    val a = arrayOf(1, 2, 3, 4, 5)
    printResults(a)
    val b = arrayOf(2, 1, 3, 4, 5)
    printResults(b)
    println()
    val c = arrayOf('A', 'B', 'C', 'D', 'E')
    printResults(c)
    val d = arrayOf('C', 'D', 'A', 'E', 'B')
    printResults(d)
}


function copy (t)
    local new = {}
    for k, v in pairs(t) do new[k] = v end
    return new
end

function jortSort (array)
    local originalArray = copy(array)
    table.sort(array)
    for i = 1, #originalArray do
        if originalArray[i] ~= array[i] then return false end
    end
    return true
end


jortSort := proc(arr)
	local copy:
	copy := sort(Array([seq(arr[i], i=1..numelems(arr))])):
	return ArrayTools:-IsEqual(copy,arr):
end proc:
#Examples
jortSort(Array([5,6,7,2,1]));
jortSort(Array([-5,0,7,12,21]));
jortSort(Array(StringTools:-Explode("abcdefg")));


jortSort[list_] := list == Sort[list];
Print[jortSort[Range[100]]];
Print[jortSort[RandomSample[Range[100]]]];


import algorithm

func jortSort[T](a: openArray[T]): bool =
  a == a.sorted()

proc test[T](a: openArray[T]) =
  echo a, " is ", if a.jortSort(): "" else: "not ", "sorted"

test([1, 2, 3])
test([2, 3, 1])
echo ""
test(['a', 'b', 'c'])
test(['c', 'a', 'b'])


function : JortSort(elems : CompareVector) ~ Bool {
  sorted := CompareVector->New(elems);
  sorted->Sort();

  each(i : sorted) {
    if(sorted->Get(i)->Compare(elems->Get(i)) <> 0) {
      return false;
    };
  };

  return true;
}


let jortSortList lst =
  lst = List.sort compare lst


sub jortsort {
  my @s=sort @_;  # Default standard string comparison
  for (0..$#s) {
    return 0 unless $_[$_] eq $s[$_];
  }
  1;
}


type JortSort(sequence s)
    return s=sort(s)
end type


go =>
  List = [
           [1,2,3,4,5],
           [2,3,4,5,1],
           [2],
           "jortsort",
           "jortsort".sort()
         ],
  foreach(L in List)
     printf("%w: ", L),
     if not jortsort(L) then
       print("not ")
     end,
     println("sorted")
  end,
  nl.

jortsort(X) => X == X.sort().


(de jortSort (L) (= L (sort L)))
(jortSort (1 2 3))


function jortsort($a) { -not (Compare-Object $a ($a | sort) -SyncWindow 0)}
jortsort @(1,2,3)
jortsort @(2,3,1)


Macro isSort(liste)
  If OpenConsole()
    Print("[ ") : ForEach liste : Print(liste+Space(1)) : Next : Print("] = ")
    If jortSort(liste) : PrintN("True") : Else : PrintN("False") : EndIf
  EndIf
EndMacro

Procedure.b jortSort(List jortS.s())
  NewList cpy.s() : CopyList(jortS(),cpy()) : SortList(cpy(),#PB_Sort_Ascending)
  ForEach jortS()
    SelectElement(cpy(),ListIndex(jortS()))
    If Not jortS()=cpy() : ProcedureReturn #False : EndIf
  Next
  ProcedureReturn #True
EndProcedure

NewList l1.s()
For i=1 To 10 : AddElement(l1()) : l1()=Chr(Random(90,65)) : Next
isSort(l1()) : SortList(l1(),#PB_Sort_Ascending) : isSort(l1())
Input()


>>> def jortsort(sequence):
	return list(sequence) == sorted(sequence)
>>> for data in [(1,2,4,3), (14,6,8), ['a', 'c'], ['s', 'u', 'x'], 'CVGH', 'PQRST']:
	print(f'jortsort({repr(data)}) is {jortsort(data)}')
jortsort((1, 2, 4, 3)) is False
jortsort((14, 6, 8)) is False
jortsort(['a', 'c']) is True
jortsort(['s', 'u', 'x']) is True
jortsort('CVGH') is False
jortsort('PQRST') is True
>>>


  [ dup
    ' [ sortwith ]
    ]'[ nested join
    do = ]                          is jortsortwith ( [ --> b )


#lang racket/base
(define (jort-sort l [<? <])
  (equal? l (sort l <?)))


/*REXX program  verifies  that  an array  is sorted  using  a   jortSort   algorithm.   */
parse arg $                                      /*obtain the list of numbers from C.L. */
if $=''  then $=1 2 4 3                          /*Not specified?  Then use the default.*/
say 'array items='  space($)                     /*display the list to the terminal.    */
if jortSort($)  then say  'The array is sorted.'
                else say  "The array isn't sorted."
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
eSort:    procedure expose @.;                    [email protected].0       /*exchange sort.*/
                    do while h>1;                 h=h%2
                      do i=1  for @.0-h;          j=i;      k=h+i
                        do  while @.k<@.j;        [email protected].j;    @.[email protected].k;    @.k=t
                        if h>=j  then leave;      j=j-h;    k=k-h
                        end   /*while @.k<@.j*/
                      end     /*i*/
                    end       /*while h>1*/
          return
/*──────────────────────────────────────────────────────────────────────────────────────*/
jortSort: parse arg x;   @.0=words(x)                         /*assign # items in list. */
                      do j=1  for @.0; !.j=word(x,j); @.j=!.j /*save a copy of original.*/
                      end   /*j*/
          call eSort                                          /*sort with exchange sort.*/
                      do k=1  for @.0
                      if !.k\[email protected].k  then return 0             /*the array isn't sorted. */
                      end   /*k*/
          return 1                                            /*the array is    sorted. */


aList = [4,2,3,1]
see jortSort(aList) + nl

func jortSort array
     originalArray = array
     array = sort(array)
     for i= 1 to len(originalArray)
         if originalArray[i] != array[i] return false ok
     next
     return true


def jort_sort(array)
  array == array.sort
end


use std::cmp::{Ord, Eq};

fn jort_sort<T: Ord + Eq + Clone>(array: Vec<T>) -> bool {
    // sort the array
    let mut sorted_array = array.to_vec();
    sorted_array.sort();

    // compare to see if it was originally sorted
    for i in 0..array.len() {
        if array[i] != sorted_array[i] {
            return false;
        }
    }

    return true;
}


import java.util.Objects.deepEquals

def jortSort[K:Ordering]( a:Array[K] ) = deepEquals(a.sorted, a)


func jort_sort(array) { array == array.sort };


func jortSort<T:Comparable>(array: [T]) -> Bool {
    return array == sorted(array)
}


proc jortsort {args} {
    set list [lindex $args end]
    set list [list {*}$list]    ;# ensure canonical list form
    set options [lrange $args 0 end-1]
    expr {[lsort {*}$options $list] eq $list}
}


JortSort() {
   cmp -s <(printf “%s\n” “[email protected]“) <(printf “%s\n” “[email protected]“ | sort)
}

JortSortVerbose() {
  if JortSort “[email protected]“; then
    echo True
  else
    echo False
  If
}

JortSortVerbose 1 2 3 4 5
JortSortVerbose 1 3 4 5 2
JortSortVerbose a b c
JortSortVerbose c a b


Function JortSort(s)
	JortSort = True
	arrPreSort = Split(s,",")
	Set arrSorted = CreateObject("System.Collections.ArrayList")
	'Populate the resorted arraylist.
	For i = 0 To UBound(arrPreSort)
		arrSorted.Add(arrPreSort(i))
	Next
	arrSorted.Sort()
	'Compare the elements of both arrays.
	For j = 0 To UBound(arrPreSort)
		If arrPreSort(j) <> arrSorted(j) Then
			JortSort = False
			Exit For
		End If
	Next
End Function

WScript.StdOut.Write JortSort("1,2,3,4,5")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("1,2,3,5,4")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("a,b,c")
WScript.StdOut.WriteLine
WScript.StdOut.Write JortSort("a,c,b")


fn main() {
  println(jort_sort([1, 2, 1, 11, 213, 2, 4])) //false
  println(jort_sort([0, 1, 0, 0, 0, 0]))       //false
  println(jort_sort([1, 2, 4, 11, 22, 22]))    //true
  println(jort_sort([0, 0, 0, 1, 2, 2]))       //true
}

fn jort_sort(a []int) bool {
  mut c := a.clone()
  c.sort()
  for k, v in c {
    if v == a[k] {
      continue
    } else {
      return false
    }
  }
  return true
}


import "/sort" for Sort

var jortSort = Fn.new { |a|
    var b = Sort.merge(a)
    for (i in 0...a.count) {
        if (a[i] != b[i]) return false
    }
    return true
}

var tests = [ [1, 2, 3, 4, 5], [2, 1, 3, 4, 5] ]
for (test in tests) System.print("%(test) -> %(jortSort.call(test) ? "sorted" : "not sorted")")


fcn jort(list){ False!=list.reduce(fcn(a,b){ (a>b) and return(Void.Stop,False); b }) }


F count_jewels(s, j)
   R sum(s.map(x -> Int(x C @j)))

print(count_jewels(‘aAAbbbb’, ‘aA’))
print(count_jewels(‘ZZ’, ‘z’))


	org	100h
	jmp	demo
	;;;	Count jewels.
	;;;	Input: BC = jewels, DE = stones.
	;;;	Output: BC = count
	;;;	Destroyed: A, DE, HL
jewel:	lxi	h,jarr	; Zero out the page of memory
	xra	a
jzero:	mov	m,a
	inr	l
	jnz	jzero
jrjwl:	ldax	b	; Get jewel
	inx	b
	mov	l,a	; Mark the corresponding byte in the array
	inr	m
	ana	a	; If 'jewel' is 0, we've reached the end
	jnz	jrjwl	; Otherwise, do next jewel
	lxi	b,0	; BC = count (we no longer need the jewel string)
jrstn:	ldax	d	; Get stone
	inx	d
	ana	a	; If zero, we're done
	rz
	mov	l,a	; Get corresponding byte in array
	mov	a,m
	ana	a
	jz	jrstn	; If zero, it is not a jewel
	inx	b	; But otherwise, it is a jewel
	jmp	jrstn
	;;;	Demo code
demo:	lxi	b,jewels	; Set up registers
	lxi	d,stones
	call	jewel		; Call the function
	;;;	Print the number
	lxi	h,num	; Pointer to number string
	push	h	; Push to stack
	mov	h,b	; HL = number to print
	mov	l,c
	lxi	b,-10	; Divisor
dgt:	lxi	d,-1	; Quotient
dgtlp:	inx	d	; Divide using trial subtraction
	dad	b
	jc	dgtlp
	mvi	a,'0'+10
	add	l	; HL = remainder-10
	pop	h	; Get pointer
	dcx	h	; Decrement pointer
	mov	m,a	; Store digit
	push	h	; Put pointer back
	xchg		; Go on with new quotient
	mov	a,h	; If 0, we're done
	ana	l
	jnz	dgt	; If not 0, next digit
	pop	d	; Get pointer and put it in DE
	mvi	c,9	; CP/M syscall to print string
	jmp	5
	db	'*****'	; Placeholder for ASCII number output
num:	db	'$'
	;;;	Example from the task
jewels:	db	'aA',0
stones:	db	'aAAbbbb',0
	;;;	Next free page of memory is used for the jewel array
jpage:	equ	$/256+1
jarr:	equ	jpage*256


	cpu	8086
	bits	16
	org	100h
section	.text
	jmp	demo
	;;;	Count jewels.
	;;;	Input: DS:SI = jewels, DS:DX = stones
	;;;	Output: CX = how many stones are jewels
	;;;	Destroyed: AX, BX, SI, DI
jewel:	xor	ax,ax
	mov	cx,128		; Allocate 256 bytes (128 words) on stack
.zloop:	push	ax		; Set them all to zero
	loop	.zloop
	mov	di,sp		; DI = start of array
	xor	bh,bh
.sjwl:	lodsb			; Get jewel
	mov	bl,al
	inc	byte [ss:di+bx]	; Set corresponding byte
	test	al,al		; If not zero, there are more jewels
	jnz	.sjwl
	mov	si,dx		; Read stones
.sstn:	lodsb			; Get stone
	mov	bl,al		; Get corresponding byte
	mov	bl,[ss:di+bx]
	add	cx,bx		; Add to count (as word)
	test	al,al		; If not zero, there are more stones
	jnz	.sstn
	add	sp,256		; Otherwise, we are done - free the array
	dec	cx		; The string terminator is a 'jewel', so remove
	ret
	;;;	Demo
demo:	mov	si,jewels	; Set up registers
	mov	dx,stones
	call	jewel		; Call the function
	;;;	Print number
	mov	ax,10		; Result is in CX
	xchg	ax,cx		; Set AX to result and CX to divisor (10)
	mov	bx,num		; Number pointer
dgt:	xor	dx,dx
	div	cx		; Divide AX by 10
	add	dl,'0'		; Remainder is in DX - add ASCII 0
	dec	bx		; Store digit in string
	mov	[bx],dl
	test	ax,ax		; Any more digits?
	jnz	dgt		; If so, next digit
	mov	dx,bx		; When done, print string
	mov	ah,9
	int	21h
	ret
section	.data
	db	'*****'		; Placeholder for ASCII number output
num:	db	'$'
stones:	db	'aAAbbbb',0	; Example from the task
jewels:	db	'aA',0


with Ada.Text_IO;

procedure Jewels_And_Stones is

   function Count (Jewels, Stones : in String) return Natural is
      Sum : Natural := 0;
   begin
      for J of Jewels loop
         for S of Stones loop
            if J = S then
               Sum := Sum + 1;
               exit;
            end if;
         end loop;
      end loop;
      return Sum;
   end Count;

   procedure Show (Jewels, Stones : in String) is
      use Ada.Text_IO;
   begin
      Put (Jewels);
      Set_Col (12); Put (Stones);
      Set_Col (20); Put (Count (Jewels => Jewels,
                                Stones => Stones)'Image);
      New_Line;
   end Show;

begin
   Show ("aAAbbbb", "aA");
   Show ("ZZ",      "z");
end Jewels_And_Stones;


BEGIN
    # procedure that counts the number of times the letters in jewels occur in stones #
    PROC count jewels = ( STRING stones, jewels )INT:
         BEGIN
             # count the occurences of each letter in stones #
             INT upper a pos = 0;
             INT lower a pos = 1 + ( ABS "Z" - ABS "A" );
             [ upper a pos : lower a pos + 26 ]INT letter counts;
             FOR c FROM LWB letter counts TO UPB letter counts DO letter counts[ c ] := 0 OD;
             FOR s pos FROM LWB stones TO UPB stones DO
                 CHAR s = stones[ s pos ];
                 IF   s >= "A" AND s <= "Z" THEN letter counts[ upper a pos + ( ABS s - ABS "A" ) ] +:= 1
                 ELIF s >= "a" AND s <= "z" THEN letter counts[ lower a pos + ( ABS s - ABS "a" ) ] +:= 1
                 FI
             OD;
             # sum the counts of the letters that appear in jewels #
             INT count := 0;
             FOR j pos FROM LWB jewels TO UPB jewels DO
                 CHAR j = jewels[ j pos ];
                 IF   j >= "A" AND j <= "Z" THEN count +:= letter counts[ upper a pos + ( ABS j - ABS "A" ) ]
                 ELIF j >= "a" AND j <= "z" THEN count +:= letter counts[ lower a pos + ( ABS j - ABS "a" ) ]
                 FI
             OD;
             count
         END # count jewels # ;

    print( ( count jewels( "aAAbbbb", "aA" ), newline ) );
    print( ( count jewels( "[email protected]"
                         , "[email protected]"
                         )
           , newline
           )
         );
    print( ( count jewels( "AB", "" ), newline ) );
    print( ( count jewels( "ZZ", "z" ), newline ) )

END


-- jewelCount :: String -> String -> Int
on jewelCount(jewels, stones)
    set js to chars(jewels)
    script
        on |λ|(a, c)
            if elem(c, jewels) then
                a + 1
            else
                a
            end if
        end |λ|
    end script
    foldl(result, 0, chars(stones))
end jewelCount

-- OR in terms of filter
-- jewelCount :: String -> String -> Int
on jewelCount2(jewels, stones)
    script
        on |λ|(c)
            elem(c, jewels)
        end |λ|
    end script
    length of filter(result, stones)
end jewelCount2

-- TEST --------------------------------------------------
on run

    unlines(map(uncurry(jewelCount), ¬
        {Tuple("aA", "aAAbbbb"), Tuple("z", "ZZ")}))

end run

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

-- Tuple (,) :: a -> b -> (a, b)
on Tuple(a, b)
    {type:"Tuple", |1|:a, |2|:b}
end Tuple

-- chars :: String -> [Char]
on chars(s)
    characters of s
end chars

-- elem :: Eq a => a -> [a] -> Bool
on elem(x, xs)
    considering case
        xs contains x
    end considering
end elem

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

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

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

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

-- Returns a function on a single tuple (containing 2 arguments)
-- derived from an equivalent function with 2 distinct arguments
-- uncurry :: (a -> b -> c) -> ((a, b) -> c)
on uncurry(f)
    script
        property mf : mReturn(f)'s |λ|
        on |λ|(pair)
            mf(|1| of pair, |2| of pair)
        end |λ|
    end script
end uncurry

-- unlines :: [String] -> String
on unlines(xs)
    set {dlm, my text item delimiters} to ¬
        {my text item delimiters, linefeed}
    set str to xs as text
    set my text item delimiters to dlm
    str
end unlines


count: function [jewels,stones][
    size select split stones => [in? & jewels]
]

print count "aA" "aAAbbbb"


JewelsandStones(ss, jj){
	for each, jewel in StrSplit(jj)
		for each, stone in StrSplit(ss)
			if (stone == jewel)
				num++
	return num
}


# syntax: GAWK -f JEWELS_AND_STONES.AWK
BEGIN {
    printf("%d\n",count("aAAbbbb","aA"))
    printf("%d\n",count("ZZ","z"))
    exit(0)
}
function count(stone,jewel,  i,total) {
    for (i=1; i<length(stone); i++) {
      if (jewel ~ substr(stone,i,1)) {
        total++
      }
    }
    return(total)
}


10 READ N%
20 FOR A%=1 TO N%
30 READ J$,S$
40 GOSUB 100
50 PRINT S$;" in ";J$;":";J%
60 NEXT
70 END

100 REM Count how many stones (S$) are jewels (J$).
110 DIM J%(127)
120 J%=0
130 FOR I%=1 TO LEN(J$): J%(ASC(MID$(J$,I%,1)))=1: NEXT
140 FOR I%=1 TO LEN(S$): J%=J%+J%(ASC(MID$(S$,I%,1))): NEXT
150 ERASE J%
160 RETURN

200 DATA 2
210 DATA "aA","aAAbbbb"
220 DATA "z","ZZZZ"


function contar_joyas(piedras, joyas)
	cont = 0
	for i = 1 to length(piedras)
		bc = instr(joyas, mid(piedras, i, 1), 1)
		if bc <> 0 then cont += 1
	next i
	return cont
end function

print contar_joyas("aAAbbbb", "aA")
print contar_joyas("ZZ", "z")
print contar_joyas("[email protected]", "[email protected]tuvwxyz")
print contar_joyas("AB", "")


get "libhdr"

let jewels(j, s) = valof
$(  let jewel = vec 255
    let count = 0
    for i = 0 to 255 do jewel!i := false
    for i = 1 to j%0 do jewel!(j%i) := true
    for i = 1 to s%0 do
        if jewel!(s%i) then
            count := count + 1
    resultis count
$)

let show(j, s) be
    writef("*"%S*" in *"%S*": %N*N", j, s, jewels(j, s))

let start() be
$(  show("aA", "aAAbbbb")
    show("z", "ZZ")
$)


T.serializable Person
   String firstName, lastName
   Int age
   T PhoneNumber
      String ntype
      String number
   [PhoneNumber] phoneNumbers
   [String] children

Person p

json:to_object(‘
{
  "firstName": "John",
  "lastName": "Smith",
  "age": 27,
  "phoneNumbers": [
    {
      "ntype": "home",
      "number": "212 555-1234"
    },
    {
      "ntype": "office",
      "number": "646 555-4567"
    }
  ],
  "children": ["Mary", "Kate"]
}’, &p)

p.phoneNumbers.pop(0)
p.children.append(‘Alex’)

print(json:from_object(p))


  ( f
  =   stones jewels N
    .   !arg:(?stones.?jewels)
      & 0:?N
      & ( @( !stones
           :   ?
               (   %@
                 : [%(   @(!jewels:? !sjt ?)
                       & 1+!N:?N
                     |
                     )
               & ~
               )
               ?
           )
        | !N
        )
  )
& f$(aAAbbbb.aA)


#include <stdio.h>
#include <string.h>

int count_jewels(const char *s, const char *j) {
    int count = 0;
    for ( ; *s; ++s) if (strchr(j, *s)) ++count;
    return count;
}

int main() {
    printf("%d\n", count_jewels("aAAbbbb", "aA"));
    printf("%d\n", count_jewels("ZZ", "z"));
    return 0;
}


using System;
using System.Linq;

public class Program
{
    public static void Main() {
        Console.WriteLine(Count("aAAbbbb", "Aa"));
        Console.WriteLine(Count("ZZ", "z"));
    }

    private static int Count(string stones, string jewels) {
        var bag = jewels.ToHashSet();
        return stones.Count(bag.Contains);
    }
}


with Ada.Text_IO;
with GNATCOLL.JSON;

procedure JSON_Test is
   use Ada.Text_IO;
   use GNATCOLL.JSON;

   JSON_String : constant String := "{""name"":""Pingu"",""born"":1986}";

   Penguin : JSON_Value := Create_Object;
   Parents : JSON_Array;
begin
   Penguin.Set_Field (Field_Name => "name",
                      Field      => "Linux");

   Penguin.Set_Field (Field_Name => "born",
                      Field      => 1992);

   Append (Parents, Create ("Linus Torvalds"));
   Append (Parents, Create ("Alan Cox"));
   Append (Parents, Create ("Greg Kroah-Hartman"));

   Penguin.Set_Field (Field_Name => "parents",
                      Field      => Parents);

   Put_Line (Penguin.Write);

   Penguin := Read (JSON_String, "json.errors");

   Penguin.Set_Field (Field_Name => "born",
                      Field      => 1986);

   Parents := Empty_Array;
   Append (Parents, Create ("Otmar Gutmann"));
   Append (Parents, Create ("Silvio Mazzola"));

   Penguin.Set_Field (Field_Name => "parents",
                      Field      => Parents);

   Put_Line (Penguin.Write);
end JSON_Test;


#include <algorithm>
#include <iostream>

int countJewels(const std::string& s, const std::string& j) {
    int count = 0;
    for (char c : s) {
        if (j.find(c) != std::string::npos) {
            count++;
        }
    }
    return count;
}

int main() {
    using namespace std;

    cout << countJewels("aAAbbbb", "aA") << endl;
    cout << countJewels("ZZ", "z") << endl;

    return 0;
}


count_jewels = proc (jewels, stones: string) returns (int)
    is_jewel: array[bool] := array[bool]$fill(0, 256, false)
    for c: char in string$chars(jewels) do
        is_jewel[char$c2i(c)] := true
    end

    n_jewels: int := 0
    for c: char in string$chars(stones) do
        if is_jewel[char$c2i(c)] then n_jewels := n_jewels + 1 end
    end
    return (n_jewels)
end count_jewels

show = proc (jewels, stones: string)
    po: stream := stream$primary_output()

    stream$putl(po, "\"" || jewels || "\" in \"" || stones || "\": "
                || int$unparse(count_jewels(jewels, stones)))
end show

start_up = proc ()
    show("aA", "aAAbbbb")
end start_up


include "cowgol.coh";

sub count_jewels(stones: [uint8], jewels: [uint8]): (count: uint16) is
    var jewel_mark: uint8[256];
    MemZero(&jewel_mark as [uint8], 256);

    while [jewels] != 0 loop
        jewel_mark[[jewels]] := 1;
        jewels := @next jewels;
    end loop;

    count := 0;
    while [stones] != 0 loop
        count := count + jewel_mark[[stones]] as uint16;
        stones := @next stones;
    end loop;
end sub;

sub print_and_count(stones: [uint8], jewels: [uint8]) is
    print(jewels);
    print(" in ");
    print(stones);
    print(": ");
    print_i16(count_jewels(stones, jewels));
    print_nl();
end sub;

print_and_count("aAAbbbb", "aA");
print_and_count("ZZ", "z");


stones, jewels = "aAAbbbb", "aA"
stones.count(jewels) # => 3

# The above solution works for that case, but fails with certain other "jewels":
stones, jewels = "aA^Bb", "^b"
stones.count(jewels) # => 4
# '^b' in the "jewels" is read as "characters other than 'b'".

# This works as intended though:
stones.count { |c| jewels.chars.includes?(c) } # => 2


F sum(&i, lo, hi, term)
   V temp = 0.0
   i = lo
   L i <= hi
      temp += term()
      i++
   R temp

F main()
   Int i
   print(sum(&i, 1, 100, () -> 1 / @i))

main()


//  Parse JSON
//
//  Nigel Galloway - April 27th., 2012
//
grammar JSON ;
@members {
String Indent = "";
}
Number	:	(('0')|('-'? ('1'..'9') ('0'..'9')*)) ('.' ('0'..'9')+)? (('e'|'E') ('+'|'-')? ('0'..'9')+)?;
WS	:	(' ' | '\t' | '\r' |'\n') {skip();};
Tz	:	' ' .. '!' | '#' .. '[' | ']' .. '~';
Control	:	'\\' ('"'|'\\'|'/'|'b'|'f'|'n'|'r'|'t'|UCode);
UCode	:	'u' ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F') ('0'..'9'|'a'..'f'|'A'..'F');
Keyword	:	'true' | 'false' | 'null';
String	:	'"' (Control? Tz)* '"';
object	:       '{' {System.out.println(Indent + "{Object}"); Indent += "    ";} (pair (',' pair*)*)? '}' {Indent = Indent.substring(4);};
pair	:	e = String {System.out.println(Indent + "{Property}\t" + $e.text);} ':' value;
value	:	Number             {System.out.println(Indent + "{Number}  \t" + $Number.text);}
	|	object
	|	String             {System.out.println(Indent + "{String}  \t" + $String.text);}
	|	Keyword            {System.out.println(Indent + "{Keyword} \t" + $Keyword.text);}
	|	array;
array	:	'[' {System.out.println(Indent + "Array"); Indent += "    ";} (value (',' value)*)? ']' {Indent = Indent.substring(4);};


import std.algorithm;
import std.stdio;

int countJewels(string s, string j) {
    int count;
    foreach (c; s) {
        if (j.canFind(c)) {
            count++;
        }
    }
    return count;
}

void main() {
    countJewels("aAAbbbb", "aA").writeln;
    countJewels("ZZ", "z").writeln;
}


proc nonrec count_jewels(*char jewels, stones) word:
    [256] bool jewel;
    word count;
    byte i;
    char c;

    for i from 0 upto 255 do jewel[i] := false od;
    while c := jewels*; c ~= '\e' do
        jewel[c] := true;
        jewels := jewels + 1;
    od;

    count := 0;
    while c := stones*; c ~= '\e' do
        if jewel[c] then count := count + 1 fi;
        stones := stones + 1
    od;
    count
corp

proc nonrec show(*char jewels, stones) void:
    writeln("'", jewels, "' in '", stones, "': ", count_jewels(jewels, stones))
corp

proc nonrec main() void:
    show("aA", "aAAbbbb");
    show("z", "ZZ")
corp


func countJewels(stones, jewels) {
    stones.Iterate().Map(x => jewels.Contains(x) ? 1 : 0).Reduce((x,y) => x + y, 0)
}

print(countJewels("aAAbbbb", "aA"))
print(countJewels("ZZ", "z"))


let fN jewels stones=stones|>Seq.filter(fun n->Seq.contains n jewels)|>Seq.length
printfn "%d" (fN "aA" "aAAbbbb")


F totalvalue(comb)
   V totwt = 0
   V totval = 0
   L(item, wt, val) comb
      totwt += wt
      totval += val
   R I totwt <= 400 {(totval, -totwt)} E (0, 0)

V items = [
   (‘map’, 9, 150), (‘compass’, 13, 35), (‘water’, 153, 200), (‘sandwich’, 50, 160),
   (‘glucose’, 15, 60), (‘tin’, 68, 45), (‘banana’, 27, 60), (‘apple’, 39, 40),
   (‘cheese’, 23, 30), (‘beer’, 52, 10), (‘suntan cream’, 11, 70), (‘camera’, 32, 30),
   (‘t-shirt’, 24, 15), (‘trousers’, 48, 10), (‘umbrella’, 73, 40),
   (‘waterproof trousers’, 42, 70), (‘waterproof overclothes’, 43, 75),
   (‘note-case’, 22, 80), (‘sunglasses’, 7, 20), (‘towel’, 18, 12), (‘socks’, 4, 50),
   (‘book’, 30, 10)
]

F knapsack01_dp(items, limit)
   V table = [[0] * (limit + 1)] * (items.len + 1)

   L(j) 1 .. items.len
      V (item, wt, val) = items[j - 1]
      L(w) 1 .. limit
         I wt > w
            table[j][w] = table[j - 1][w]
         E
            table[j][w] = max(table[j - 1][w], table[j - 1][w - wt] + val)

   [(String, Int, Int)] result
   V w = limit
   L(j) (items.len .< 0).step(-1)
      I table[j][w] != table[j - 1][w]
         V (item, wt, val) = items[j - 1]
         result.append(items[j - 1])
         w -= wt
   R result

V bagged = knapsack01_dp(items, 400)
print("Bagged the following items\n  "sorted(bagged.map((item, _, _2) -> item)).join("\n  "))
V (val, wt) = totalvalue(bagged)
print(‘for a total value of #. and a total weight of #.’.format(val, -wt))