#include <stdio.h>
#include <X11/Xlib.h>

int main()
{
  Display *d;
  Window inwin;      /* root window the pointer is in */
  Window inchildwin; /* child win the pointer is in */
  int rootx, rooty; /* relative to the "root" window; we are not interested in these,
                       but we can't pass NULL */
  int childx, childy;  /* the values we are interested in */
  Atom atom_type_prop; /* not interested */
  int actual_format;   /* should be 32 after the call */
  unsigned int mask;   /* status of the buttons */
  unsigned long n_items, bytes_after_ret;
  Window *props; /* since we are interested just in the first value, which is
		    a Window id */

  /* default DISPLAY */
  d = XOpenDisplay(NULL);

  /* ask for active window (no error check); the client must be freedesktop
     compliant */
  (void)XGetWindowProperty(d, DefaultRootWindow(d),
			   XInternAtom(d, "_NET_ACTIVE_WINDOW", True),
			   0, 1, False, AnyPropertyType,
			   &atom_type_prop, &actual_format,
			   &n_items, &bytes_after_ret, (unsigned char**)&props);

  XQueryPointer(d, props[0], &inwin,  &inchildwin,
		&rootx, &rooty, &childx, &childy, &mask);
  printf("relative to active window: %d,%d\n", childx, childy);

  XFree(props);           /* free mem */
  (void)XCloseDisplay(d); /* and close the display */
  return 0;
}


using System;
using System.Windows.Forms;
static class Program
{
    [STAThread]
    static void Main()
    {
        Console.WriteLine(Control.MousePosition.X);
        Console.WriteLine(Control.MousePosition.Y);
    }
}


(let [point (.. java.awt.MouseInfo getPointerInfo getLocation)] [(.getX point) (.getY point)])


(ql:quickload "ltk")
(in-package :ltk-user)
(defun motion (event)
    (format t "~a x position is ~a~&" event (event-x event)))

(with-ltk ()
    ;; create a small window. Enter the mouse to see lots of events.
    (bind *tk* "<Motion>" #'motion))


procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
   lblMousePosition.Caption := ('X:' + IntToStr(X) + ', Y:' + IntToStr(Y));
end;


on mouse_move
  clear
  text mouse_x & " " & mouse_y
.


(lib 'plot)
(plot-x-minmax 10) ; set logical dimensions of plotting area
(plot-y-minmax 100)
  → (("x" 0 10) ("y" 0 100))
;; press ESC to see the canvas
;; the mouse position is displayed as , for example,  [ x: 5.6 y : 88.7]
;; 0 <= x <= 10, 0 <= y <= 100


import Graphics.Element exposing (Element, show)
import Mouse

main : Signal Element
main =
  Signal.map show Mouse.position


(mouse-pixel-position)
;; => (FRAME . (X . Y))


!
! MOUSE WITH 'MOUSE.LIB' LIBRARY
!

PROGRAM MOUSE

!$KEY

!$INCLUDE="PC.LIB"

!$INCLUDE="MOUSE.LIB"

PROCEDURE GETMONITORTYPE(->MONITOR$)
      !$RCODE="DEF SEG=0"
      STATUS=PEEK($463)
      !$RCODE="DEF SEG"
      MONITOR$=""
      IF STATUS=$B4 THEN
         !$RCODE="STATUS=(INP(&H3BA) AND &H80)"
         FOR DELAYLOOP=1 TO 30000 DO
             !$RCODE="XX=((INP(&H3BA) AND &H80)<>STATUS)"
             IF XX THEN MONITOR$="HERC" END IF
         END FOR
         IF MONITOR$="" THEN MONITOR$="MONO" END IF
       ELSE
          REGAX%=$1A00
          EXECUTEASM($10)
          IF (REGAX% AND $FF)=$1A THEN
                MONITOR$="VGA"
             ELSE
                REGAX%=$1200  REGBX%=$10
                EXECUTEASM($10)
                IF (REGBX% AND $FF)=$10 THEN
                     MONITOR$="CGA"
                  ELSE
                     MONITOR$="EGA"
                END IF
          END IF
      END IF
END PROCEDURE

BEGIN
    INITASM
    GETMONITORTYPE(->MONITOR$)
    COLOR(7,0)
    CLS
    LOCATE(1,50)  PRINT("MONITOR TYPE  ";MONITOR$)
    MOUSE_RESETANDSTATUS(->STATUS,BUTTONS)
    IF STATUS<>-1 THEN
        BEEP
        CLS
        PRINT("MOUSE DRIVER NOT INSTALLED OR MOUSE NOT FOUND")
        REPEAT
           GET(IN$)
        UNTIL IN$<>""
     ELSE
        MOUSE_SETEXTCURSOR
        MOUSE_SETCURSORLIMITS(8,199,0,639)
        MOUSE_SETSENSITIVITY(30,30,50)
        MOUSE_SHOWCURSOR
        REPEAT
          OLDX=X  OLDY=Y
          MOUSE_GETCURSORPOSITION(->X,Y,LEFT%,RIGHT%,BOTH%,MIDDLE%)
          GET(IN$)
          COLOR(15,0)
          LOCATE(1,2)
          PRINT("X =";INT(X/8)+1;"  Y =";INT(Y/8)+1;"  ";)
          IF LEFT%   THEN LOCATE(1,37) COLOR(10,0)  PRINT("LEFT";) END IF
          IF RIGHT%  THEN LOCATE(1,37) COLOR(12,0)  PRINT("RIGHT";) END IF
          IF MIDDLE% THEN LOCATE(1,37) COLOR(14,0)  PRINT("MIDDLE";) END IF
          IF NOT RIGHT% AND NOT LEFT% AND NOT MIDDLE% THEN
              LOCATE(1,37)  PRINT("       ";)
          END IF
          IF NOT (X=OLDX AND Y=OLDY) THEN MOUSE_SHOWCURSOR END IF
        UNTIL IN$=CHR$(27)
   END IF
   MOUSE_HIDECURSOR
   CLS
END PROGRAM


open System.Windows.Forms
open System.Runtime.InteropServices

#nowarn "9"
[<Struct; StructLayout(LayoutKind.Sequential)>]
type POINT =
    new (x, y) = { X = x; Y = y }
    val X : int
    val Y : int

[<DllImport("user32.dll")>]
extern nativeint GetForegroundWindow();
[<DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true, ExactSpelling=true)>]
extern int ScreenToClient(nativeint hWnd, POINT &pt);

let GetMousePosition() =
    let hwnd = GetForegroundWindow()
    let pt = Cursor.Position
    let mutable ptFs = new POINT(pt.X, pt.Y)
    ScreenToClient(hwnd, &ptFs) |> ignore
    ptFs


: replace-text ( button text -- )
    [ drop children>> pop drop ] [ >label add-gadget drop ] 2bi ;
: present-locations ( loc1 loc2 -- string )
    [
      first2 [ number>string ] [email protected] "," glue
    ] [email protected] ";" glue ;
: example ( -- ) "click me"
[
  dup hand-rel ! location relative to the button
  hand-loc get ! location relative to the window
  present-locations replace-text
]
<border-button> gadget. ;


type MOUSE
   'mouse position, button state, wheel state
   x as integer
   y as integer
   buttons as integer
   wheel as integer
end type

screen 12

dim as MOUSE mouse

while inkey=""
    locate 1,1
    getmouse(mouse.x, mouse.y, mouse.wheel, mouse.buttons)
    if mouse.x < 0 then
        print "Mouse out of window.                                  "
        print "                                                      "
        print "                                                      "
    else
        print "Mouse position : ", mouse.x, mouse.y, "            "
        print "Buttons clicked: ";
        print Iif( mouse.buttons and 1, "Left      ", "          " );
        print Iif( mouse.buttons and 2, "Right     ", "          " );
        print Iif( mouse.buttons and 4, "Middle    ", "          " )
        print "Wheel scrolls: ", mouse.wheel," "
    end if
wend


PUBLIC SUB Form1_MouseMove()
PRINT mouse.X
PRINT Mouse.Y
END


package main

import (
    "fmt"
    "github.com/go-vgo/robotgo"
)

func isInside(x, y, w, h, mx, my int) bool {
    rx := x + w - 1
    ry := y + h - 1
    return mx >= x && mx <= rx && my >= y && my <= ry
}

func main() {
    name := "gedit" // say
    fpid, err := robotgo.FindIds(name)
    if err == nil && len(fpid) > 0 {
        pid := fpid[0]
        robotgo.ActivePID(pid) // make gedit active window
        x, y, w, h := robotgo.GetBounds(pid)
        fmt.Printf("The active window's top left corner is at (%d, %d)\n", x, y)
        fmt.Printf("Its width is %d and its height is %d\n", w, h)
        mx, my := robotgo.GetMousePos()
        fmt.Printf("The screen location of the mouse cursor is (%d, %d)\n", mx, my)
        if !isInside(x, y, w, h, mx, my) {
            fmt.Println("The mouse cursor is outside the active window")
        } else {
            wx := mx - x
            wy := my - y
            fmt.Printf("The window location of the mouse cursor is (%d, %d)\n", wx, wy)
        }
    } else {
        fmt.Println("Problem when finding PID(s) of", name)
    }
}


1.upto(5) {
    Thread.sleep(1000)
    def p = java.awt.MouseInfo.pointerInfo.location
    println "${it}: x=${[email protected]} y=${[email protected]}"
}


   WINDOW(WINdowhandle=handle)
   AXIS(WINdowhandle=handle, MouSeCall=Mouse_Callback, MouSeX=X, MouSeY=Y)
 END

SUBROUTINE Mouse_Callback()
   WRITE(Messagebox, Name) X, Y
 END


until *Pending() > 0 & Event() == "q" do { # loop until there is something to do
   px := WAttrib("pointerx")
   py := WAttrib("pointery")
   #  do whatever is needed
   WDelay(5)  # wait and share processor
   }


Point mouseLocation = MouseInfo.getPointerInfo().getLocation();


document.addEventListener('mousemove', function(e){
  var position = { x: e.clientX, y: e.clientY }
}


using Gtk

const win = GtkWindow("Get Mouse Position", 600, 800)
const butn = GtkButton("Click Me Somewhere")
push!(win, butn)

callback(b, evt) = set_gtk_property!(win, :title, "Mouse Position: X is $(evt.x), Y is $(evt.y)")
signal_connect(callback, butn, "button-press-event")

showall(win)

c = Condition()
endit(w) = notify(c)
signal_connect(endit, win, :destroy)
wait(c)


// version 1.1.2

import java.awt.MouseInfo

fun main(args: Array<String>) {
    (1..5).forEach {
        Thread.sleep(1000)
        val p = MouseInfo.getPointerInfo().location  // gets screen coordinates
        println("${it}: x = ${"%-4d".format(p.x)} y = ${"%-4d".format(p.y)}")
    }
}


    nomainwin

    UpperLeftX = DisplayWidth-WindowWidth
    UpperLeftY = DisplayHeight-WindowHeight

    struct point, x as long, y as long

    stylebits #main.st ,0,0,_WS_EX_STATICEDGE,0
    statictext #main.st "",16,16,100,26

    stylebits #main ,0,0,_WS_EX_TOPMOST,0
    open "move your mouse" for window_nf as #main

    #main "trapclose [quit]"
    timer 100, [mm]
    wait

[mm]
    CallDll #user32, "GetForegroundWindow", WndHandle as uLong
    #main.st CursorPos$(WndHandle)
    wait

[quit]
    close #main
    end

function CursorPos$(handle)
    Calldll #user32, "GetCursorPos",_
        point as struct,_
        result as long
    Calldll #user32, "ScreenToClient",_
        handle As Ulong,_
        point As struct,_
        result as long
    x = point.x.struct
    y = point.y.struct
    CursorPos$=x; ",";y
end function


-- Method 1:
-- this script in either the stack script or the card script to get position relative to the current stack window
on mouseMove pMouseH,pMouseV
   put pMouseH,pMouse
end mouseMove

-- Method 2:
-- this script can go anywhere to get current position relative to the current stack window
put mouseLoc()

-- Method 3:
-- this script can go anywhere to get current position relative to the current stack window
put the mouseLoc

-- Method 4:
-- this script can go anywhere to get current position relative to the current window
put the mouseH &","& the mouseV

To get the mousePosition relative to the current screen instead of relative to the current stack window use the screenMouseLoc keyword
example results:
117,394 -- relative to current window
117,394 -- relative to current window
117,394 -- relative to current window
148,521 -- relative to current screen


LiveCode Builder (LCB) is a slightly lower level, strictly typed variant of LiveCode Script (LCS) used for making add-on extensions to LiveCode Script

-- results will be a point array struct like [117.0000,394.0000] relative to the current widget's view port
use com.livecode.widget -- include the required module
--- in your handler:
variable tPosition as Point -- type declaration, tPosition is a point array struct
put the mouse position into tPosition
variable tRect as Rectangle -- type declaration, tRect is a rect array struct, something like [0,1024,0,768]
put my bounds into tRect
if tPosition is within tRect then
   log "mouse position is within the widget bounds"
end if


Module Checkit {
	\\ works when console is the active window
	\\ pressing right mouse button exit the loop
	While mouse<>2
		Print mouse.x, mouse.y
	End While
	\\ end of part one, now we make a form with title Form1 (same name as the variable name)
	Declare Form1 Form
	Layer Form1 {
		window 16, 10000,8000  ' 16pt font at maximum 10000 twips x 8000 twips
		cls #335522, 1 \\ from 2nd line start the split screen (for form's layer)
		pen 15 ' white
	}
	Function Form1.MouseMove {
		Read new button, shift, x, y  ' we use new because call is local, same scope as Checkit.
		Layer Form1 {
			print x, y, button
			refresh
		}
	}
	Function Form1.MouseDown {
		Read new button, shift, x, y
		\\ when we press mouse button we print in console
		\\ but only the first time
		print x, y, button
		refresh
	}
	\\ open Form1 as modal window above console
	Method Form1, "Show", 1
	Declare Form1 Nothing
}
CheckIt


try destroydialog mousePos catch ()

rollout mousePos "Mouse position" width:200
(
	label mousePosText "Current mouse position:" pos:[0,0]
	label mousePosX "" pos:[130,0]
	label mousePosSep "x" pos:[143,0]
	label mousePosY "" pos:[160,0]

	timer updateTimer interval:50 active:true

	on updateTimer tick do
	(
		mousePosX.text = (mouse.screenpos.x as integer) as string
		mousePosY.text = (mouse.screenpos.y as integer) as string
	)

)

createdialog mousepos


import Nanoquery.Util.Windows

// a function to handle the mouse moved event
def mouse_moved($caller, $e)
	println "(" + $e.getX() + ", " + $e.getY() + ")"
end

// create a window, set the handler for mouse moved, and show it
w = new("Window")
w.setSize(500, 500)
w.setHandler(w.mouseMoved, mouse_moved)
w.show()


import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window

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

proc onButtonPress(window: ApplicationWindow; event: Event; data: pointer): bool =
  echo event.getCoords()
  result = true

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

proc activate(app: Application) =
  ## Activate the application.

  let window = app.newApplicationWindow()
  window.setTitle("Mouse position")
  window.setSizeRequest(640, 480)

  discard window.connect("button-press-event", onButtonPress, pointer(nil))

  window.showAll()

#———————————————————————————————————————————————————————————————————————————————————————————————————

let app = newApplication(Application, "Rosetta.MousePosition")
discard app.connect("activate", activate)
discard app.run()


open Xlib

let () =
  let d = xOpenDisplay "" in

  (* ask for active window (no error check);
     the client must be freedesktop compliant *)
  let _, _, _, _, props =
    xGetWindowProperty_window d
        (xDefaultRootWindow d)
        (xInternAtom d "_NET_ACTIVE_WINDOW" true)
        0 1 false AnyPropertyType
  in

  let _, _, _, child, _ = xQueryPointer d props in
  begin match child with
  | Some(_, childx, childy) ->
      Printf.printf "relative to active window: %d,%d\n%!" childx childy;
  | None ->
      print_endline "the pointer is not on the same screen as the specified window"
  end;

  xCloseDisplay d;
;;


declare
  [QTk] = {Module.link ['x-oz://system/wp/QTk.ozf']}
  WindowClosed = {NewCell false}
  Label
  Window = {QTk.build
	    td(action:proc {$} WindowClosed := true {Window close} end
	       label(text:"" handle:Label))}
in
  {Window show}

  for while:{Not @WindowClosed} do
     TopmostWindow = {List.last {String.tokens {Tk.return wm(stackorder '.')} & }}
     Winfo = {Record.mapInd winfo(rootx:_ rooty:_ pointerx:_ pointery:_)
	      fun {$ I _}
		 {Tk.returnInt winfo(I TopmostWindow)}
	      end}
  in
     {Label set(text:"x: "#(Winfo.pointerx - Winfo.rootx)
		#", y: "#(Winfo.pointery - Winfo.rooty))}
     {Delay 250}
  end


use SDL;
use SDL::Events;
use SDLx::App;

my $app = SDLx::App->new;
$app->add_event_handler( sub {
	my $event = shift;
	if( $event->type == SDL_MOUSEMOTION ) {
		printf( "x=%d y=%d\n", $event->motion_x, $event->motion_y );
		$app->stop
	}
} );
$app->run;


-- demo\rosetta\Mouse_position.exw
include pGUI.e

Ihandle global_lbl, canvas_lbl, timer_lbl

function globalmotion_cb(integer x, integer y, atom /*pStatus*/)
    IupSetStrAttribute(global_lbl,"TITLE","globalmotion_cb %d, %d",{x,y})
    return IUP_DEFAULT
end function

function canvas_motion_cb(Ihandle /*canvas*/, integer x, integer y, atom pStatus)
    IupSetStrAttribute(canvas_lbl,"TITLE","canvasmotion_cb %d, %d",{x,y})
    return IUP_DEFAULT;
end function

function OnTimer(Ihandle /*ih*/)
    integer {x,y} = IupGetIntInt(NULL,"CURSORPOS")
    IupSetStrAttribute(timer_lbl,"TITLE","timer %d, %d",{x,y})
    return IUP_IGNORE
end function

procedure main()
Ihandle separator1, separator2,
        canvas, frame_1, frame_2,
        dialog

    IupOpen()

    global_lbl = IupLabel("Move the mouse anywhere on the window","EXPAND=HORIZONTAL")
    separator1 = IupLabel(NULL,"SEPARATOR=HORIZONTAL")
    canvas_lbl = IupLabel("Move the mouse anywhere on the canvas","EXPAND=HORIZONTAL")
    separator2 = IupLabel(NULL,"SEPARATOR=HORIZONTAL")
    timer_lbl  = IupLabel("This one runs on a three second timer","EXPAND=HORIZONTAL")

    frame_1 = IupFrame(IupVbox({global_lbl,
                                separator1,
                                canvas_lbl,
                                separator2,
                                timer_lbl}),
                      "TITLE=IupLabel, SIZE=200x")

    canvas = IupCanvas("MOTION_CB", Icallback("canvas_motion_cb"),
                       "EXPAND=HORIZONTAL, RASTERSIZE=200x200")
    frame_2 = IupFrame(canvas, "TITLE=IupCanvas")

    dialog = IupDialog(IupHbox({frame_1,frame_2}, "MARGIN=5x5, GAP=5"))
    IupSetAttribute(dialog,"TITLE","Mouse motion");

    IupSetGlobal("INPUTCALLBACKS", "Yes");
    IupSetGlobalFunction("GLOBALMOTION_CB", Icallback("globalmotion_cb"));

    Ihandle hTimer = IupTimer(Icallback("OnTimer"), 3000)

    IupShow(dialog)

    IupMainLoop()
    IupClose()
end procedure
main()


(de mousePosition ()
   (prog2
      (prin "^[[?9h")  # Mouse reporting on
      (and
         (= "^[" (key))
         (key 200)
         (key 200)
         (key)
         (cons
            (- (char (key)) 32)
            (- (char (key)) 32) ) )
      (prin "^[[?9l") ) )  # Mouse reporting off


x = WindowMouseX(#MyWindow)
y = WindowMouseY(#MyWindow)


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

void draw(){
  // mouseX and mouseY provide the current mouse position
  ellipse(mouseX, mouseY, 5, 5); // graphic output example
  println("x:" + mouseX + " y:" + mouseY);
}


import Tkinter as tk

def showxy(event):
    xm, ym = event.x, event.y
    str1 = "mouse at x=%d  y=%d" % (xm, ym)
    # show cordinates in title
    root.title(str1)
    # switch color to red if mouse enters a set location range
    x,y, delta = 100, 100, 10
    frame.config(bg='red'
                 if abs(xm - x) < delta and abs(ym - y) < delta
                 else 'yellow')

root = tk.Tk()
frame = tk.Frame(root, bg= 'yellow', width=300, height=200)
frame.bind("<Motion>", showxy)
frame.pack()

root.mainloop()


#lang racket/gui
(define-values [point _] (get-current-mouse-state))
(send point get-x)
(send point get-y)


use java::awt::MouseInfo:from<java>;

given MouseInfo.getPointerInfo.getLocation {
    say .getX, 'x', .getY;
}


Load "guilib.ring"

lPress = false
nX = 0
nY = 0

new qApp {

        win1 = new qWidget()
        {

                setWindowTitle("Move this label!")
                setGeometry(100,100,400,400)
                setstylesheet("background-color:white;")

                Label1 = new qLabel(Win1){
                        setGeometry(100,100,200,50)
                        setText("Welcome")
                        setstylesheet("font-size: 30pt")
                        myfilter = new qallevents(label1)
                        myfilter.setEnterevent("pEnter()")
                        myfilter.setLeaveevent("pLeave()")
                        myfilter.setMouseButtonPressEvent("pPress()")
                        myfilter.setMouseButtonReleaseEvent("pRelease()")                                                               myfilter.setMouseMoveEvent("pMove()")
                        installeventfilter(myfilter)
                }

                show()
        }

        exec()
}

Func pEnter
        Label1.setStyleSheet("background-color: purple; color:white;font-size: 30pt;")

Func pLeave
        Label1.setStyleSheet("background-color: white; color:black;font-size: 30pt;")

Func pPress
        lPress = True
        nX = myfilter.getglobalx()
        ny = myfilter.getglobaly()

Func pRelease
        lPress = False
        pEnter()

Func pMove
        nX2 = myfilter.getglobalx()
        ny2 = myfilter.getglobaly()
        ndiffx = nX2 - nX
        ndiffy = nY2 - nY
        if lPress
                Label1 {
                        move(x()+ndiffx,y()+ndiffy)
                        setStyleSheet("background-color: Green;
                                 color:white;font-size: 30pt;")
                        nX = nX2
                        ny = nY2
                }
        ok


Shoes.app(:title => "Mouse Position", :width => 400, :height => 400) do
  @position = para "Position : ?, ?", :size => 12, :margin => 10

  motion do |x, y|
    @position.text = "Position : #{x}, #{y}"
  end
end


// rustc 0.9 (7613b15 2014-01-08 18:04:43 -0800)

use std::libc::{BOOL, HANDLE, LONG};
use std::ptr::mut_null;

type HWND = HANDLE;

#[deriving(Eq)]
struct POINT {
    x: LONG,
    y: LONG
}

#[link_name = "user32"]
extern "system" {
    fn GetCursorPos(lpPoint:&mut POINT) -> BOOL;
    fn GetForegroundWindow() -> HWND;
    fn ScreenToClient(hWnd:HWND, lpPoint:&mut POINT);
}

fn main() {
    let mut pt = POINT{x:0, y:0};
    loop {
        std::io::timer::sleep(100); // sleep duration in milliseconds

        let pt_prev = pt;
        unsafe { GetCursorPos(&mut pt) };
        if pt != pt_prev {
            let h = unsafe { GetForegroundWindow() };
            if h == mut_null() { continue }

            let mut pt_client = pt;
            unsafe { ScreenToClient(h, &mut pt_client) };
            println!("x: {}, y: {}", pt_client.x, pt_client.y);
        }
    }
}


import java.awt.MouseInfo
object MousePosition extends App {
  val mouseLocation = MouseInfo.getPointerInfo.getLocation
  println (mouseLocation)
}


xPos := pointerXPos(curr_win);
yPos := pointerYPos(curr_win);


World activeHand position. " ([email protected])"


open XWindows ;
val dp =  XOpenDisplay "" ;
val w  =  XCreateSimpleWindow (RootWindow dp) origin (Area {x=0,y=0,w=400,h=300}) 3 0 0xffffff ;
XMapWindow w;
val (focus,_)=( Posix.Process.sleep (Time.fromReal 2.0);         (* time to move from interpreter + activate arbitrary window *)
	        XGetInputFocus dp
              ) ;
XQueryPointer focus ;
XQueryPointer w;


package require Tk 8.5
set curWindow [lindex [wm stackorder .] end]
# Everything below will work with anything from Tk 8.0 onwards
set x [expr {[winfo pointerx .] - [winfo rootx $curWindow]}]
set y [expr {[winfo pointery .] - [winfo rooty $curWindow]}]
tk_messageBox -message "the mouse is at ($x,$y) in window $curWindow"


Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    'X and Y are in "twips" -- 15 twips per pixel
    Me.Print "X:" & X
    Me.Print "Y:" & Y
End Sub


import "dome" for Window
import "graphics" for Canvas
import "input" for Mouse

class Game {
    static init() {
        Window.title = "Mouse position"
        Canvas.resize(400, 400)
        Window.resize(400, 400)
        // get initial mouse coordinates
        __px = Mouse.x
        __py = Mouse.y
        __ticks = 0
        System.print("The coordinates of the mouse relative to the canvas are:")
    }

    static update() {
        __ticks = __ticks + 1
        if (__ticks%60 == 0) {
            // get current mouse coordinates
            var cx = Mouse.x
            var cy = Mouse.y
            // if it's moved in the last second, report new position
            if (cx != __px || cy != __py) {
                System.print([cx, cy])
                __px = cx
                __py = cy
            }
        }
    }

    static draw(alpha) {}
}


include c:\cxpl\stdlib;
if not OpenMouse then Text(0, "A mouse is required")
else [ShowMouse(true);
      IntOut(0, GetMousePosition(0));  ChOut(0, ^,);
      IntOut(0, GetMousePosition(1));  CrLf(0);
     ]


BEGIN # find some Motzkin numbers #
    PR read "primes.incl.a68" PR
    # returns a table of the Motzkin numbers 0 .. n #
    OP   MOTZKIN = ( INT n )[]LONG LONG INT:
         BEGIN
            [ 0 : n ]LONG LONG INT m;
            IF n >= 0 THEN
                m[ 0 ] := 1;
                IF n >= 1 THEN
                    m[ 1 ] := 1;
                    FOR i FROM 2 TO UPB m DO
                        m[ i ] := ( ( m[ i - 1 ] * ( ( 2 * i ) + 1  ) )
                                  + ( m[ i - 2 ] * ( ( 3 * i ) - 3  ) )
                                  )
                             OVER ( i + 2 )
                    OD
                FI
            FI;
            m
         END # MOTZKIN # ;
    # returns a string representation of n with commas                       #
    PROC commatise = ( LONG LONG INT n )STRING:
         BEGIN
            STRING result      := "";
            STRING unformatted  = whole( n, 0 );
            INT    ch count    := 0;
            FOR c FROM UPB unformatted BY -1 TO LWB unformatted DO
                IF   ch count <= 2 THEN ch count +:= 1
                ELSE                    ch count  := 1; "," +=: result
                FI;
                unformatted[ c ] +=: result
            OD;
            result
         END; # commatise #
    # left-pads a string to at least n characters                            #
    PROC pad left = ( STRING s, INT n )STRING:
         BEGIN
             STRING result := s;
             WHILE ( UPB result - LWB result ) + 1 < n DO " " +=: result OD;
             result
         END; # pad left #

    # show the Motzkin numbers #
    print( ( " n                      M[n] Prime?", newline ) );
    print( ( "-----------------------------------", newline ) );
    []LONG LONG INT m = MOTZKIN 41;
    FOR i FROM LWB m TO UPB m DO
        print( ( whole( i, -2 )
               , pad left( commatise( m[ i ] ), 26 )
               , IF is probably prime( m[ i ] ) THEN "  prime" ELSE "" FI
               , newline
               )
             )
    OD
END


# syntax: GAWK --bignum -f MOTZKIN_NUMBERS.AWK
BEGIN {
    print(" n         Motzkin[n] prime")
    limit = 41
    m[0] = m[1] = 1
    for (i=2; i<=limit; i++) {
      m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2)
    }
    for (i=0; i<=limit; i++) {
      printf("%2d %18d %3d\n",i,m[i],is_prime(m[i]))
    }
    exit(0)
}
function is_prime(x,  i) {
    if (x <= 1) {
      return(0)
    }
    for (i=2; i<=int(sqrt(x)); i++) {
      if (x % i == 0) {
        return(0)
      }
    }
    return(1)
}


dim M(42)
M[0] = 1 : M[1] = 1
print rjust("1",18) : print rjust("1",18)

for n = 2 to 41
	M[n] = M[n-1]
	for i = 0 to n-2
		M[n] += M[i]*M[n-2-i]
	next i
	print rjust(string(M[n]),18); chr(9);
	if isPrime(M[n]) then print "is a prime" else print
next n
end

function isPrime(v)
	if v <= 1 then return False
	for i = 2 to int(sqr(v))
		if v % i = 0 then return False
	next i
	return True
end function


#include <locale.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

bool is_prime(uint64_t n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (uint64_t p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

int main() {
    setlocale(LC_ALL, "");
    printf(" n          M(n)             Prime?\n");
    printf("-----------------------------------\n");
    uint64_t m0 = 1, m1 = 1;
    for (uint64_t i = 0; i < 42; ++i) {
        uint64_t m =
            i > 1 ? (m1 * (2 * i + 1) + m0 * (3 * i - 3)) / (i + 2) : 1;
        printf("%2llu%'25llu  %s\n", i, m, is_prime(m) ? "true" : "false");
        m0 = m1;
        m1 = m;
    }
}


using System;
using BI = System.Numerics.BigInteger;

class Program {

  // has multiple factors (other than 1 and x)
  static bool hmf(BI x) {
    if (x < 4) return x == 1;
    if ((x & 1) == 0 || x % 3 == 0) return true;
    int l = (int)Math.Sqrt((double)x); // this limit works because the 40th to 80th Motzkin numbers have factors of 2 or 3
    for (int j = 5, d = 4; j <= l; j += d = 6 - d)
      if (x % j == 0) return x > j;
    return false;
  }

  static void Main(string[] args) {
    BI a = 0, b = 1, t;
    int n = 1, s = 0, d = 1, c = 0, f = 1;
    while (n <= 80)
      Console.WriteLine("{0,46:n0} {1}",
        t = b / n++,
        hmf(t) ? "" : "is prime.",
        t = b,
        b = ((c += d * 3 + 3) * a +
             (f += d * 2 + 3) * b) /
             (s += d += 2),
        a = t);
  }
}


#include <cstdint>
#include <iomanip>
#include <iostream>

bool is_prime(uint64_t n) {
    if (n < 2)
        return false;
    if (n % 2 == 0)
        return n == 2;
    if (n % 3 == 0)
        return n == 3;
    for (uint64_t p = 5; p * p <= n; p += 4) {
        if (n % p == 0)
            return false;
        p += 2;
        if (n % p == 0)
            return false;
    }
    return true;
}

class motzkin_generator {
public:
    uint64_t next();
private:
    uint64_t n = 0;
    uint64_t m0 = 1;
    uint64_t m1 = 1;
};

uint64_t motzkin_generator::next() {
    uint64_t m = n > 1 ? (m1 * (2 * n + 1) + m0 * (3 * n - 3)) / (n + 2) : 1;
    ++n;
    m0 = m1;
    m1 = m;
    return m;
}

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << " n          M(n)             Prime?\n";
    std::cout << "-----------------------------------\n";
    std::cout << std::boolalpha;
    motzkin_generator mgen;
    for (int i = 0; i < 42; ++i) {
        uint64_t n = mgen.next();
        std::cout << std::setw(2) << i << std::setw(25) << n << "  "
                  << is_prime(n) << '\n';
    }
}


// Motzkin numbers. Nigel Galloway: September 10th., 2021
let M=let rec fN g=seq{yield List.item 1 g; yield! fN(0L::(g|>List.windowed 3|>List.map(List.sum))@[0L;0L])} in fN [0L;1L;0L;0L]
M|>Seq.take 42|>Seq.iter(printfn "%d")


USING: combinators formatting io kernel math math.primes
tools.memory.private ;

MEMO: motzkin ( m -- n )
    dup 2 < [
        drop 1
    ] [
        {
            [ 2 * 1 + ]
            [ 1 - motzkin * ]
            [ 3 * 3 - ]
            [ 2 - motzkin * + ]
            [ 2 + /i ]
        } cleave
    ] if ;

" n        motzkin(n)\n" print
42 [
    dup motzkin [ commas ] keep prime? "prime" "" ?
    "%2d %24s  %s\n" printf
] each-integer


Array m[42];
m[1]:=1;
m[2]:=2;
!!(1,0);             {precompute and print m[0] thru m[2]}
!!(1,0);
!!(2,1);
for n=3 to 41 do
    m[n]:=(m[n-1]*(2*n+1) + m[n-2]*(3*n-3))/(n+2);
    !!(m[n],Isprime(m[n]));
od;

;    {built-in Isprime function returns 0 for 1, 1 for primes, and}
;    {the smallest prime factor for composites, so this actually gives}
;    {slightly more information than requested}


#include "isprime.bas"

dim as ulongint M(0 to 41)
M(0) = 1 : M(1) = 1
print "1" : print "1"
for n as integer = 2 to 41
    M(n) = M(n-1)
    for i as uinteger = 0 to n-2
        M(n) += M(i)*M(n-2-i)
    next i
    print M(n),
    if isprime(M(n)) then print "is a prime" else print
next n


package main

import (
    "fmt"
    "rcu"
)

func motzkin(n int) []int {
    m := make([]int, n+1)
    m[0] = 1
    m[1] = 1
    for i := 2; i <= n; i++ {
        m[i] = (m[i-1]*(2*i+1) + m[i-2]*(3*i-3)) / (i + 2)
    }
    return m
}

func main() {
    fmt.Println(" n          M[n]             Prime?")
    fmt.Println("-----------------------------------")
    m := motzkin(41)
    for i, e := range m {
        fmt.Printf("%2d  %23s  %t\n", i, rcu.Commatize(e), rcu.IsPrime(e))
    }
}


import Control.Monad.Memo (Memo, memo, startEvalMemo)
import Math.NumberTheory.Primes.Testing (isPrime)
import System.Environment (getArgs)
import Text.Printf (printf)

type I = Integer

-- The n'th Motzkin number, where n is assumed to be ≥ 0.  We memoize the
-- computations using MonadMemo.
motzkin :: I -> Memo I I I
motzkin 0 = return 1
motzkin 1 = return 1
motzkin n = do
  m1 <- memo motzkin (n-1)
  m2 <- memo motzkin (n-2)
  return $ ((2*n+1)*m1 + (3*n-3)*m2) `div` (n+2)

-- The first n+1 Motzkin numbers, starting at 0.
motzkins :: I -> [I]
motzkins = startEvalMemo . mapM motzkin . enumFromTo 0

-- For i = 0 to n print i, the i'th Motzkin number, and if it's a prime number.
printMotzkins :: I -> IO ()
printMotzkins n = mapM_ prnt $ zip [0 :: I ..] (motzkins n)
  where prnt (i, m) = printf "%2d %20d %s\n" i m $ prime m
        prime m = if isPrime m then "prime" else ""

main :: IO ()
main = do
  [n] <- map read <$> getArgs
  printMotzkins n


using Primes

function motzkin(N)
    m = zeros(Int, N)
    m[1] = m[2] = 1
    for i in 3:N
        m[i] = (m[i - 1] * (2i - 1) + m[i - 2] * (3i - 6)) ÷ (i + 1)
    end
    return m
end

println(" n               M[n]     Prime?\n-----------------------------------")
for (i, m) in enumerate(motzkin(42))
    println(lpad(i - 1, 2), lpad(m, 20), lpad(isprime(m), 8))
end


import strformat, strutils

func isPrime(n: Positive): bool =
  if n == 1: return false
  if (n and 1) == 0: return n == 2
  if n mod 3 == 0: return n == 3
  var d = 5
  while d * d <= n:
    if n mod d == 0: return false
    inc d, 2
    if n mod d == 0: return false
    inc d, 4
  result = true

func motzkin(n: Positive): seq[int64] =
  result.setLen(n + 1)
  result[0] = 1
  result[1] = 1
  for i in 2..n:
    result[i] = (result[i-1] * (2 * i + 1) + result[i-2] * (3 * i - 3)) div (i + 2)

echo " n          M[n]             Prime?"
echo "-----------------------------------"
var m = motzkin(41)
for i, val in m:
  echo &"{i:2}  {insertSep($val):>23}  {val.isPrime}"


#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Motzkin_numbers
use warnings;
use ntheory qw( is_prime );

sub motzkin
  {
  my $N = shift;
  my @m = ( 0, 1, 1 );
  for my $i ( 3 .. $N )
    {
    $m[$i] = ($m[$i - 1] * (2 * $i - 1) + $m[$i - 2] * (3 * $i - 6)) / ($i + 1);
    }
  return splice @m, 1;
  }

print "  n          M[n]\n";
my $count = 0;
for ( motzkin(42) )
  {
  printf "%3d%25s  %s\n", $count++, s/\B(?=(\d\d\d)+$)/,/gr,
    is_prime($_) ? 'prime' : '';
  }


with javascript_semantics
include mpfr.e
function motzkin(integer n)
    sequence m = mpz_inits(2,1) -- {1,1}
    mpz m2 = mpz_init()         -- (scratch)
    for i=3 to n do
        mpz m1 = mpz_init()     -- (a new mpz rqd for every m[i])
        mpz_mul_si(m1,m[i-1],2*i-1)     -- (nb i is 1-based)
        mpz_mul_si(m2,m[i-2],3*i-6)     --        ""
        mpz_add(m1,m1,m2)
        assert(mpz_fdiv_q_ui(m1,m1,i+1)==0) -- (verify rmdr==0)
        m &= m1
    end for
    return m
end function

printf(1," n                     M[n]\n")
printf(1,"---------------------------\n")
sequence m = motzkin(42)
for i=1 to 42 do
    string mi = mpz_get_str(m[i],comma_fill:=true),
           pi = iff(mpz_prime(m[i])?"prime":"")
    printf(1,"%2d  %23s  %s\n", {i-1, mi, pi})
end for


  ' [ 1 1 ]
  41 times
    [ dup -2 split nip do
      i^ 2 + 2 * 1 - *
      swap i^ 2 + 3 * 6 - * +
      i^ 3 + / join ]
  behead drop
  witheach
    [ i^ echo sp dup echo isprime if [ say " prime" ] cr ]


use Lingua::EN::Numbers;

constant \C = 1, |[\×] (2, 6 … ∞) Z/ 2 .. *;

sub binomial { [×] ($^n … 0) Z/ 1 .. $^p }

my \𝐌 = 1, |(1..∞).map: -> \𝐧 { sum ^𝐧 .map( -> \𝐤 { C[𝐤] × binomial 𝐧, 2×𝐤 } ) };

say " 𝐧          𝐌[𝐧]            Prime?";
𝐌[^42].kv.map: { printf "%2d %24s  %s\n", $^k, $^v.&comma, $v.is-prime };


/*REXX program to display the first  N  Motzkin numbers,  and if that number is prime.  */
numeric digits 92                                /*max number of decimal digits for task*/
parse arg n .                                    /*obtain optional argument from the CL.*/
if n=='' | n==","  then n= 42                    /*Not specified?  Then use the default.*/
w= length(n) + 1;  wm= digits()%4                /*define maximum widths for two columns*/
say center('n', w     )   center("Motzkin[n]", wm)       center(' primality', 11)
say center('' , w, "─")   center(''          , wm, "─")  center('',           11, "─")
@.= 1                                            /*define default vale for the @. array.*/
      do m=0  for n                              /*step through indices for Motzkin #'s.*/
      if m>1  then @.m= (@(m-1)*(m+m+1) + @(m-2)*(m*3-3))%(m+2)  /*calculate a Motzkin #*/
      call show                                  /*display a Motzkin number ──► terminal*/
      end   /*m*/

say center('' , w, "─")   center(''          , wm, "─")  center('',           11, "─")
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
@:      parse arg i;          return @.i         /*return function expression based on I*/
commas: parse arg ?;  do jc=length(?)-3  to 1  by -3; ?=insert(',', ?, jc); end; return ?
prime:  if isPrime(@.m)  then return "   prime";                                 return ''
show:   y= commas(@.m);  say right(m, w)  right(y, max(wm, length(y)))  prime(); return
/*──────────────────────────────────────────────────────────────────────────────────────*/
isPrime: procedure expose p?. p#. p_.;  parse arg x     /*persistent P·· REXX variables.*/
         if symbol('P?.#')\=='VAR'  then         /*1st time here?   Then define primes. */
           do                                    /*L is a list of some low primes < 100.*/
           L= 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101
           p?.=0                                 /* [↓]  define P_index,  P,  P squared.*/
                  do i=1  for words(L);   _= word(L,i);   p?._= 1;   p#.i= _;   p_.i= _*_
                  end   /*i*/;                   p?.0= x2d(3632c8eb5af3b) /*bypass big ÷*/
           p?.n= _ + 4                           /*define next prime after last prime.  */
           p?.#= i - 1                           /*define the number of primes found.   */
           end                                   /* p?.  p#.  p_   must be unique.      */
         if x<p?.n  then return p?.x             /*special case, handle some low primes.*/
         if x==p?.0 then return 1                /*save a number of primality divisions.*/
         parse var  x   ''   -1   _              /*obtain right─most decimal digit of X.*/
         if    _==5  then return 0;  if x//2 ==0  then return 0   /*X ÷ by 5?  X ÷ by 2?*/
         if x//3==0  then return 0;  if x//7 ==0  then return 0   /*" "  " 3?  " "  " 7?*/
                                                 /*weed numbers that're ≥ 11 multiples. */
           do j=5  to p?.#  while p_.j<=x;  if x//p#.j ==0  then return 0
           end   /*j*/
                                                 /*weed numbers that're>high multiple Ps*/
           do k=p?.n  by 6  while k*k<=x;   if x//k    ==0  then return 0
                                            if x//(k+2)==0  then return 0
           end   /*k*/;           return 1       /*Passed all divisions?   It's a prime.*/


require "prime"

motzkin = Enumerator.new do |y|
  m = [1,1]
  m.each{|m| y << m }

  2.step do |i|
    m << (m.last*(2*i+1) + m[-2]*(3*i-3)) / (i+2)
    m.unshift # an arr with last 2 elements is sufficient
    y << m.last
  end
end

motzkin.take(42).each_with_index do |m, i|
  puts "#{'%2d' % i}: #{m}#{m.prime? ? ' prime' : ''}"
end


// [dependencies]
// primal = "0.3"
// num-format = "0.4"

fn motzkin(n: usize) -> Vec<usize> {
    let mut m = vec![0; n];
    m[0] = 1;
    m[1] = 1;
    for i in 2..n {
        m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2);
    }
    m
}

fn main() {
    use num_format::{Locale, ToFormattedString};
    let count = 42;
    let m = motzkin(count);
    println!(" n          M(n)             Prime?");
    println!("-----------------------------------");
    for i in 0..count {
        println!(
            "{:2}  {:>23}  {}",
            i,
            m[i].to_formatted_string(&Locale::en),
            primal::is_prime(m[i] as u64)
        );
    }
}


import Foundation

extension BinaryInteger {
  @inlinable
  public var isPrime: Bool {
    if self == 0 || self == 1 {
      return false
    } else if self == 2 {
      return true
    }

    let max = Self(ceil((Double(self).squareRoot())))

    for i in stride(from: 2, through: max, by: 1) where self % i == 0  {
      return false
    }

    return true
  }
}

func motzkin(_ n: Int) -> [Int] {
  var m = Array(repeating: 0, count: n)

  m[0] = 1
  m[1] = 1

  for i in 2..<n {
    m[i] = (m[i - 1] * (2 * i + 1) + m[i - 2] * (3 * i - 3)) / (i + 2)
  }

  return m
}

let m = motzkin(42)

for (i, n) in m.enumerated() {
  print("\(i): \(n) \(n.isPrime ? "prime" : "")")
}


import "/long" for ULong
import "/fmt" for Fmt

var motzkin = Fn.new { |n|
    var m = List.filled(n+1, 0)
    m[0] = ULong.one
    m[1] = ULong.one
    for (i in 2..n) {
        m[i] = (m[i-1] * (2*i + 1) + m[i-2] * (3*i -3))/(i + 2)
    }
    return m
}

System.print(" n          M[n]             Prime?")
System.print("-----------------------------------")
var m = motzkin.call(41)
for (i in 0..41) {
    Fmt.print("$2d  $,23i  $s", i, m[i], m[i].isPrime)
}


dim M(41)
M(0) = 1 : M(1) = 1
print str$(M(0), "%19g")
print str$(M(1), "%19g")
for n = 2 to 41
    M(n) = M(n-1)
    for i = 0 to n-2
        M(n) = M(n) + M(i)*M(n-2-i)
    next i
    print str$(M(n), "%19.0f"),
    if isPrime(M(n)) then print "is a prime" else print : fi
next n
end

sub isPrime(v)
    if v < 2 then return False : fi
    if mod(v, 2) = 0 then return v = 2 : fi
    if mod(v, 3) = 0 then return v = 3 : fi
    d = 5
    while d * d <= v
        if mod(v, d) = 0 then return False else d = d + 2 : fi
    wend
    return True
end sub


V symboltable = Array(‘a’..‘z’)

F move2front_encode(strng)
   [Int] sequence
   V pad = copy(:symboltable)
   L(char) strng
      V indx = pad.index(char)
      sequence.append(indx)
      pad = [pad.pop(indx)] [+] pad
   R sequence

F move2front_decode(sequence)
   [Char] chars
   V pad = copy(:symboltable)
   L(indx) sequence
      V char = pad[indx]
      chars.append(char)
      pad = [pad.pop(indx)] [+] pad
   R chars.join(‘’)

L(s) [‘broood’, ‘bananaaa’, ‘hiphophiphop’]
   V encode = move2front_encode(s)
   print(‘#14 encodes to #.’.format(s, encode), end' ‘, ’)
   V decode = move2front_decode(encode)
   print(‘which decodes back to #.’.format(decode))
   assert(s == decode, ‘Whoops!’)


DEFINE SYMBOL_TABLE_SIZE="26"

PROC InitSymbolTable(BYTE ARRAY table BYTE len)
  BYTE i

  FOR i=0 TO len-1
  DO
    table(i)=i+'a
  OD
RETURN

BYTE FUNC Find(BYTE ARRAY table BYTE len,c)
  BYTE i

  FOR i=0 TO len-1
  DO
    IF table(i)=c THEN
      RETURN (i)
    FI
  OD
  Break()
RETURN (0)

PROC MoveToFront(BYTE ARRAY table BYTE len,pos)
  BYTE sym

  sym=table(pos)
  WHILE pos>0
  DO
    table(pos)=table(pos-1)
    pos==-1
  OD
  table(pos)=sym
RETURN

PROC Encode(CHAR ARRAY in BYTE ARRAY out BYTE POINTER outLen)
  BYTE ARRAY table(SYMBOL_TABLE_SIZE)
  BYTE i,pos

  outLen^=0
  InitSymbolTable(table,SYMBOL_TABLE_SIZE)
  FOR i=1 TO in(0)
  DO
    pos=Find(table,SYMBOL_TABLE_SIZE,in(i))
    out(outLen^)=pos
    outLen^==+1
    MoveToFront(table,SYMBOL_TABLE_SIZE,pos)
  OD
RETURN

PROC Decode(BYTE ARRAY in BYTE inLen CHAR ARRAY out)
  BYTE ARRAY table(SYMBOL_TABLE_SIZE)
  BYTE i,pos,len

  len=0
  InitSymbolTable(table,SYMBOL_TABLE_SIZE)
  FOR i=0 TO inLen-1
  DO
    pos=in(i)
    len==+1
    out(len)=table(pos)
    MoveToFront(table,SYMBOL_TABLE_SIZE,pos)
  OD
  out(0)=len
RETURN

PROC Test(CHAR ARRAY s)
  BYTE ARRAY encoded(255)
  CHAR ARRAY decoded(256)
  BYTE encodedLength,i

  Print("Source:  ")
  PrintE(s)

  Encode(s,encoded,@encodedLength)
  Print("Encoded: ")
  FOR i=0 TO encodedLength-1
  DO
    PrintB(encoded(i)) Put(32)
  OD
  PutE()

  Decode(encoded,encodedLength,decoded)
  Print("Decoded: ")
  PrintE(decoded)
  IF SCompare(s,decoded)=0 THEN
    PrintE("Decoded is equal to the source.")
  ELSE
    PrintE("Decoded is different from the source!")
  FI
  PutE()
RETURN

PROC Main()
  Test("broood")
  Test("bananaaa")
  Test("hiphophiphop")
RETURN


with Ada.Text_IO;

procedure Move_To_Front is

   subtype Lower_Case is Character range 'a' .. 'z';
   subtype Index is Integer range 0 .. 25;
   type Table is array (Index) of Lower_Case;
   Alphabet: constant Table := "abcdefghijklmnopqrstuvwxyz";
   type Number_String is array(Positive range <>) of Natural;

   function Encode(S: String) return Number_String is
      Key: Table := Alphabet;

      function Encode(S: String; Tab: in out Table) return Number_String is

	 procedure Look_Up(A: in out Table; Ch: Lower_Case; Pos: out Index) is
	 begin
	    for I in A'Range loop
	       if A(I) = Ch then
		  Pos := I;
		  A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last);
		  return;
	       end if;
	    end loop;
	    raise Program_Error with "unknown character";
	 end Look_Up;

	 Empty: Number_String(1 .. 0);
	 Result: Natural;
      begin
	 if S'Length = 0 then
	    return Empty;
	 else
	    Look_Up(Tab, S(S'First), Result);
	    return Result & Encode(S(S'First+1 .. S'Last), Tab);
	 end if;
      end Encode;

   begin
      return Encode(S, Key);
   end Encode;

   function Decode(N: Number_String) return String is
      Key: Table := Alphabet;

      function Decode(N: Number_String; Tab: in out Table) return String is

	 procedure Look_Up(A: in out Table; Pos: Index; Ch: out Lower_Case) is
	 begin
	    Ch := A(Pos);
	    A := A(Pos) & A(A'First .. Pos-1) & A(Pos+1 .. A'Last);
	 end Look_Up;

	 Result: String(N'Range);
      begin
	 for I in N'Range loop
	    Look_Up(Tab, N(I), Result(I));
	 end loop;
	 return Result;
      end Decode;

   begin
      return Decode(N, Key);
   end Decode;

   procedure Encode_Write_Check(S: String) is
      N: Number_String := Encode(S);
      T: String := Decode(N);
      Check: String := (if S=T then "Correct!" else "*WRONG*!");
   begin
      Ada.Text_IO.Put("'" & S & "' encodes to");
      for Num of N loop
	 Ada.Text_IO.Put(Integer'Image(Num));
      end loop;
      Ada.Text_IO.Put_Line(". This decodes to '" & T & "'. " & Check);
   end Encode_Write_Check;

begin
   Encode_Write_Check("broood");
   Encode_Write_Check("bananaaa");
   Encode_Write_Check("hiphophiphop");
end Move_To_Front;


decode(list l)
{
    integer c, e;
    data al, s;

    al = "abcdefghijklmnopqrstuvwxyz";
    for (, e in l) {
        s.append(c = al[e]);
        al.delete(e).insert(0, c);
    }

    s;
}

encode(data s)
{
    integer c, e;
    data al;
    list l;

    al = "abcdefghijklmnopqrstuvwxyz";
    for (, c in s) {
        l.append(e = al.place(c));
        al.delete(e).insert(0, c);
    }

    l;
}

main(void)
{
    for (, text s in list("broood", "bananaaa", "hiphophiphop")) {
        list l;

        l = encode(s);
        l.ucall(o_, 1, " ");
        o_(": ", decode(l), "\n");
    }

    0;
}


# move the character at text pos to the front of text                         #
# note text pos is based from 0                                               #
PROC move to front = ( STRING text, INT text pos )STRING:
    IF text pos < 1
    THEN
        # the character is already at the front (or not in the string)        #
        text
    ELSE
        # the character isn't already at the front - construct the new string #

        INT    char pos = LWB text + text pos;

        ( text[ char pos     : char pos     ]
        + text[              : char pos - 1 ]
        + text[ char pos + 1 :              ]
        )

    FI;

# encode the string "text", using "initial table" as the starting symbol table#
PROC encode = ( STRING text, STRING initial table )[]INT:
BEGIN

    [ 1 : ( UPB text - LWB text ) + 1 ]INT result;

    STRING symbol table := initial table;

    FOR text pos FROM LWB text TO UPB text
    DO
        INT    symbol pos := 0;

        result[ text pos ]
            := IF char in string( text[ text pos ], symbol pos, symbol table )
               THEN
                   # the character is in the symbol table at symbol pos       #
                   # (indexed from LWB text) - we store the positions         #
                   # indexed from 0                                           #
                   symbol pos - LWB text
               ELSE
                   # the character isn't in the symbol table                  #
                   -1
               FI;

        # modify the symbol table so the latest character is at the front     #
        symbol table := move to front( symbol table, result[ text pos ] )

    OD;

    result
END; # encode #

# decode "encoded", using "initial table" as the starting symbol table        #
PROC decode = ( []INT encoded, STRING initial table )STRING:
BEGIN

    STRING result       := "";
    STRING symbol table := initial table;

    FOR text pos FROM LWB encoded TO UPB encoded
    DO
        result
           +:= IF encoded[ text pos ] < 0
               THEN
                   # the encoded character wasn't in the string               #
                   "?"
               ELSE
                  # the character is in the symbol table                      #
                  symbol table[ encoded[ text pos ] + LWB symbol table ]
                FI;

        # modify the symbol table so the latest character is at the front     #
        symbol table := move to front( symbol table, encoded[ text pos ] )

    OD;

    result
END; # decode #

# routine to test the encode and decode routines                              #
PROC test encode and decode = ( STRING text )VOID:
BEGIN

    # initial value for the symbol table                                      #
    []CHAR initial table = "abcdefghijklmnopqrstuvwxyz";

    # procedure to format the encoded value                                   #
    PROC format encoded value = ( []INT values )STRING:
    BEGIN
        STRING result := "";
        FOR value pos FROM LWB values TO UPB values
        DO
            result +:= ( " " + whole( values[ value pos ], 0 ) )
        OD;

        result
    END; # format encoded value #

    []INT  encoded = encode( text,    initial table );
    STRING decoded = decode( encoded, initial table );

    print( ( ( text
             + " encodes to ["
             + format encoded value( encoded )
             + " ] which "
             + IF text = decoded
               THEN
                   "correctly"
               ELSE
                   "INCORRECTLY"
               FI
             + " decodes to """
             + decoded
             + """"
             )
           , newline
           )
         )

END; # test encode and decode #

main: (

     test encode and decode( "broood" )
  ;  test encode and decode( "bananaaa" )
  ;  test encode and decode( "hiphophiphop" )

# ;  test encode and decode( "abcdefghijklmnopqrstuvwxyz" ) #
# ;  test encode and decode( "zyxwvutsrqponmlkjihgfedcba" ) #

)


MTF_Encode(string){
	str := "abcdefghijklmnopqrstuvwxyz"
	loop, parse, string
		code .= (A_Index>1 ? ",":"") . InStr(str, A_LoopField) - 1	, str := A_LoopField . StrReplace(str, A_LoopField)
	return code
}

MTF_Decode(code){
	str := "abcdefghijklmnopqrstuvwxyz"
	loop, parse, code, `,
		string .= (letter := SubStr(str, A_LoopField+1, 1)) 		, str := letter . StrReplace(str, letter)
	return string
}


  ( encode
  =   string symboltable
    .   !arg:(?string.?symboltable)
      &   vap
        $ ( (
            =   A Z i
              .   !symboltable:?A [?i !arg ?Z
                & !arg !A !Z:?symboltable
                & !i
            )
          . !string
          )
  )
& ( decode
  =   indices symboltable
    .   !arg:(?indices.?symboltable)
      &   str
        $ ( map
          $ ( (
              =   A Z symbol
                .   !symboltable:?A [!arg %?symbol ?Z
                  & !symbol !A !Z:?symboltable
                  & !symbol
              )
            . !indices
            )
          )
  )
& ( test
  =   string symboltable encoded decoded
    .   !arg:(?string.?symboltable)
      & put$str$("input:" !string ", ")
      & encode$(!string.!symboltable):?encoded
      & put$("encoded:" !encoded ", ")
      & decode$(!encoded.!symboltable):?decoded
      & put$str$("decoded:" !decoded ", ")
      & (   !string:!decoded
          & out$OK
        | out$WRONG
        )
  )
&   a b c d e f g h i j k l m n o p q r s t y v w x y z
  : ?symboltable
& test$(broood.!symboltable)
& test$(bananaaa.!symboltable)
& test$(hiphophiphop.!symboltable)


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

#define MAX_SIZE 100

int move_to_front(char *str,char c)
{
    char *q,*p;
    int shift=0;
    p=(char *)malloc(strlen(str)+1);
    strcpy(p,str);
    q=strchr(p,c); //returns pointer to location of char c in string str
    shift=q-p;      // no of characters from 0 to position of c in str
    strncpy(str+1,p,shift);
    str[0]=c;
    free(p);
  //  printf("\n%s\n",str);
    return shift;
}

void decode(int* pass,int size,char *sym)
{
    int i,index;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=table[pass[i]];
        index=move_to_front(table,c);
        if(pass[i]!=index) printf("there is an error");
        sym[i]=c;
    }
    sym[size]='\0';
}

void encode(char *sym,int size,int *pass)
{
    int i=0;
    char c;
    char table[]="abcdefghijklmnopqrstuvwxyz";
    for(i=0;i<size;i++)
    {
        c=sym[i];
        pass[i]=move_to_front(table,c);
    }
}

int check(char *sym,int size,int *pass)
{
    int *pass2=malloc(sizeof(int)*size);
    char *sym2=malloc(sizeof(char)*size);
    int i,val=1;

    encode(sym,size,pass2);
    i=0;
    while(i<size && pass[i]==pass2[i])i++;
    if(i!=size)val=0;

    decode(pass,size,sym2);
    if(strcmp(sym,sym2)!=0)val=0;

    free(sym2);
    free(pass2);

    return val;
}

int main()
{
    char sym[3][MAX_SIZE]={"broood","bananaaa","hiphophiphop"};
    int pass[MAX_SIZE]={0};
    int i,len,j;
    for(i=0;i<3;i++)
    {
        len=strlen(sym[i]);
        encode(sym[i],len,pass);
        printf("%s : [",sym[i]);
        for(j=0;j<len;j++)
            printf("%d ",pass[j]);
        printf("]\n");
        if(check(sym[i],len,pass))
            printf("Correct :)\n");
        else
            printf("Incorrect :(\n");
    }
    return 0;
}


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

namespace MoveToFront
{
    class Program
    {
        private static char[] symbolTable;
        private static void setSymbolTable()
        {
            symbolTable = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
        }

        private static void moveToFront(int charIndex)
        {
            char toFront = symbolTable[charIndex];
            for (int j = charIndex; j > 0; j--)
            {
                symbolTable[j] = symbolTable[j - 1];
            }
            symbolTable[0] = toFront;
        }

        public static int[] Encode(string input)
        {
            setSymbolTable();
            var output = new List<int>();
            foreach (char c in input)
            {
                for (int i = 0; i < 26; i++)
                {
                    if (symbolTable[i] == c)
                    {
                        output.Add(i);
                        moveToFront(i);
                        break;
                    }
                }
            }
            return output.ToArray();
        }

        public static string Decode(int[] input)
        {
            setSymbolTable();
            var output = new StringBuilder(input.Length);
            foreach (int n in input)
            {
                output.Append(symbolTable[n]);
                moveToFront(n);
            }
            return output.ToString();
        }

        static void Main(string[] args)
        {
            string[] testInputs = new string[] { "broood", "bananaaa", "hiphophiphop" };
            int[] encoding;
            foreach (string s in testInputs)
            {
                Console.WriteLine($"Encoding for '{s}':");
                encoding = Encode(s);
                foreach (int i in encoding)
                {
                    Console.Write($"{i} ");
                }
                Console.WriteLine($"\nDecoding for '{s}':");
                Console.WriteLine($"{Decode(encoding)}\n");
            }
        }
    }
}


#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

using namespace std;

class MTF
{
public:
    string encode( string str )
    {
	fillSymbolTable();
	vector<int> output;
	for( string::iterator it = str.begin(); it != str.end(); it++ )
	{
	    for( int i = 0; i < 26; i++ )
	    {
		if( *it == symbolTable[i] )
		{
		    output.push_back( i );
		    moveToFront( i );
		    break;
		}
	    }
	}
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    ostringstream ss;
	    ss << *it;
	    r += ss.str() + " ";
	}
	return r;
    }

    string decode( string str )
    {
	fillSymbolTable();
	istringstream iss( str ); vector<int> output;
	copy( istream_iterator<int>( iss ), istream_iterator<int>(), back_inserter<vector<int> >( output ) );
	string r;
	for( vector<int>::iterator it = output.begin(); it != output.end(); it++ )
	{
	    r.append( 1, symbolTable[*it] );
	    moveToFront( *it );
	}
	return r;
    }

private:
    void moveToFront( int i )
    {
	char t = symbolTable[i];
	for( int z = i - 1; z >= 0; z-- )
	    symbolTable[z + 1] = symbolTable[z];

        symbolTable[0] = t;
    }

    void fillSymbolTable()
    {
        for( int x = 0; x < 26; x++ )
	    symbolTable[x] = x + 'a';
    }

    char symbolTable[26];
};

int main()
{
    MTF mtf;
    string a, str[] = { "broood", "bananaaa", "hiphophiphop" };
    for( int x = 0; x < 3; x++ )
    {
        a = str[x];
        cout << a << " -> encoded = ";
        a = mtf.encode( a );
        cout << a << "; decoded = " << mtf.decode( a ) << endl;
    }
    return 0;
}


(def lowercase (map char (range (int \a) (inc (int \z)))))

(defn move-to-front [x xs]
  (cons x (remove #{x} xs)))

(defn encode [text table & {:keys [acc] :or {acc []}}]
  (let [c (first text)
        idx (.indexOf table c)]
    (if (empty? text) acc (recur (drop 1 text) (move-to-front c table) {:acc (conj acc idx)}))))

(defn decode [indices table & {:keys [acc] :or {acc []}}]
  (if (empty? indices) (apply str acc)
    (let [n (first indices)
          c (nth table n)]
      (recur (drop 1 indices) (move-to-front c table) {:acc (conj acc c)}))))

(doseq [word ["broood" "bananaaa" "hiphophiphop"]]
  (let [encoded (encode word lowercase)
        decoded (decode encoded lowercase)]
    (println (format "%s encodes to %s which decodes back to %s."
                   word encoded decoded))))


(defconstant +lower+ (coerce "abcdefghijklmnopqrstuvwxyz" 'list))

(defun move-to-front (x xs)
  (cons x (remove x xs)))

(defun enc (text table)
  (map 'list
       (lambda (c)
               (let ((idx (position c table)))
                 (setf table (move-to-front c table))
                 idx))
       text))

(defun dec (indices table)
    (coerce (mapcar (lambda (idx)
                      (let ((c (nth idx table)))
                        (setf table (move-to-front c table))
                        c))
                    indices)
            'string))

(loop for word in '("broood" "bananaaa" "hiphophiphop")
      do (let* ((encoded (enc word +lower+))
                (decoded (dec encoded +lower+)))
           (assert (string= word decoded))
           (format T "~s encodes to ~a which decodes back to ~s.~%"
                   word encoded decoded)))


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

ptrdiff_t[] mtfEncoder(in string data) pure nothrow @safe
in {
    assert(data.countchars("a-z") == data.length);
} out(result) {
    assert(result.length == data.length);
    assert(result.all!(e => e >= 0 && e < lowercase.length));
} body {
    ubyte[lowercase.length] order = lowercase.representation;
    auto encoded = new typeof(return)(data.length);

    size_t i = 0;
    foreach (immutable b; data) {
        immutable j = encoded[i++] = order[].countUntil(b);
        bringToFront(order[0 .. j], order[j .. j + 1]);
    }

    return encoded;
}

string mtfDecoder(in ptrdiff_t[] encoded) pure nothrow @safe
in {
    assert(encoded.all!(e => e >= 0 && e < lowercase.length));
} out(result) {
    assert(result.length == encoded.length);
    assert(result.countchars("a-z") == result.length);
} body {
    ubyte[lowercase.length] order = lowercase.representation;
    auto decoded = new char[encoded.length];

    size_t i = 0;
    foreach (immutable code; encoded) {
        decoded[i++] = order[code];
        bringToFront(order[0 .. code], order[code .. code + 1]);
    }

    return decoded;
}

void main() {
    foreach (immutable word; ["broood", "bananaaa", "hiphophiphop"]) {
        immutable encoded = word.mtfEncoder;
        immutable decoded = encoded.mtfDecoder;
        writefln("'%s' encodes to %s, which decodes back to '%s'",
                 word, encoded, decoded);
        assert(word == decoded);
    }
}


defmodule MoveToFront do
  @table  Enum.to_list(?a..?z)

  def encode(text), do: encode(to_char_list(text), @table, [])

  defp encode([], _, output), do: Enum.reverse(output)
  defp encode([h|t], table, output) do
    i = Enum.find_index(table, &(&1 == h))
    encode(t, move2front(table, i), [i | output])
  end

  def decode(indices), do: decode(indices, @table, [])

  defp decode([], _, output), do: Enum.reverse(output) |> to_string
  defp decode([h|t], table, output) do
    decode(t, move2front(table, h), [Enum.at(table, h) | output])
  end

  def move2front(table, i), do: [Enum.at(table,i) | List.delete_at(table, i)]
end

Enum.each(["broood", "bananaaa", "hiphophiphop"], fn word ->
  IO.inspect word
  IO.inspect enc = MoveToFront.encode(word)
  IO.puts "#{word == MoveToFront.decode(enc)}\n"
end)


// Move-to-front algorithm . Nigel Galloway: March 1st., 2021
let fN g=List.permute(fun n->match compare n g with 0->0 |1->n |_->n+1)
let decode n=let rec fG n g=[|match n with n::t->yield List.item n g; yield! fG t (fN n g)|_->()|] in fG n ['a'..'z']|>System.String
let encode n=let rec fG n g=[match n with n::t->let n=g|>List.findIndex((=)n) in yield n; yield! fG t (fN n g)|_->()]
             fG ((string n).ToCharArray()|>List.ofArray) ['a'..'z']
["broood";"bananaaa";"hiphophiphop"]|>List.iter(fun n->let i=encode n in let g=decode i in printfn "%s->%A->%s check=%A" n i g (n=g))


USING: formatting kernel locals make sequences ;

: to-front ( elt seq -- seq' ) over [ remove ] dip prefix ;

: encode ( symbols msg -- indices )
    [ [ swap 2dup index , to-front ] each ] { } make nip ;

: decode ( symbols indices -- msg )
    [ [ swap [ nth ] keep over , to-front ] each ] "" make nip ;

:: round-trip ( msg symbols -- )
    symbols msg encode :> encoded
    symbols encoded decode :> decoded
    msg decoded assert=
    msg encoded decoded "%s -> %u -> %s\n" printf ;

"broood" "bananaaa" "hiphophiphop"
[ "abcdefghijklmnopqrstuvwxyz" round-trip ] [email protected]


#define FAIL -1

sub mtf( s() as string, i as uinteger )
    'moves the symbol at index i to the front and shifts preceding ones back
    dim as string*1 t = s(i)
    for j as uinteger = i to 1 step -1
        s(j) = s(j-1)
    next j
    s(0)=t
end sub

sub make_symbols( s() as string )
    'populates an array of strings with the lowercase alphabet
    for i as uinteger = 97 to 122
        s(i-97) = chr(i)
    next i
end sub

function find( s() as string, l as string ) as integer
    'returns the index of the first occurrence of the symbol l in s()
    for i as uinteger = 0 to ubound(s)
        if s(i) = l then return i
    next i
    return FAIL
end function

sub encode( s() as string, ind() as uinteger )
    dim as integer n = ubound(s), i
    redim as uinteger ind(0 to n)
    dim as string a(0 to 25)
    make_symbols(a())
    for z as uinteger = 0 to n
        i = find( a(), s(z) )
        if i = FAIL then
            print "Uh oh! Couldn't find ";s(z);" in alphabet."
            end
        end if
        mtf( a(), i )
        ind(z) = i
    next z
end sub

sub decode( s() as string, ind() as uinteger )
    dim as integer n = ubound(ind), i
    redim as string s(0 to n)
    dim as string a(0 to 25)
    make_symbols(a())
    for z as uinteger = 0 to n
        s(z) = a(ind(z))
        mtf(a(), ind(z))
    next z
end sub

sub printarr( s() as string )
    for i as uinteger = 0 to ubound(s)
        print s(i);
    next i
    print
end sub

sub printind( ind() as integer )
    for i as uinteger = 0 to ubound(ind)
        print ind(i);" ";
    next i
    print
end sub

sub compose( s() as string, b as string )
    'turns a string into a zero-indexed array of single letters
    'The reason we use such arrays is to get them zero-indexed
    'and to make the point that we could work with multi-char
    'symbol tables if we wanted to
    dim as integer n = len(b), i
    redim as string s(0 to n-1)
    for i = 0 to n-1
        s(i) = mid(b, 1+i, 1)
    next i
end sub

'-----------now the tests-------------
redim as string s(0)
redim as integer ind(0)

compose( s(), "broood" )
encode( s(), ind() )
printind( ind() )
decode( s(), ind() )
printarr( s() ) : print

compose( s(), "bananaaa" )
encode( s(), ind() )
printind( ind() )
decode( s(), ind() )
printarr( s() ) : print

compose( s(), "hiphophiphop" )
encode( s(), ind() )
printind( ind() )
decode( s(), ind() )
printarr( s() )


Public Sub Main()
Dim sToCode As String[] = ["broood", "bananaaa", "hiphophiphop"]  'Samples to process
Dim sHold As New String[]                                         'To store results
Dim siCount, siCounter, siPos As Short                            'Various variables
Dim sOutput, sCode, sWork, sEach As String                        'Various variables

For siCounter = 0 To sToCode.Max                                  'To loop through each 'Sample'
  sCode = "abcdefghijklmnopqrstuvwxyz"                            'Set sCode to default setting
  For siCount = 1 To Len(sToCode[siCounter])                      'Loop through each letter in 'Sample'
    sWork = Mid(sToCode[siCounter], siCount, 1)                   'sWork to store the Letter
    siPos = InStr(scode, sWork) - 1                               'Find the position of the letter in sCode, -1 for '0' based array
    sOutput &= Str(siPos) & " "                                   'Add the postion to sOutput
    sCode = Mid(sCode, siPos + 1, 1) & Replace(sCode, sWork, "")  'sCode = the letter + the rest of sCode except the letter
  Next
  Print sToCode[siCounter] & " = " & sOutput                      'Print the 'Sample' and the coded version
  sHold.Add(Trim(sOutput))                                        'Add the code to the sHold array
  sOutput = ""                                                    'Clear sOutput
Next

Print                                                             'Print a blank line

For siCounter = 0 To sHold.Max                                    'To loop through each coded 'Sample'
  sCode = "abcdefghijklmnopqrstuvwxyz"                            'Set sCode to default setting
  For Each sEach In Split(sHold[siCounter], " ")                  'For each 'code' in coded 'Sample'
    sWork = Mid(sCode, Val(sEach) + 1, 1)                         'sWork = the decoded letter
    sOutput &= sWork                                              'Add the decoded letter to sOutput
    sCode = sWork & Replace(sCode, sWork, "")                     'sCode = the decoded letter + the rest of sCode except the letter
  Next
  Print sHold[siCounter] & " = " & sOutput                        'Print the coded and decoded result
  sOutput = ""                                                    'Clear sOutput
Next

End


package main

import (
	"bytes"
	"fmt"
)

type symbolTable string

func (symbols symbolTable) encode(s string) []byte {
	seq := make([]byte, len(s))
	pad := []byte(symbols)
	for i, c := range []byte(s) {
		x := bytes.IndexByte(pad, c)
		seq[i] = byte(x)
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return seq
}

func (symbols symbolTable) decode(seq []byte) string {
	chars := make([]byte, len(seq))
	pad := []byte(symbols)
	for i, x := range seq {
		c := pad[x]
		chars[i] = c
		copy(pad[1:], pad[:x])
		pad[0] = c
	}
	return string(chars)
}

func main() {
	m := symbolTable("abcdefghijklmnopqrstuvwxyz")
	for _, s := range []string{"broood", "bananaaa", "hiphophiphop"} {
		enc := m.encode(s)
		dec := m.decode(enc)
		fmt.Println(s, enc, dec)
		if dec != s {
			panic("Whoops!")
		}
	}
}


import Data.List (delete, elemIndex, mapAccumL)

import Data.Maybe (fromJust)

table :: String
table = ['a' .. 'z']

encode :: String -> [Int]
encode =
  let f t s = (s : delete s t, fromJust (elemIndex s t))
  in snd . mapAccumL f table

decode :: [Int] -> String
decode = snd . mapAccumL f table
  where
    f t i =
      let s = (t !! i)
      in (s : delete s t, s)

main :: IO ()
main =
  mapM_ print $
  (,) <*> uncurry ((==) . fst) <$> -- Test that ((fst . fst) x) == snd x)
  ((,) <*> (decode . snd) <$>
   ((,) <*> encode <$> ["broood", "bananaaa", "hiphophiphop"]))


procedure main(A)
    every writes(s := !A, " -> [") do {
        every writes(!(enc := encode(&lcase,s))," ")
        writes("] -> ",s2 := decode(&lcase,enc))
        write((s == s2, " (Correct)") | " (Incorrect)")
        }
end

procedure encode(m,s)
    enc := []
    every c := !s do {
        m ?:= reorder(tab(i := upto(c)),move(1),tab(0))
        put(enc,i-1)   # Strings are 1-based
        }
    return enc
end

procedure decode(m,enc)
    dec := ""
    every i := 1 + !enc do {	# Lists are 1-based
        dec ||:= m[i]
        m ?:= reorder(tab(i),move(1),tab(0))
        }
    return dec
end

procedure reorder(s1,s2,s3)
    return s2||s1||s3
end


spindizzy=:3 :0
  'seq table'=. y
  ndx=.$0
  orig=. table
  for_sym. seq do.
    ndx=.ndx,table i.sym
    table=. sym,table-.sym
  end.
  ndx
  assert. seq-:yzzidnips ndx;orig
)

yzzidnips=:3 :0
  'ndx table'=. y
  seq=.''
  for_n. ndx do.
    seq=.seq,sym=. n{table
    table=. sym,table-.sym
  end.
  seq
)


import java.util.LinkedList;
import java.util.List;

public class MTF{
	public static List<Integer> encode(String msg, String symTable){
		List<Integer> output = new LinkedList<Integer>();
		StringBuilder s = new StringBuilder(symTable);
		for(char c : msg.toCharArray()){
			int idx = s.indexOf("" + c);
			output.add(idx);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output;
	}

	public static String decode(List<Integer> idxs, String symTable){
		StringBuilder output = new StringBuilder();
		StringBuilder s = new StringBuilder(symTable);
		for(int idx : idxs){
			char c = s.charAt(idx);
			output = output.append(c);
			s = s.deleteCharAt(idx).insert(0, c);
		}
		return output.toString();
	}

	private static void test(String toEncode, String symTable){
		List<Integer> encoded = encode(toEncode, symTable);
		System.out.println(toEncode + ": " + encoded);
		String decoded = decode(encoded, symTable);
		System.out.println((toEncode.equals(decoded) ? "" : "in") + "correctly decoded to " + decoded);
	}

	public static void main(String[] args){
		String symTable = "abcdefghijklmnopqrstuvwxyz";
		test("broood", symTable);
		test("bananaaa", symTable);
		test("hiphophiphop", symTable);
	}
}


var encodeMTF = function (word) {
  var init = {wordAsNumbers: [], charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};

  return word.split('').reduce(function (acc, char) {
    var charNum = acc.charList.indexOf(char); //get index of char
    acc.wordAsNumbers.push(charNum); //add original index to acc
    acc.charList.unshift(acc.charList.splice(charNum, 1)[0]); //put at beginning of list
    return acc;
  }, init).wordAsNumbers; //return number list
};

var decodeMTF = function (numList) {
  var init = {word: '', charList: 'abcdefghijklmnopqrstuvwxyz'.split('')};

  return numList.reduce(function (acc, num) {
    acc.word += acc.charList[num];
    acc.charList.unshift(acc.charList.splice(num, 1)[0]); //put at beginning of list
    return acc;
  }, init).word;
};

//test our algorithms
var words = ['broood', 'bananaaa', 'hiphophiphop'];
var encoded = words.map(encodeMTF);
var decoded = encoded.map(decodeMTF);

//print results
console.log("from encoded:");
console.log(encoded);
console.log("from decoded:");
console.log(decoded);


# Input is the string to be encoded, st is the initial symbol table (an array)
# Output: the encoded string (an array)
def m2f_encode(st):
  reduce explode[] as $ch
    ( [ [], st];                  # state: [ans, st]
      (.[1]|index($ch)) as $ix
      | .[1] as $st
      | [ (.[0] + [ $ix ]),  [$st[$ix]] + $st[0:$ix] + $st[$ix+1:] ] )
  | .[0];

# Input should be the encoded string (an array)
# and st should be the initial symbol table (an array)
def m2f_decode(st):
  reduce .[] as $ix
    ( [ [], st];                  # state: [ans, st]
      .[1] as $st
      | [ (.[0] + [ $st[$ix] ]),  [$st[$ix]] + $st[0:$ix] + $st[$ix+1:] ] )
  | .[0]
  | implode;


function encodeMTF(str::AbstractString, symtable::Vector{Char}=collect('a':'z'))
    function encode(ch::Char)
        r = findfirst(symtable, ch)
        deleteat!(symtable, r)
        prepend!(symtable, ch)
        return r
    end
    collect(encode(ch) for ch in str)
end

function decodeMTF(arr::Vector{Int}, symtable::Vector{Char}=collect('a':'z'))
    function decode(i::Int)
        r = symtable[i]
        deleteat!(symtable, i)
        prepend!(symtable, r)
        return r
    end
    join(decode(i) for i in arr)
end

testset = ["broood", "bananaaa", "hiphophiphop"]
encoded = encodeMTF.(testset)
decoded = decodeMTF.(encoded)
for (str, enc, dec) in zip(testset, encoded, decoded)
    println("Test string: $str\n -> Encoded: $enc\n -> Decoded: $dec")
end

using Base.Test
@testset "Decoded string equal to original" begin
    for (str, dec) in zip(testset, decoded)
        @test str == dec
    end
end


// version 1.1.2

fun encode(s: String): IntArray {
    if (s.isEmpty()) return intArrayOf()
    val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
    val result = IntArray(s.length)
    for ((i, c) in s.withIndex()) {
        val index = symbols.indexOf(c)
        if (index == -1)
            throw IllegalArgumentException("$s contains a non-alphabetic character")
        result[i] = index
        if (index == 0) continue
        for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j]
        symbols[0] = c
    }
    return result
}

fun decode(a: IntArray): String {
    if (a.isEmpty()) return ""
    val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
    val result = CharArray(a.size)
    for ((i, n) in a.withIndex()) {
        if (n !in 0..25)
            throw IllegalArgumentException("${a.contentToString()} contains an invalid number")
        result[i] = symbols[n]
        if (n == 0) continue
        for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j]
        symbols[0] = result[i]
    }
    return result.joinToString("")
}

fun main(args: Array<String>) {
    val strings = arrayOf("broood", "bananaaa", "hiphophiphop")
    val encoded = Array<IntArray?>(strings.size) { null }
    for ((i, s) in strings.withIndex()) {
        encoded[i] = encode(s)
        println("${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}")
    }
    println()
    val decoded = Array<String?>(encoded.size) { null }
    for ((i, a) in encoded.withIndex()) {
        decoded[i] = decode(a!!)
        print("${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}")
        println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}")
    }
}


-- Return table of the alphabet in lower case
function getAlphabet ()
    local letters = {}
    for ascii = 97, 122 do table.insert(letters, string.char(ascii)) end
    return letters
end

-- Move the table value at ind to the front of tab
function moveToFront (tab, ind)
    local toMove = tab[ind]
    for i = ind - 1, 1, -1 do tab[i + 1] = tab[i] end
    tab[1] = toMove
end

-- Perform move-to-front encoding on input
function encode (input)
    local symbolTable, output, index = getAlphabet(), {}
    for pos = 1, #input do
        for k, v in pairs(symbolTable) do
            if v == input:sub(pos, pos) then index = k end
        end
        moveToFront(symbolTable, index)
        table.insert(output, index - 1)
    end
    return table.concat(output, " ")
end

-- Perform move-to-front decoding on input
function decode (input)
    local symbolTable, output = getAlphabet(), ""
    for num in input:gmatch("%d+") do
        output = output .. symbolTable[num + 1]
        moveToFront(symbolTable, num + 1)
    end
    return output
end

-- Main procedure
local testCases, output = {"broood", "bananaaa", "hiphophiphop"}
for _, case in pairs(testCases) do
    output = encode(case)
    print("Original string: " .. case)
    print("Encoded: " .. output)
    print("Decoded: " .. decode(output))
    print()
end


Module CheckIt {
      Global All$, nl$
      \\ upgrade to document
      Document All$
      Nl$<={
      }
      Function Encode$(Inp$) {
           Def SymbolTable$="abcdefghijklmnopqrstuvwxyz", Out$=""
            For i=1 to Len(Inp$)
                  c$=Mid$(Inp$, i, 1)
                  k=Instr(SymbolTable$, c$)
                  Insert k, 1 SymbolTable$=""
                  Out$=If$(Out$="" -> Quote$(k-1),Quote$(Param(Out$), k-1))
                  Insert 1 SymbolTable$=c$
                  \\ we use <= for globals
                  All$<=Format$("   {0} {1:30} {2}", c$, Out$, SymbolTable$)+nl$
            Next i
            =Out$
      }
      Function Decode$(Inp$) {
           Def SymbolTable$="abcdefghijklmnopqrstuvwxyz", Out$=""
           flush
           Data Param(Inp$)
           While not empty {
                  k=Number+1
                  c$=Mid$(SymbolTable$, k, 1)
                  Out$+=c$
                  Insert k, 1 SymbolTable$=""  ' erase at position k
                  Insert 1 SymbolTable$=c$
                  All$<=Format$("{0::-2} {1} {2:30} {3}", k-1, c$, Out$, SymbolTable$)+nl$
            }
            =Out$
      }
      TryThis("broood")
      TryThis("bananaaa")
      TryThis("hiphophiphop")
      ClipBoard All$
      Sub TryThis(a$)
            Local Out$=Encode$(a$)
            Local final$=Decode$(Out$)
            Print final$, final$=a$
      End Sub
}
CheckIt


mtf[word_]:=Module[{f,f2,p,q},
   f[{output_,symList_},next_]:=Module[{index},index=Position[symList,next][[1,1]]-1;
       {output~Append~index,Prepend[Delete[symList,index+1],next]}];
   p=Fold[f,{{},CharacterRange["a","z"]},Characters[ToString[word]]][[1]];
   f2[{output_,symList_},next_]:=Module[{index},index=symList[[next+1]];
       {output~Append~index,Prepend[DeleteCases[symList,ToString[index]],index]}];
   q=Fold[f2,{{},CharacterRange["a","z"]},p][[1]];
   Print["'", word,"' encodes to: ",p, " - "  ,p," decodes to: '",[email protected],"' - Input equals Output: " ,[email protected]];]


function testMTF
    symTable = 'abcdefghijklmnopqrstuvwxyz';
    inStr = {'broood' 'bananaaa' 'hiphophiphop'};
    for k = 1:length(inStr)
        outArr = encodeMTF(inStr{k}, symTable);
        outStr = decodeMTF(outArr, symTable);
        fprintf('%s: [ %s]\n', inStr{k}, sprintf('%d ', outArr))
        fprintf('%scorrectly decoded to %s\n', char('in'.*~strcmp(outStr, inStr{k})), outStr)
    end
end

function arr = encodeMTF(str, symTable)
    n = length(str);
    arr = zeros(1, n);
    for k = 1:n
        arr(k) = find(str(k) == symTable, 1);
        symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)];
    end
    arr = arr-1; % Change to zero-indexed array
end

function str = decodeMTF(arr, symTable)
    arr = arr+1; % Change to one-indexed array
    n = length(arr);
    str = char(zeros(1, n));
    for k = 1:n
        str(k) = symTable(arr(k));
        symTable = [symTable(arr(k)) symTable(1:arr(k)-1) symTable(arr(k)+1:end)];
    end
end


import algorithm, sequtils, strformat

const SymbolTable = toSeq('a'..'z')

func encode(s: string): seq[int] =
  var symtable: seq[char] = SymbolTable
  for c in s:
    let idx = symtable.find(c)
    result.add idx
    symtable.rotateLeft(0..idx, -1)

func decode(s: seq[int]): string =
  var symtable = SymbolTable
  for idx in s:
    result.add symtable[idx]
    symtable.rotateLeft(0..idx, -1)

for word in ["broood", "babanaaa", "hiphophiphop"]:
  let encoded = word.encode()
  let decoded = encoded.decode()
  let status = if decoded == word: "correctly" else: "incorrectly"
  echo &"'{word}' encodes to {encoded} which {status} decodes to '{decoded}'."


use strict;
use warnings;
sub encode {
	my ($str) = @_;
	my $table = join '', 'a' .. 'z';
	map {
		$table =~ s/(.*?)$_/$_$1/ or die;
		length($1);
	} split //, $str;
}

sub decode {
	my $table = join '', 'a' .. 'z';
	join "", map {
		$table =~ s/(.{$_})(.)/$2$1/ or die;
		$2;
	} @_;
}

for my $test ( qw(broood bananaaa hiphophiphop) ) {
	my @encoded = encode($test);
	print "$test: @encoded\n";
	my $decoded = decode(@encoded);
	print "in" x ( $decoded ne $test );
	print "correctly decoded to $decoded\n";
}


with javascript_semantics
function encode(string s)
    string symtab = "abcdefghijklmnopqrstuvwxyz"
    sequence res = {}
    for i=1 to length(s) do
        integer ch = s[i], k = find(ch,symtab)
        res &= k-1
--      for j=k to 2 by -1 do
--          symtab[j] = symtab[j-1]
--      end for
--      symtab[1] = ch
        symtab[1..k] = ch&symtab[1..k-1]
    end for
    return res
end function

function decode(sequence s)
    string symtab = "abcdefghijklmnopqrstuvwxyz"
    string res = ""
    for i=1 to length(s) do
        integer k = s[i]+1
        integer ch = symtab[k]
        res &= ch
--      for j=k to 2 by -1 do
--          symtab[j] = symtab[j-1]
--      end for
--      symtab[1] = ch
        symtab[1..k] = ch&symtab[1..k-1]
    end for
    return res
end function

procedure test(string s)
    sequence e = encode(s)
    string d = decode(e)
    ?{s,e,d,{"**ERROR**","ok"}[(s=d)+1]}
end procedure
test("broood")
test("bananaaa")
test("hiphophiphop")


<?php

function symbolTable() {
    $symbol = array();
    for ($c = ord('a') ; $c <= ord('z') ; $c++) {
        $symbol[$c - ord('a')] = chr($c);
    }
    return $symbol;
}

function mtfEncode($original, $symbol) {
    $encoded = array();
    for ($i = 0 ; $i < strlen($original) ; $i++) {
        $char = $original[$i];
        $position = array_search($char, $symbol);
        $encoded[] = $position;
        $mtf = $symbol[$position];
        unset($symbol[$position]);
        array_unshift($symbol, $mtf);
    }
    return $encoded;
}

function mtfDecode($encoded, $symbol) {
    $decoded = '';
    foreach ($encoded AS $position) {
        $char = $symbol[$position];
        $decoded .= $char;
        unset($symbol[$position]);
        array_unshift($symbol, $char);
    }
    return $decoded;
}

foreach (array('broood', 'bananaaa', 'hiphophiphop') AS $original) {
    $encoded = mtfEncode($original, symbolTable());
    $decoded = mtfDecode($encoded, symbolTable());
    echo
        $original,
        ' -> [', implode(',', $encoded), ']',
        ' -> ', $decoded,
        ' : ', ($original === $decoded ? 'OK' : 'Error'),
        PHP_EOL;
}


import util.

go =>
  Strings = ["broood", "bananaaa", "hiphophiphop"],
  foreach(String in Strings)
    check(String)
  end,
  nl.

% adjustments to 1-based index
encode(String) = [Pos,Table] =>
  Table = "abcdefghijklmnopqrstuvwxyz",
  Pos = [],
  Len = String.length,
  foreach({C,I} in zip(String,1..Len))
    Pos := Pos ++ [find_first_of(Table,C)-1],
    if Len > I then
       Table := [C] ++ delete(Table,C)
    end
  end.

decode(Pos) = String =>
  Table = "abcdefghijklmnopqrstuvwxyz",
  String = [],
  foreach(P in Pos)
    C = Table[P+1],
    Table := [C] ++ delete(Table,C),
    String := String ++ [C]
  end.

% Check the result
check(String) =>
   [Pos,Table] = encode(String),
   String2 = decode(Pos),
   if length(String) < 100 then
      println(pos=Pos),
      println(table=Table),
      println(string2=String2)
   else
      printf("String is too long to print (%d chars)\n", length(String))
   end,
   println(cond(String != String2, "not ", "") ++ "same"),
   nl.


(de encode (Str)
   (let Table (chop "abcdefghijklmnopqrstuvwxyz")
      (mapcar
         '((C)
            (dec
               (prog1
                  (index C Table)
                  (rot Table @) ) ) )
         (chop Str) ) ) )

(de decode (Lst)
   (let Table (chop "abcdefghijklmnopqrstuvwxyz")
      (pack
         (mapcar
            '((N)
               (prog1
                  (get Table (inc 'N))
                  (rot Table N) ) )
            Lst ) ) ) )


*process source attributes xref or(!);
 /*********************************************************************
 * 25.5.2014 Walter Pachl translated from REXX
 *********************************************************************/
 ed: Proc Options(main);
 Call enc_dec('broood');
 Call enc_dec('bananaaa');
 Call enc_dec('hiphophiphop');

 enc_dec: Proc(in);
 Dcl in  Char(*);
 Dcl out Char(20) Var Init('');
 Dcl st Char(26) Init('abcdefghijklmnopqrstuvwxyz');
 Dcl sta Char(26) Init((st));
 Dcl enc(20) Bin Fixed(31);
 Dcl encn Bin Fixed(31) Init(0);
 Dcl (i,p.k) Bin Fixed(31);
 Dcl c       Char(1);
 Do i=1 To length(in);
   c=substr(in,i,1);
   p=index(st,c);
   encn+=1;
   enc(encn)=p-1;
   st=c!!left(st,p-1)!!substr(st,p+1);
   End;
 Put Skip List(' in='!!in);
 Put Skip List('sta='!!sta!!' original symbol table');
 Put Skip Edit('enc=',(enc(i) do i=1 To encn))(a,20(F(3)));
 Put Skip List(' st='!!st!!' symbol table after encoding');
 Do i=1 To encn;
   k=enc(i)+1;
   out=out!!substr(sta,k,1);
   sta=substr(sta,k,1)!!left(sta,k-1)!!substr(sta,k+1);
   End;
 Put Skip List('out='!!out);
 Put Skip List(' ');
 If out=in Then;
 Else
   Put Skip List('all wrong!!');
 End;


Function Test-MTF
{
    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory=$true,Position=0)]
        [string]$word,

        [Parameter(Mandatory=$false)]
        [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
    )
    Begin
    {
        Function Encode
        {
            Param
            (
                [Parameter(Mandatory=$true,Position=0)]
                [string]$word,

                [Parameter(Mandatory=$false)]
                [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
            )
            foreach ($letter in $word.ToCharArray())
            {
                $index = $SymbolTable.IndexOf($letter)

                $prop = [ordered]@{
                    Input = $letter
                    Output = [int]$index
                    SymbolTable = $SymbolTable
                }
                New-Object PSobject -Property $prop
                $SymbolTable = $SymbolTable.Remove($index,1).Insert(0,$letter)
            }
        }
        Function Decode
        {
            Param
            (
                [Parameter(Mandatory=$true,Position=0)]
                [int[]]$index,

                [Parameter(Mandatory=$false)]
                [string]$SymbolTable = 'abcdefghijklmnopqrstuvwxyz'
            )
            foreach ($i in $index)
            {
                #Write-host $i -ForegroundColor Red
                $letter = $SymbolTable.Chars($i)

                $prop = [ordered]@{
                    Input = $i
                    Output = $letter
                    SymbolTable = $SymbolTable
                }
                New-Object PSObject -Property $prop
                $SymbolTable = $SymbolTable.Remove($i,1).Insert(0,$letter)
            }
        }
    }
    Process
    {
        #Encoding
        Write-Host "Encoding $word" -NoNewline
        $Encoded = (Encode -word $word).output
        Write-Host -NoNewline ": $($Encoded -join ',')"

        #Decoding
        Write-Host "`nDecoding $($Encoded -join ',')" -NoNewline
        $Decoded = (Decode -index $Encoded).output -join ''
        Write-Host -NoNewline ": $Decoded`n"
    }
    End{}
}


from __future__ import print_function
from string import ascii_lowercase

SYMBOLTABLE = list(ascii_lowercase)

def move2front_encode(strng, symboltable):
    sequence, pad = [], symboltable[::]
    for char in strng:
        indx = pad.index(char)
        sequence.append(indx)
        pad = [pad.pop(indx)] + pad
    return sequence

def move2front_decode(sequence, symboltable):
    chars, pad = [], symboltable[::]
    for indx in sequence:
        char = pad[indx]
        chars.append(char)
        pad = [pad.pop(indx)] + pad
    return ''.join(chars)

if __name__ == '__main__':
    for s in ['broood', 'bananaaa', 'hiphophiphop']:
        encode = move2front_encode(s, SYMBOLTABLE)
        print('%14r encodes to %r' % (s, encode), end=', ')
        decode = move2front_decode(encode, SYMBOLTABLE)
        print('which decodes back to %r' % decode)
        assert s == decode, 'Whoops!'


  [ []
    26 times
      [ char a i^ +
        join ] ] constant is symbols (   --> $ )

  [ [] symbols rot
    witheach
      [ over find
        tuck pluck
        swap join
        dip join ]
   drop ]                 is encode  ( $ --> [ )

 [ $ "" symbols rot
   witheach
     [ pluck
       dup rot join
       dip join ]
   drop ]                 is decode  ( [ --> $ )

 [ dup echo$
   say " --> "
   dup encode
   dup echo
   say " --> "
   decode
   dup echo$
   = iff
     [ say " :-)" ]
   else
     [ say " :-(" ]
   cr cr ]                is task    ( $ -->   )

  $ "broood bananaaa hiphophiphop"
  nest$ witheach task


#lang racket
(define default-symtab "abcdefghijklmnopqrstuvwxyz")

(define (move-to-front:encode in (symtab default-symtab))
  (define inner-encode
    (match-lambda**
     [((? string? (app string->list in)) st acc) ; make input all listy
      (inner-encode in st acc)]
     [(in (? string? (app string->list st)) acc) ; make symtab all listy
      (inner-encode in st acc)]
     [((list) _ (app reverse rv)) ; nothing more to encode
      rv]
     [((list a tail ...) (list left ... a right ...) acc) ; encode and recur
      (inner-encode tail `(,a ,@left ,@right) (cons (length left) acc))]))
  (inner-encode in symtab null))

(define (move-to-front:decode in (symtab default-symtab))
  (define inner-decode
    (match-lambda**
     [(in (? string? (app string->list st)) acc) ; make symtab all listy
      (inner-decode in st acc)]
     [((list) _ (app (compose list->string reverse) rv)) ; nothing more to encode
      rv]
     [((list a tail ...) symbols acc) ; decode and recur
      (match/values
       (split-at symbols a)
       [(l (cons ra rd))
        (inner-decode tail (cons ra (append l rd)) (cons ra acc))])]))
  (inner-decode in symtab null))

(module+ test
  ;; Test against the example in the task
  (require rackunit)
  (check-equal? (move-to-front:encode "broood") '(1 17 15 0 0 5))
  (check-equal? (move-to-front:decode '(1 17 15 0 0 5)) "broood")
  (check-equal? (move-to-front:decode (move-to-front:encode "broood")) "broood"))

(module+ main
  (define (encode+decode-string str)
    (define enc (move-to-front:encode str))
    (define dec (move-to-front:decode enc))
    (define crt (if (equal? dec str) "correctly" "incorrectly"))
    (printf "~s encodes to ~s, which decodes ~s to ~s.~%" str enc crt dec))

  (for-each encode+decode-string '("broood" "bananaaa" "hiphophiphop")))


sub encode ( Str $word ) {
    my @sym = 'a' .. 'z';
    gather for $word.comb -> $c {
	die "Symbol '$c' not found in @sym" if $c eq @sym.none;
        @sym[0 .. take (@sym ... $c).end] .= rotate(-1);
    }
}

sub decode ( @enc ) {
    my @sym = 'a' .. 'z';
    [~] gather for @enc -> $pos {
        take @sym[$pos];
        @sym[0..$pos] .= rotate(-1);
    }
}

use Test;
plan 3;
for <broood bananaaa hiphophiphop> -> $word {
    my $enc = encode($word);
    my $dec = decode($enc);
    is $word, $dec, "$word.fmt('%-12s') ($enc[])";
}


/* REXX ***************************************************************
* 25.05.2014 Walter Pachl
* REXX strings start with position 1
**********************************************************************/
Call enc_dec 'broood'
Call enc_dec 'bananaaa'
Call enc_dec 'hiphophiphop'
Exit
enc_dec: Procedure
Parse Arg in
st='abcdefghijklmnopqrstuvwxyz'
sta=st /* remember this for decoding */
enc=''
Do i=1 To length(in)
  c=substr(in,i,1)
  p=pos(c,st)
  enc=enc (p-1)
  st=c||left(st,p-1)substr(st,p+1)
  End
Say ' in='in
Say 'sta='sta 'original symbol table'
Say 'enc='enc
Say ' st='st  'symbol table after encoding'
out=''
Do i=1 To words(enc)
  k=word(enc,i)+1
  out=out||substr(sta,k,1)
  sta=substr(sta,k,1)left(sta,k-1)substr(sta,k+1)
  End
Say 'out='out
Say ' '
If out==in Then Nop
Else
  Say 'all wrong!!'
Return


# Project : Move-to-front algorithm

test("broood")
test("bananaaa")
test("hiphophiphop")

func encode(s)
        symtab = "abcdefghijklmnopqrstuvwxyz"
        res = ""
        for i=1 to len(s)
             ch = s[i]
             k = substr(symtab, ch)
             res = res + " " + (k-1)
             for j=k to 2 step -1
                  symtab[j] = symtab[j-1]
             next
             symtab[1] = ch
        next
        return res

func decode(s)
        s = str2list( substr(s, " ", nl) )
        symtab = "abcdefghijklmnopqrstuvwxyz"
        res = ""
        for i=1 to len(s)
             k = number(s[i]) + 1
             ch = symtab[k]
             res = res + " " + ch
             for j=k to 2 step -1
                   symtab[j] = symtab[j-1]
             next
             symtab[1] = ch
        next
        return right(res, len(res)-2)

func test(s)
        e = encode(s)
        d = decode(e)
        see "" + s + " => " + "(" + right(e, len(e) - 1) + ") " + " => " + substr(d, " ", "") + nl


module MoveToFront

  ABC = ("a".."z").to_a.freeze

  def self.encode(str)
    ar = ABC.dup
    str.chars.each_with_object([]) do |char, memo|
      memo << (i = ar.index(char))
      ar = m2f(ar,i)
    end
  end

  def self.decode(indices)
    ar = ABC.dup
    indices.each_with_object("") do |i, str|
      str << ar[i]
      ar = m2f(ar,i)
    end
  end

  private
  def self.m2f(ar,i)
    [ar.delete_at(i)] + ar
  end

end

['broood', 'bananaaa', 'hiphophiphop'].each do |word|
  p word == MoveToFront.decode(p MoveToFront.encode(p word))
end


fn main() {
    let examples = vec!["broood", "bananaaa", "hiphophiphop"];
    for example in examples {
        let encoded = encode(example);
        let decoded = decode(&encoded);
        println!(
            "{} encodes to {:?} decodes to {}",
            example, encoded, decoded
        );
    }
}

fn get_symbols() -> Vec<u8> {
    (b'a'..b'z').collect()
}

fn encode(input: &str) -> Vec<usize> {
    input
        .as_bytes()
        .iter()
        .fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
            let i = s.iter().position(|c| c == x).unwrap();
            let c = s.remove(i);
            s.insert(0, c);
            o.push(i);
            (o, s)
        })
        .0
}

fn decode(input: &[usize]) -> String {
    input
        .iter()
        .fold((Vec::new(), get_symbols()), |(mut o, mut s), x| {
            o.push(s[*x]);
            let c = s.remove(*x);
            s.insert(0, c);
            (o, s)
        })
        .0
        .into_iter()
        .map(|c| c as char)
        .collect()
}


package rosetta

import scala.annotation.tailrec

object MoveToFront {
  /**
   *  Default radix
   */
  private val R = 256

  /**
   *  Default symbol table
   */
  private def symbolTable = (0 until R).map(_.toChar).mkString

  /**
   *  Apply move-to-front encoding using default symbol table.
   */
  def encode(s: String): List[Int] = {
    encode(s, symbolTable)
  }

  /**
   *  Apply move-to-front encoding using symbol table <tt>symTable</tt>.
   */
  def encode(s: String, symTable: String): List[Int] = {
    val table = symTable.toCharArray

    @inline @tailrec def moveToFront(ch: Char, index: Int, tmpout: Char): Int = {
      val tmpin = table(index)
      table(index) = tmpout
      if (ch != tmpin)
        moveToFront(ch, index + 1, tmpin)
      else {
        table(0) = ch
        index
      }
    }

    @tailrec def encodeString(output: List[Int], s: List[Char]): List[Int] = s match {
      case Nil => output
      case x :: xs => {
        encodeString(moveToFront(x, 0, table(0)) :: output, s.tail)
      }
    }
    encodeString(Nil, s.toList).reverse
  }

  /**
   *  Apply move-to-front decoding using default symbol table.
   */
  def decode(ints: List[Int]): String = {
    decode(ints, symbolTable)
  }

  /**
   *  Apply move-to-front decoding using symbol table <tt>symTable</tt>.
   */
  def decode(lst: List[Int], symTable: String): String = {
    val table = symTable.toCharArray

    @inline def moveToFront(c: Char, index: Int) {
      for (i <- index-1 to 0 by -1)
        table(i+1) = table(i)
      table(0) = c
    }

    @tailrec def decodeList(output: List[Char], lst: List[Int]): List[Char] = lst match {
      case Nil => output
      case x :: xs => {
        val c = table(x)
        moveToFront(c, x)
        decodeList(c :: output, xs)
      }
    }
    decodeList(Nil, lst).reverse.mkString
  }

  def test(toEncode: String, symTable: String) {
		val encoded = encode(toEncode, symTable)
		println(toEncode + ": " + encoded)
		val decoded = decode(encoded, symTable)
		if (toEncode != decoded)
		  print("in")
		println("correctly decoded to " + decoded)
	}
}

/**
 * Unit tests the <tt>MoveToFront</tt> data type.
 */
object RosettaCodeMTF extends App {
	val symTable = "abcdefghijklmnopqrstuvwxyz"
	MoveToFront.test("broood", symTable)
	MoveToFront.test("bananaaa", symTable)
	MoveToFront.test("hiphophiphop", symTable)
}


func encode(str) {
    var table = ('a'..'z' -> join);
    str.chars.map { |c|
        var s = '';
        table.sub!(Regex('(.*?)' + c), {|s1| s=s1; c + s1});
        s.len;
    }
}

func decode(nums) {
    var table = ('a'..'z' -> join);
    nums.map { |n|
        var s = '';
        table.sub!(Regex('(.{' + n + '})(.)'), {|s1, s2| s=s2; s2 + s1});
        s;
    }.join;
}

%w(broood bananaaa hiphophiphop).each { |test|
    var encoded = encode(test);
    say "#{test}: #{encoded}";
    var decoded = decode(encoded);
    print "in" if (decoded != test);
    say "correctly decoded to #{decoded}";
}


var str="broood"
var number:[Int]=[1,17,15,0,0,5]

//function to encode the string
func encode(st:String)->[Int]
{

var array:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

	var num:[Int]=[]
	var temp:Character="a"
	var i1:Int=0
	for i in st.characters
	{
		for j in 0...25
		{
			if i==array[j]
			{
				num.append(j)
				temp=array[j]
				i1=j
				while(i1>0)
				{
					array[i1]=array[i1-1]
					i1=i1-1

				}
				array[0]=temp
			}

		}

	}

	return num

}

func decode(s:[Int])->[Character]
{

	var st1:[Character]=[]
	var alph:[Character]=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
	var temp1:Character="a"
	var i2:Int=0
	for i in 0...s.character.count-1
	{
		i2=s[i]
		st1.append(alph[i2])
		temp1=alph[i2]

				while(i2>0)
				{
					alph[i2]=alph[i2-1]
					i2=i2-1

				}
				alph[0]=temp1

	}
	return st1

}

var encarr:[Int]=encode(st:str)
var decarr:[Character]=decode(s:number)
print(encarr)
print(decarr)