package require Tcl 8.6

oo::class create MoveToFront {
    variable symbolTable
    constructor {symbols} {
	set symbolTable [split $symbols ""]
    }

    method MoveToFront {table index} {
	list [lindex $table $index] {*}[lreplace $table $index $index]
    }
    method encode {text} {
	set t $symbolTable
	set r {}
	foreach c [split $text ""] {
	    set i [lsearch -exact $t $c]
	    lappend r $i
	    set t [my MoveToFront $t $i]
	}
	return $r
    }
    method decode {numbers} {
	set t $symbolTable
	set r ""
	foreach n $numbers {
	    append r [lindex $t $n]
	    set t [my MoveToFront $t $n]
	}
	return $r
    }
}

MoveToFront create mtf "abcdefghijklmnopqrstuvwxyz"
foreach tester {"broood" "bananaaa" "hiphophiphop"} {
    set enc [mtf encode $tester]
    set dec [mtf decode $enc]
    puts [format "'%s' encodes to %s. This decodes to '%s'. %s" \
	    $tester $enc $dec [expr {$tester eq $dec ? "Correct!" : "WRONG!"}]]
}


Function mtf_encode(s)
	'create the array list and populate it with the initial symbol position
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 'a to z in decimal.
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 1 To Len(s)
		char = Mid(s,i,1)
		If i = Len(s) Then
			output = output & symbol_table.IndexOf(char,0)
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		Else
			output = output & symbol_table.IndexOf(char,0) & " "
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_encode = output
End Function

Function mtf_decode(s)
	'break the function argument into an array
	code = Split(s," ")
	'create the array list and populate it with the initial symbol position
	Set symbol_table = CreateObject("System.Collections.ArrayList")
	For j = 97 To 122 'a to z in decimal.
		symbol_table.Add Chr(j)
	Next
	output = ""
	For i = 0 To UBound(code)
		char = symbol_table(code(i))
		output = output & char
		If code(i) <> 0 Then
			symbol_table.RemoveAt(symbol_table.LastIndexOf(char))
			symbol_table.Insert 0,char
		End If
	Next
	mtf_decode = output
End Function

'Testing the functions
wordlist = Array("broood","bananaaa","hiphophiphop")
For Each word In wordlist
	WScript.StdOut.Write word & " encodes as " & mtf_encode(word) & " and decodes as " &_
		mtf_decode(mtf_encode(word)) & "."
	WScript.StdOut.WriteBlankLines(1)
Next


import "/fmt" for Fmt
import "/seq" for Lst

var encode = Fn.new { |s|
    if (s.isEmpty) return []
    var symbols = "abcdefghijklmnopqrstuvwxyz".toList
    var result = List.filled(s.count, 0)
    var i = 0
    for (c in s) {
        var index = Lst.indexOf(symbols, c)
        if (index == -1) Fiber.abort("%(s) contains a non-alphabetic character")
        result[i] = index
        if (index > 0) {
            for (j in index-1..0) symbols[j + 1] = symbols[j]
            symbols[0] = c
        }
        i = i + 1
    }
    return result
}

var decode = Fn.new { |a|
    if (a.isEmpty) return ""
    var symbols = "abcdefghijklmnopqrstuvwxyz".toList
    var result = List.filled(a.count, "")
    var i = 0
    for (n in a) {
        if (n < 0 || n > 25) Fiber.abort("%(a) contains an invalid number")
        result[i] = symbols[n]
        if (n > 0) {
            for (j in n-1..0) symbols[j + 1] = symbols[j]
            symbols[0] = result[i]
        }
        i = i + 1
    }
    return result.join()
}

var strings = ["broood", "bananaaa", "hiphophiphop"]
var encoded = List.filled(strings.count, null)
var i = 0
for (s in strings) {
    encoded[i] = encode.call(s)
    Fmt.print("$-12s -> $n", s, encoded[i])
    i = i + 1
}
System.print()
var decoded = List.filled(encoded.count, null)
i = 0
for (a in encoded) {
    decoded[i] = decode.call(a)
    var correct = (decoded[i] == strings[i]) ? "correct" : "incorrect"
    Fmt.print("$-38n -> $-12s -> $s", a, decoded[i], correct)
    i = i + 1
}


fcn encode(text){ //-->List
   st:=["a".."z"].pump(Data);	//"abcd..z" as byte array
   text.reduce(fcn(st,c,sink){
      n:=st.index(c); sink.write(n); st.del(n).insert(0,c); },st,sink:=L());
   sink;
}


BEGIN
    MODE MWRITER = STRUCT( LONG REAL value
                         , STRING    log
                         );
    PRIO BIND = 9;
    OP   BIND = ( MWRITER m, PROC( LONG REAL )MWRITER f )MWRITER:
    (    MWRITER n := f( value OF m );
         log OF n  := log OF m + log OF n;
         n
    );

    OP   LEN     = ( STRING s )INT: ( UPB s + 1 ) - LWB s;
    PRIO PAD     = 9;
    OP   PAD     = ( STRING s, INT width )STRING: IF LEN s >= width THEN s ELSE s + ( width - LEN s ) * " " FI;

    PROC unit    = ( LONG REAL v, STRING s )MWRITER: ( v, "  " + s PAD 17 + ":" + fixed( v, -19, 15 ) + REPR 10 );

    PROC root    = ( LONG REAL v )MWRITER: unit( long sqrt( v ), "Took square root" );
    PROC add one = ( LONG REAL v )MWRITER: unit( v+1, "Added one" );
    PROC half    = ( LONG REAL v )MWRITER: unit( v/2, "Divided by two" );

    MWRITER mw2 := unit( 5, "Initial value" ) BIND root BIND add one BIND half;
    print( ( "The Golden Ratio is", fixed( value OF mw2, -19, 15 ), newline ) );
    print( ( newline, "This was derived as follows:-", newline ) );
    print( ( log OF mw2 ) )
END


-- WRITER MONAD FOR APPLESCRIPT

-- How can we compose functions which take simple values as arguments
-- but return an output value which is paired with a log string ?

-- We can prevent functions which expect simple values from choking
-- on log-wrapped output (from nested functions)
-- by writing Unit/Return() and Bind() for the Writer monad in AppleScript

on run {}

    -- Derive logging versions of three simple functions, pairing
    -- each function with a particular comment string

    -- (a -> b) -> (a -> (b, String))
    set wRoot to writerVersion(root, "obtained square root")
    set wSucc to writerVersion(succ, "added one")
    set wHalf to writerVersion(half, "divided by two")

    loggingHalfOfRootPlusOne(5)

    --> value + log string
end run

-- THREE SIMPLE FUNCTIONS
on root(x)
    x ^ (1 / 2)
end root

on succ(x)
    x + 1
end succ

on half(x)
    x / 2
end half

-- DERIVE A LOGGING VERSION OF A FUNCTION  BY COMBINING IT WITH A
-- LOG STRING FOR THAT FUNCTION
-- (SEE 'on run()' handler at top of script)
-- (a -> b) -> String -> (a -> (b, String))
on writerVersion(f, strComment)
    script
        on call(x)
            {value:sReturn(f)'s call(x), comment:strComment}
        end call
    end script
end writerVersion

-- DEFINE A COMPOSITION OF THE SAFE VERSIONS
on loggingHalfOfRootPlusOne(x)
    logCompose([my wHalf, my wSucc, my wRoot], x)
end loggingHalfOfRootPlusOne

-- Monadic UNIT/RETURN and BIND functions for the writer monad
on writerUnit(a)
    try
        set strValue to ": " & a as string
    on error
        set strValue to ""
    end try
    {value:a, comment:"Initial value" & strValue}
end writerUnit

on writerBind(recWriter, wf)
    set recB to wf's call(value of recWriter)
    set v to value of recB

    try
        set strV to " -> " & (v as string)
    on error
        set strV to ""
    end try

    {value:v, comment:(comment of recWriter) & linefeed & (comment of recB) & strV}
end writerBind

-- THE TWO HIGHER ORDER FUNCTIONS ABOVE ENABLE COMPOSITION OF
-- THE LOGGING VERSIONS OF EACH FUNCTION
on logCompose(lstFunctions, varValue)
    reduceRight(lstFunctions, writerBind, writerUnit(varValue))
end logCompose

-- xs: list, f: function, a: initial accumulator value
-- the arguments available to the function f(a, x, i, l) are
-- v: current accumulator value
-- x: current item in list
-- i: [ 1-based index in list ] optional
-- l: [ a reference to the list itself ] optional
on reduceRight(xs, f, a)
    set sf to sReturn(f)

    repeat with i from length of xs to 1 by -1
        set a to sf's call(a, item i of xs, i, xs)
    end repeat
end reduceRight

-- Unit/Return and bind for composing handlers in script wrappers
-- lift 2nd class function into 1st class wrapper
-- handler function --> first class script object
on sReturn(f)
    script
        property call : f
    end script
end sReturn

-- return a new script in which function g is composed
-- with the f (call()) of the Mf script
-- Mf -> (f -> Mg) -> Mg
on sBind(mf, g)
    script
        on call(x)
            sReturn(g)'s call(mf's call(x))
        end call
    end script
end sBind


#include <cmath>
#include <iostream>
#include <string>

using namespace std;

// Use a struct as the monad
struct LoggingMonad
{
    double Value;
    string Log;
};

// Use the >> operator as the bind function
auto operator>>(const LoggingMonad& monad, auto f)
{
    auto result = f(monad.Value);
    return LoggingMonad{result.Value, monad.Log + "\n" + result.Log};
}

// Define the three simple functions
auto Root = [](double x){ return sqrt(x); };
auto AddOne = [](double x){ return x + 1; };
auto Half = [](double x){ return x / 2.0; };

// Define a function to create writer monads from the simple functions
auto MakeWriter = [](auto f, string message)
{
    return [=](double x){return LoggingMonad(f(x), message);};
};

// Derive writer versions of the simple functions
auto writerRoot = MakeWriter(Root, "Taking square root");
auto writerAddOne = MakeWriter(AddOne, "Adding 1");
auto writerHalf = MakeWriter(Half, "Dividing by 2");

int main()
{
    // Compose the writers to compute the golden ratio
    auto result = LoggingMonad{5, "Starting with 5"} >> writerRoot >> writerAddOne >> writerHalf;
    cout << result.Log << "\nResult: " << result.Value;
}


(define (Writer.unit x (log #f))
	(if log (cons log x)
		(cons (format "init → %d" x) x)))

;; f is a lisp function
;; (Writer.lift f) returns a  Writer function which returns a Writer element

(define (Writer.lift f name)
	(lambda(elem)
             (Writer.unit
             	(f (rest elem))
                (format "%a \n %a  → %a" (first elem) name (f (rest elem))))))

;; lifts and applies
(define (Writer.bind f elem) ((Writer.lift f (string f)) elem))

(define (Writer.print elem) (writeln 'result (rest elem)) (writeln (first elem)))

;; Writer monad versions
(define w-root  (Writer.lift sqrt "root"))
(define w-half  (Writer.lift (lambda(x) (// x 2)) "half"))
(define w-inc  ( Writer.lift add1 "add-one"))

;; no binding required, as we use Writer lifted functions
(->  5 Writer.unit w-root w-inc w-half Writer.print)

result 1.618033988749895
init → 5
root → 2.23606797749979
add-one → 3.23606797749979
half → 1.618033988749895

;; binding
(->>  0 Writer.unit (Writer.bind sin) (Writer.bind cos)  w-inc w-half Writer.print)

result 1
init → 0
sin → 0
cos → 1
add-one → 2
half → 1


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

{
    [ 5 "Started with five, " <writer> ]
    [ sqrt "took square root, " <writer> ]
    [ 1 + "added one, " <writer> ]
    [ 2 / "divided by two." <writer> ]
} do .


package main

import (
    "fmt"
    "math"
)

type mwriter struct {
    value float64
    log   string
}

func (m mwriter) bind(f func(v float64) mwriter) mwriter {
    n := f(m.value)
    n.log = m.log + n.log
    return n
}

func unit(v float64, s string) mwriter {
    return mwriter{v, fmt.Sprintf("  %-17s: %g\n", s, v)}
}

func root(v float64) mwriter {
    return unit(math.Sqrt(v), "Took square root")
}

func addOne(v float64) mwriter {
    return unit(v+1, "Added one")
}

func half(v float64) mwriter {
    return unit(v/2, "Divided by two")
}

func main() {
    mw1 := unit(5, "Initial value")
    mw2 := mw1.bind(root).bind(addOne).bind(half)
    fmt.Println("The Golden Ratio is", mw2.value)
    fmt.Println("\nThis was derived as follows:-")
    fmt.Println(mw2.log)
}


import Control.Monad.Trans.Writer
import Control.Monad ((>=>))

loggingVersion :: (a -> b) -> c -> a -> Writer c b
loggingVersion f log x = writer (f x, log)

logRoot = loggingVersion sqrt "obtained square root, "
logAddOne = loggingVersion (+1) "added 1, "
logHalf = loggingVersion (/2) "divided by 2, "

halfOfAddOneOfRoot = logRoot >=> logAddOne >=> logHalf

main = print $ runWriter (halfOfAddOneOfRoot 5)


root=: %:
incr=: >:
half=: -:

tostr=: ,@":

loggingVersion=: conjunction define
  n;~u
)

Lroot=: root loggingVersion 'obtained square root'
Lincr=: incr loggingVersion 'added 1'
Lhalf=: half loggingVersion 'divided by 2'

loggingUnit=: verb define
  y;'Initial value: ',tostr y
)

loggingBind=: adverb define
  r=. u 0{::y
  v=. 0{:: r
  v;(1{::y),LF,(1{::r),' -> ',tostr v
)

loggingCompose=: dyad define
  ;(dyad def '<x`:6 loggingBind;y')/x,<loggingUnit y
)


(function () {
    'use strict';

    // START WITH THREE SIMPLE FUNCTIONS

    // Square root of a number more than 0
    function root(x) {
        return Math.sqrt(x);
    }

    // Add 1
    function addOne(x) {
        return x + 1;
    }

    // Divide by 2
    function half(x) {
        return x / 2;
    }

    // DERIVE LOGGING VERSIONS OF EACH FUNCTION

    function loggingVersion(f, strLog) {
        return function (v) {
            return {
                value: f(v),
                log: strLog
            };
        }
    }

    var log_root = loggingVersion(root, "obtained square root"),

        log_addOne = loggingVersion(addOne, "added 1"),

        log_half = loggingVersion(half, "divided by 2");

    // UNIT/RETURN and BIND for the the WRITER MONAD

    // The Unit / Return function for the Writer monad:
    // 'Lifts' a raw value into the wrapped form
    // a -> Writer a
    function writerUnit(a) {
        return {
            value: a,
            log: "Initial value: " + JSON.stringify(a)
        };
    }

    // The Bind function for the Writer monad:
    // applies a logging version of a function
    // to the contents of a wrapped value
    // and return a wrapped result (with extended log)

    // Writer a -> (a -> Writer b) -> Writer b
    function writerBind(w, f) {
        var writerB = f(w.value),
            v = writerB.value;

        return {
            value: v,
            log: w.log + '\n' + writerB.log + ' -> ' + JSON.stringify(v)
        };
    }

    // USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS

    // We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight
    // which starts by 'lifting' the initial value into a Writer wrapping,
    // and then nests function applications (working from right to left)
    function logCompose(lstFunctions, value) {
        return lstFunctions.reduceRight(
            writerBind,
            writerUnit(value)
        );
    }

    var half_of_addOne_of_root = function (v) {
        return logCompose(
            [log_half, log_addOne, log_root], v
        );
    };

    return half_of_addOne_of_root(5);
})();


'use strict';

/* writer monad, in Jsish */
function writerMonad() {

    // START WITH THREE SIMPLE FUNCTIONS

    // Square root of a number more than 0
    function root(x) {
        return Math.sqrt(x);
    }

    // Add 1
    function addOne(x) {
        return x + 1;
    }

    // Divide by 2
    function half(x) {
        return x / 2;
    }

    // DERIVE LOGGING VERSIONS OF EACH FUNCTION

    function loggingVersion(f, strLog) {
        return function (v) {
            return {
                value: f(v),
                log: strLog
            };
        };
    }

    var log_root = loggingVersion(root, "obtained square root"),

        log_addOne = loggingVersion(addOne, "added 1"),

        log_half = loggingVersion(half, "divided by 2");

    // UNIT/RETURN and BIND for the the WRITER MONAD

    // The Unit / Return function for the Writer monad:
    // 'Lifts' a raw value into the wrapped form
    // a -> Writer a
    function writerUnit(a) {
        return {
            value: a,
            log: "Initial value: " + JSON.stringify(a)
        };
    }

    // The Bind function for the Writer monad:
    // applies a logging version of a function
    // to the contents of a wrapped value
    // and return a wrapped result (with extended log)

    // Writer a -> (a -> Writer b) -> Writer b
    function writerBind(w, f) {
        var writerB = f(w.value),
            v = writerB.value;

        return {
            value: v,
            log: w.log + '\n' + writerB.log + ' -> ' + JSON.stringify(v)
        };
    }

    // USING UNIT AND BIND TO COMPOSE LOGGING FUNCTIONS

    // We can compose a chain of Writer functions (of any length) with a simple foldr/reduceRight
    // which starts by 'lifting' the initial value into a Writer wrapping,
    // and then nests function applications (working from right to left)
    function logCompose(lstFunctions, value) {
        return lstFunctions.reduceRight(
            writerBind,
            writerUnit(value)
        );
    }

    var half_of_addOne_of_root = function (v) {
        return logCompose(
            [log_half, log_addOne, log_root], v
        );
    };

    return half_of_addOne_of_root(5);
}

var writer = writerMonad();
;writer.value;
;writer.log;

/*
=!EXPECTSTART!=
writer.value ==> 1.61803398874989
writer.log ==> Initial value: 5
obtained square root -> 2.23606797749979
added 1 -> 3.23606797749979
divided by 2 -> 1.61803398874989
=!EXPECTEND!=
*/


struct Writer x::Real; msg::String; end

Base.show(io::IO, w::Writer) = print(io, w.msg, ": ", w.x)

unit(x, logmsg) = Writer(x, logmsg)

bind(f, fmsg, w) = unit(f(w.x), w.msg * ", " * fmsg)

f1(x) = 7x
f2(x) = x + 8

a = unit(3, "after intialization")
b = bind(f1, "after times 7 ", a)
c = bind(f2, "after plus 8", b)

println("$a => $b => $c")
println(bind(f2, "after plus 8", bind(f1, "after times 7", unit(3, "after intialization"))))


// version 1.2.10

import kotlin.math.sqrt

class Writer<T : Any> private constructor(val value: T, s: String) {
    var log = "  ${s.padEnd(17)}: $value\n"
        private set

    fun bind(f: (T) -> Writer<T>): Writer<T> {
        val new = f(this.value)
        new.log = this.log + new.log
        return new
    }

    companion object {
        fun <T : Any> unit(t: T, s: String) = Writer<T>(t, s)
    }
}

fun root(d: Double) = Writer.unit(sqrt(d), "Took square root")

fun addOne(d: Double) = Writer.unit(d + 1.0, "Added one")

fun half(d: Double) = Writer.unit(d / 2.0, "Divided by two")

fun main(args: Array<String>) {
    val iv = Writer.unit(5.0, "Initial value")
    val fv = iv.bind(::root).bind(::addOne).bind(::half)
    println("The Golden Ratio is ${fv.value}")
    println("\nThis was derived as follows:-\n${fv.log}")
}


from math import sqrt
from sugar import `=>`, `->`

type
  WriterUnit = (float, string)
  WriterBind = proc(a: WriterUnit): WriterUnit

proc bindWith(f: (x: float) -> float; log: string): WriterBind =
  result = (a: WriterUnit) => (f(a[0]), a[1] & log)

func doneWith(x: int): WriterUnit =
  (x.float, "")

var
  logRoot = sqrt.bindWith "obtained square root, "
  logAddOne = ((x: float) => x+1'f).bindWith "added 1, "
  logHalf = ((x: float) => x/2'f).bindWith "divided by 2, "

echo 5.doneWith.logRoot.logAddOne.logHalf


# 20200704 added Perl programming solution

package Writer;

use strict;
use warnings;

sub new {
   my ($class, $value, $log) = @_;
   return bless [ $value => $log ], $class;
}

sub Bind {
   my ($self, $code) = @_;
   my ($value, $log) = @$self;
   my $n = $code->($value);
   return Writer->new( @$n[0], $log.@$n[1] );
}

sub Unit { Writer->new($_[0], sprintf("%-17s: %.12f\n",$_[1],$_[0])) }

sub root { Unit sqrt($_[0]), "Took square root" }

sub addOne { Unit $_[0]+1, "Added one" }

sub half { Unit $_[0]/2, "Divided by two" }

print Unit(5, "Initial value")->Bind(\&root)->Bind(\&addOne)->Bind(\&half)->[1];


with javascript_semantics
function bind(object m, integer f)
    return f(m)
end function

function unit(object m)
    return m
end function

function root(sequence al)
    {atom a, string lg} = al
    atom res = sqrt(a)
    return {res,lg&sprintf("took root: %f -> %f\n",{a,res})}
end function

function addOne(sequence al)
    {atom a, string lg} = al
    atom res = a + 1
    return {res,lg&sprintf("added one: %f -> %f\n",{a,res})}
end function

function half(sequence al)
    {atom a, string lg} = al
    atom res = a / 2
    return {res,lg&sprintf("halved it: %f -> %f\n",{a,res})}
end function

printf(1,"%f obtained by\n%s", bind(bind(bind({5,""},root),addOne),half))


class WriterMonad {

	/** @var mixed */
	private $value;
	/** @var string[] */
	private $logs;

	private function __construct($value, array $logs = []) {
		$this->value = $value;
		$this->logs = $logs;
	}

	public static function unit($value, string $log): WriterMonad {
		return new WriterMonad($value, ["{$log}: {$value}"]);
	}

	public function bind(callable $mapper): WriterMonad  {
		$mapped = $mapper($this->value);
		assert($mapped instanceof WriterMonad);
		return new WriterMonad($mapped->value, [...$this->logs, ...$mapped->logs]);
	}

	public function value() {
		return $this->value;
	}

	public function logs(): array {
		return $this->logs;
	}
}

$root = fn(float $i): float => sqrt($i);
$addOne = fn(float $i): float => $i + 1;
$half = fn(float $i): float => $i / 2;

$m = fn (callable $callback, string $log): callable => fn ($value): WriterMonad => WriterMonad::unit($callback($value), $log);

$result = WriterMonad::unit(5, "Initial value")
	->bind($m($root, "square root"))
	->bind($m($addOne, "add one"))
	->bind($m($half, "half"));

print "The Golden Ratio is: {$result->value()}\n";
print join("\n", $result->logs());


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

import functools
import math
import os

from typing import Any
from typing import Callable
from typing import Generic
from typing import List
from typing import TypeVar
from typing import Union

T = TypeVar("T")

class Writer(Generic[T]):
    def __init__(self, value: Union[T, Writer[T]], *msgs: str):
        if isinstance(value, Writer):
            self.value: T = value.value
            self.msgs: List[str] = value.msgs + list(msgs)
        else:
            self.value = value
            self.msgs = list(f"{msg}: {self.value}" for msg in msgs)

    def bind(self, func: Callable[[T], Writer[Any]]) -> Writer[Any]:
        writer = func(self.value)
        return Writer(writer, *self.msgs)

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

    def __str__(self):
        return f"{self.value}\n{os.linesep.join(reversed(self.msgs))}"

    def __repr__(self):
        return f"Writer({self.value}, \"{', '.join(reversed(self.msgs))}\")"

def lift(func: Callable, msg: str) -> Callable[[Any], Writer[Any]]:
    """Return a writer monad version of the simple function `func`."""

    @functools.wraps(func)
    def wrapped(value):
        return Writer(func(value), msg)

    return wrapped

if __name__ == "__main__":
    square_root = lift(math.sqrt, "square root")
    add_one = lift(lambda x: x + 1, "add one")
    half = lift(lambda x: x / 2, "div two")

    print(Writer(5, "initial") >> square_root >> add_one >> half)


# 20200508 Raku programming solution

class Writer { has Numeric $.value ; has Str $.log }

sub Bind (Writer \v, &code) {
   my \n = v.value.&code;
   Writer.new: value => n.value, log => v.log ~ n.log
};

sub Unit(\v, \s) { Writer.new: value=>v, log=>sprintf "%-17s: %.12f\n",s,v}

sub root(\v) { Unit v.sqrt, "Took square root" }

sub addOne(\v) { Unit v+1, "Added one" }

sub half(\v) { Unit v/2, "Divided by two" }

say Unit(5, "Initial value").&Bind(&root).&Bind(&addOne).&Bind(&half).log;


import "/fmt" for Fmt

class Mwriter {
    construct new(value, log) {
        _value = value
        _log = log
    }

    value { _value }
    log {_log}
    log=(value) { _log = value }

    bind(f) {
        var n = f.call(_value)
        n.log = _log + n.log
        return n
    }

    static unit(v, s) { Mwriter.new(v, "  %(Fmt.s(-17, s)): %(v)\n") }
}

var root   = Fn.new { |v| Mwriter.unit(v.sqrt, "Took square root") }
var addOne = Fn.new { |v| Mwriter.unit(v + 1,  "Added one") }
var half   = Fn.new { |v| Mwriter.unit( v / 2, "Divided by two") }

var mw1 = Mwriter.unit(5, "Initial value")
var mw2 = mw1.bind(root).bind(addOne).bind(half)
System.print("The Golden Ratio is %(mw2.value)")
System.print("\nThis was derived as follows:-")
System.print(mw2.log)


class Writer{
   fcn init(x){ var X=x, logText=Data(Void,"  init \U2192; ",x.toString()) }
   fcn unit(text)  { logText.append(text); self }
   fcn lift(f,name){ unit("\n  %s \U2192; %s".fmt(name,X=f(X))) }
   fcn bind(f,name){ lift.fp(f,name) }
   fcn toString{ "Result = %s\n%s".fmt(X,logText.text) }

   fcn root{ lift(fcn(x){ x.sqrt() },"root") }
   fcn half{ lift('/(2),"half") }
   fcn inc { lift('+(1),"inc") }
}


V n = 12
L(j) 1..n
   print(‘#3’.format(j), end' ‘ ’)
print(‘│’)
L 1..n
   print(‘────’, end' ‘’)
print(‘┼───’)

L(i) 1..n
   L(j) 1..n
      print(I j < i {‘    ’} E ‘#3 ’.format(i * j), end' ‘’)
   print(‘│ ’i)


*        12*12 multiplication table    14/08/2015
MULTTABL CSECT
         USING  MULTTABL,R12
         LR     R12,R15
         LA     R10,0              buffer pointer
         LA     R3,BUFFER
         MVC    0(4,R3),=C'  | '
         LA     R10,4(R10)
         LA     R5,12
         LA     R4,1               i=1
LOOPN    LA     R3,BUFFER          do i=1 to 12
         AR     R3,R10
         XDECO  R4,XDEC            i
         MVC    0(4,R3),XDEC+8     output i
         LA     R10,4(R10)
         LA     R4,1(R4)
         BCT    R5,LOOPN           end i
         XPRNT  BUFFER,52
         XPRNT  PORT,52            border
         LA     R5,12
         LA     R4,1               i=1 (R4)
LOOPI    LA     R10,0              do i=1 to 12
         MVC    BUFFER,=CL52' '
         LA     R3,BUFFER
         AR     R3,R10
         XDECO  R4,XDEC
         MVC    0(2,R3),XDEC+10
         LA     R10,2(R10)
         LA     R3,BUFFER
         AR     R3,R10
         MVC    0(2,R3),=C'| '
         LA     R10,2(R10)
         LA     R7,12
         LA     R6,1               j=1 (R6)
LOOPJ    CR     R6,R4              do j=1 to 12
         BNL    MULT
         LA     R3,BUFFER
         AR     R3,R10
         MVC    0(4,R3),=C'    '
         LA     R10,4(R10)
         B      NEXTJ
MULT     LR     R9,R4              i
         MR     R8,R6              i*j in R8R9
         LA     R3,BUFFER
         AR     R3,R10
         XDECO  R9,XDEC
         MVC    0(4,R3),XDEC+8
         LA     R10,4(R10)
NEXTJ    LA     R6,1(R6)
         BCT    R7,LOOPJ           end j
ELOOPJ   XPRNT  BUFFER,52
         LA     R4,1(R4)
         BCT    R5,LOOPI           end i
ELOOPI   XR     R15,R15
         BR     R14
BUFFER   DC     CL52' '
XDEC     DS     CL12
PORT     DC     C'--+-------------------------------------------------'
         YREGS
         END    MULTTABL


	org	100h
	lxi	h,output
	;;;	Make the header
	call	skip	; Four spaces,
	mvi	m,'|'	; separator,
	inx	h
	lxi	d,0C01h	; 12 fields starting at 1
fnum:	mov	a,e	; Field number
	call	num
	inr	e
	dcr 	d	; If not 12 yet, next field number
	jnz	fnum
	call	nl	; Newline
	mvi	a,'-'	; Four dashes,
	mvi	b,4
	call	bchr
	mvi	m,'+'	; Plus,
	inx	h
	mvi	b,12*4	; and 12*4 more dashes
	call	bchr
	call	nl	; Newline
	;;;	Write the 12 lines
	mvi	d,1	; Start at line 1,
line:	mov	a,d	; Add the line number
	call	num
	mvi	m,'|'	; separator
	inx	h
	mvi	e,1	; Start at column 1
	mvi	c,0	; Cumulative sum at C
field:	mov	a,c	; Add line number giving next column
	add	d
	mov	c,a
	mov	a,e	; If column >= line, we need to print
	cmp	d
	mov	a,c	; the current total
	cc	skip	; skip field if column >= line
	cnc	num	; print field if column < line
	inr	e	; next column
	mov	a,e
	cpi	13	; column 13?
	jnz	field	; If not, next field on line
	call 	nl	; But if so, add newline
	inr	d	; next line
	mov	a,d
	cpi	13	; line 13?
	jnz	line	; If not, next line
	mvi	m,'$'	; Write a CP/M string terminator,
	mvi	c,9	; And use CP/M to print the string
	lxi	d,output
	jmp	5
	;;;	Add the character in A to the string at HL, B times
bchr:	mov	m,a
	inx	h
	dcr	b
	jnz	bchr
	ret
	;;;	Add newline to string at HL
nl:	mvi	m,13	; CR
	inx	h
	mvi	m,10	; LF
	inx	h
	ret
	;;;	Add four spaces to string at HL (skip field)
skip:	mvi	b,' '
	mov	m,b
	inx	h
	mov	m,b
	inx	h
	mov	m,b
	inx	h
	mov	m,b
	inx	h
	ret
	;;;	Add 3-digit number in A to string at HL
num:	mvi	m,' '	; Separator space
	inx	h
	ana	a	; Clear carry
	mvi	b,100	; 100s digit
	call	dspc
	mvi	b,10	; 10s digit
	call	dspc
	mvi	b,1	; 1s digit
dspc:	jc	dgt	; If carry, we need a digit
	cmp	b	; >= digit?
	jnc	dgt	; If not, we need a digit
	mvi	m,' '	; Otherwise, fill with space
	inx	h
	cmc		; Return with carry off
	ret
dgt:	mvi	m,'0'-1	; Calculate digit
dloop:	inr	m	; Increment digit
	sub	b	; while B can be subtracted
	jnc	dloop
	add	b
	inx	h
	ret
output:	equ	$


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

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ MAXI,   12
/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessValeur:        .fill 11, 1, ' '            // size => 11
szCarriageReturn:   .asciz "\n"
sBlanc1:            .asciz " "
sBlanc2:            .asciz "  "
sBlanc3:            .asciz "   "
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                           // entry of program
    ldr x6,qAdrsBlanc1
    ldr x7,qAdrsBlanc2
    ldr x8,qAdrsBlanc3
                                // display first line
    mov x4,#0
1:                              // begin loop
    mov x0,x4
    ldr x1,qAdrsMessValeur      // display value
    bl conversion10             // call function
    strb wzr,[x1,x0]            // final zéro on display value
    ldr x0,qAdrsMessValeur
    bl affichageMess            // display message
    cmp x4,#10                  // one or two digit in résult
    csel x0,x7,x8,ge            // display 2 or 3 spaces
    bl affichageMess            // display message
    add x4,x4,1                 // increment counter
    cmp x4,MAXI
    ble 1b                      // loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess            // display carriage return

    mov x5,#1                   // line counter
2:                              // begin loop lines
    mov x0,x5                   // display column 1 with N° line
    ldr x1,qAdrsMessValeur      // display value
    bl conversion10             // call function
    strb wzr,[x1,x0]            // final zéro
    ldr x0,qAdrsMessValeur
    bl affichageMess            // display message
    cmp x5,#10                  // one or two digit in N° line
    csel x0,x7,x8,ge            // display 2 or 3 spaces
    bl affichageMess
    mov x4,#1                  // counter column
3:                             // begin loop columns
    mul x0,x4,x5               // multiplication
    mov x3,x0                  // save résult
    ldr x1,qAdrsMessValeur     // display value
    bl conversion10            // call function
    strb wzr,[x1,x0]
    ldr x0,qAdrsMessValeur
    bl affichageMess           // display message
    cmp x3,100                 // 3 digits in résult ?
    csel x0,x6,x0,ge           // display 1 spaces
    bge 4f
    cmp x3,10                  // 2 digits in result
    csel x0,x7,x8,ge           // display 2 or 3 spaces

4:
    bl affichageMess           // display message
    add x4,x4,1                // increment counter column
    cmp x4,x5                  // < counter lines
    ble 3b                     // loop
    ldr x0,qAdrszCarriageReturn
    bl affichageMess           // display carriage return
    add x5,x5,1                // increment line counter
    cmp x5,MAXI                // MAXI ?
    ble 2b                     // loop

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

qAdrsMessValeur:         .quad sMessValeur
qAdrszCarriageReturn:    .quad szCarriageReturn
qAdrsBlanc1:             .quad sBlanc1
qAdrsBlanc2:             .quad sBlanc2
qAdrsBlanc3:             .quad sBlanc3

/******************************************************************/
/*     Converting a register to a decimal unsigned                */
/******************************************************************/
/* x0 contains value and x1 address area   */
/* x0 return size of result (no zero final in area) */
/* area size => 11 bytes          */
.equ LGZONECAL,   10
conversion10:
    stp x1,lr,[sp,-16]!            // save  registers
    stp x2,x3,[sp,-16]!            // save  registers
    stp x4,x5,[sp,-16]!            // save  registers
    mov x3,x1
    mov x2,#LGZONECAL
    mov x4,10
1:                                 // start loop
    mov x5,x0
    udiv x0,x5,x4
    msub x1,x0,x4,x5               //  x5 <- dividende. quotient ->x0 reste -> x1
    add x1,x1,48                      // digit
    strb w1,[x3,x2]                // store digit on area
    cbz x0,2f                      // stop if quotient = 0
    sub x2,x2,1                    // else previous position
    b 1b                           // and loop
                                   // and move digit from left of area
2:
    mov x4,0
3:
    ldrb w1,[x3,x2]
    strb w1,[x3,x4]
    add x2,x2,1
    add x4,x4,1
    cmp x2,LGZONECAL
    ble 3b
                                  // and move spaces in end on area
    mov x0,x4                     // result length
    mov x1,' '                    // space
4:
    strb w1,[x3,x4]               // store space in area
    add x4,x4,1                   // next position
    cmp x4,LGZONECAL
    ble 4b                        // loop if x4 <= area size

100:
    ldp x4,x5,[sp],16                     // restaur  2 registers
    ldp x2,x3,[sp],16                     // restaur  2 registers
    ldp x1,lr,[sp],16                     // restaur  2 registers
    ret                                   // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


PROC PrintRight(BYTE num,size)
  BYTE i

  IF num<10 THEN
    size==-1
  ELSEIF num<100 THEN
    size==-2
  ELSE
    size==-3
  FI
  FOR i=1 TO size
  DO
    Put(' )
  OD
  PrintB(num)
RETURN

PROC Main()
  BYTE ARRAY colw=[1 1 1 2 2 2 2 2 2 3 3 3]
  BYTE i,j,x,w

  ;clear screen
  Put(125)

  ;draw frame
  Position(1,3)
  FOR i=1 TO 38
  DO Put($12) OD

  FOR j=2 TO 15
  DO
    Position(36,j)
    Put($7C)
  OD

  Position(36,3)
  Put($13)

  ;draw numbers
  FOR j=1 TO 12
  DO
    x=1
    FOR i=1 TO 12
    DO
      w=colw(i-1)
      IF i>=j THEN
        IF j=1 THEN
          Position(x,j+1)
          PrintRight(i*j,w)
        FI
        IF i=12 THEN
          Position(37,j+3)
          PrintRight(j,2)
        FI
        Position(x,j+3)
        PrintRight(i*j,w)
      FI
      x==+w+1
    OD
  OD
RETURN


package {

    import flash.display.Sprite;
    import flash.events.Event;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFormat;

    [SWF (width = 550, height = 550)]
    public class MultiplicationTable extends Sprite {

        public function MultiplicationTable() {
            if ( stage ) _init();
            else addEventListener(Event.ADDED_TO_STAGE, _init);
        }

        private function _init(e:Event = null):void {

            removeEventListener(Event.ADDED_TO_STAGE, _init);

            var format:TextFormat = new TextFormat();
            format.size = 15;
            var blockSize:uint = 40;
            var max:uint = 12;

            var i:uint, j:uint;
            var tf:TextField;

            for ( i = 1; i <= max; i++ ) {
                tf = new TextField();
                tf.defaultTextFormat = format;
                tf.x = blockSize * i;
                tf.y = 0;
                tf.width = tf.height = blockSize;
                tf.autoSize = TextFieldAutoSize.CENTER;
                tf.text = String(i);
                addChild(tf);

                tf = new TextField();
                tf.defaultTextFormat = format;
                tf.x = 0;
                tf.y = blockSize * i;
                tf.width = tf.height = blockSize;
                tf.autoSize = TextFieldAutoSize.CENTER;
                tf.text = String(i);
                addChild(tf);
            }

            var yOffset:Number = tf.textHeight / 2;
            y += yOffset;

            graphics.lineStyle(1, 0x000000);
            graphics.moveTo(blockSize, -yOffset);
            graphics.lineTo(blockSize, (blockSize * (max + 1)) - yOffset);
            graphics.moveTo(0, blockSize - yOffset);
            graphics.lineTo(blockSize * (max + 1), blockSize - yOffset);

            for ( i = 1; i <= max; i++ ) {
                for ( j = 1; j <= max; j++ ) {
                    if ( j > i )
                        continue;

                    tf = new TextField();
                    tf.defaultTextFormat = format;
                    tf.x = blockSize * i;
                    tf.y = blockSize * j;
                    tf.width = tf.height = blockSize;
                    tf.autoSize = TextFieldAutoSize.CENTER;
                    tf.text = String(i * j);
                    addChild(tf);
                }
            }

        }

    }

}


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Fixed;  use Ada.Strings.Fixed;
procedure Multiplication_Table is
   package IO is new Integer_IO (Integer);
   use IO;
begin
   Put ("  | ");
   for Row in 1..12 loop
      Put (Row, Width => 4);
   end loop;
   New_Line;
   Put_Line ("--+-" & 12 * 4 * '-');
   for Row in 1..12 loop
      Put (Row, Width => 2);
      Put ("| ");
      for Column in 1..12 loop
         if Column < Row then
            Put ("    ");
         else
            Put (Row * Column, Width => 4);
         end if;
      end loop;
      New_Line;
   end loop;
end Multiplication_Table;


scope
    # print a school style multiplication table
    # NB: print outputs a newline at the end, write and printf do not
    write( "    " );
    for i to 12 do printf( " %3d", i ) od;
    printf( "\n   +" );
    for i to 12 do write( "----" ) od;
    for i to 12 do
        printf( "\n%3d|", i );
        for j        to i - 1 do write(  "    "        ) od;
        for j from i to 12    do printf( " %3d", i * j ) od;
    od;
    print()
epocs


main:(
  INT max = 12;
  INT width = ENTIER(log(max)*2)+1;
  STRING empty = " "*width, sep="|", hr = "+" + (max+1)*(width*"-"+"+");
  FORMAT ifmt = $g(-width)"|"$; # remove leading zeros #

  printf(($gl$, hr));
  print(sep + IF width<2 THEN "x" ELSE " "*(width-2)+"x " FI + sep);
  FOR col TO max DO printf((ifmt, col)) OD;
  printf(($lgl$, hr));

  FOR row TO max DO
    [row:max]INT product;
    FOR col FROM row TO max DO product[col]:=row*col OD;
    STRING prefix=(empty+sep)*(row-1);
    printf(($g$, sep, ifmt, row, $g$, prefix, ifmt, product, $l$))
  OD;
  printf(($gl$, hr))
)


begin
    % print a school style multiplication table                              %
    i_w := 3; s_w := 0; % set output formating                               %
    write( "    " );
    for i := 1 until 12 do writeon( " ", i );
    write( "   +" );
    for i := 1 until 12 do writeon( "----" );
    for i := 1 until 12 do begin
        write( i, "|" );
        for j := 1 until i - 1 do writeon( "    " );
        for j := i until 12    do writeon( " ", i * j );
    end;

end.


set n to 12 -- Size of table.
repeat with x from 0 to n
    if x = 0 then set {table, x} to {{return}, -1}
    repeat with y from 0 to n
        if y's contents = 0 then
            if x > 0 then set row to {f(x)}
            if x = -1 then set {row, x} to {{f("x")}, 1}
        else
            if y ≥ x then set end of row to f(x * y)
            if y < x then set end of row to f("")
        end if
    end repeat
    set end of table to row & return
end repeat
return table as string

-- Handler/Function for formatting fixed width integer string.
on f(x)
    set text item delimiters to ""
    return (characters -4 thru -1 of ("    " & x)) as string
end f


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

/************************************/
/* Constantes                       */
/************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
.equ MAXI,   12
/*********************************/
/* Initialized data              */
/*********************************/
.data
sMessValeur:       .fill 11, 1, ' '            @ size => 11
szCarriageReturn: .asciz "\n"
sBlanc1:            .asciz " "
sBlanc2:            .asciz "  "
sBlanc3:            .asciz "   "
/*********************************/
/* UnInitialized data            */
/*********************************/
.bss
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                @ entry of program
    push {fp,lr}      @ saves 2 registers
    @ display first line
    mov r4,#0
1:    @ begin loop
    mov r0,r4
    ldr r1,iAdrsMessValeur     @ display value
    bl conversion10             @ call function
    mov r2,#0                      @ final zéro
    strb r2,[r1,r0]               @ on display value
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
    cmp r4,#10                     @ one or two digit in résult
    ldrgt r0,iAdrsBlanc2       @ two  display two spaces
    ldrle r0,iAdrsBlanc3       @ one  display 3 spaces
    bl affichageMess            @ display message
    add r4,#1                      @ increment counter
    cmp r4,#MAXI
    ble 1b                       @ loop
    ldr r0,iAdrszCarriageReturn
    bl affichageMess            @ display carriage return

    mov r5,#1                   @ line counter
2:    @ begin loop lines
    mov r0,r5                      @ display column 1 with N° line
    ldr r1,iAdrsMessValeur     @ display value
    bl conversion10             @ call function
    mov r2,#0                      @ final zéro
    strb r2,[r1,r0]
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
    cmp r5,#10                      @ one or two digit in N° line
    ldrge r0,iAdrsBlanc2
    ldrlt r0,iAdrsBlanc3
    bl affichageMess
    mov r4,#1                     @ counter column
3:  @ begin loop columns
    mul r0,r4,r5                   @ multiplication
    mov r3,r0                      @ save résult
    ldr r1,iAdrsMessValeur     @ display value
    bl conversion10             @ call function
    mov r2,#0
    strb r2,[r1,r0]
    ldr r0,iAdrsMessValeur
    bl affichageMess            @ display message
    cmp r3,#100                    @ 3 digits in résult ?
    ldrge r0,iAdrsBlanc1       @ yes, display one space
    bge 4f
    cmp r3,#10                     @ 2 digits in result
    ldrge r0,iAdrsBlanc2       @ yes display 2 spaces
    ldrlt r0,iAdrsBlanc3       @ no  display 3 spaces
4:
    bl affichageMess            @ display message
    add r4,#1                      @ increment counter column
    cmp r4,r5                      @ < counter lines
    ble 3b                        @ loop
    ldr r0,iAdrszCarriageReturn
    bl affichageMess            @ display carriage return
    add r5,#1                      @ increment line counter
    cmp r5,#MAXI                  @ MAXI ?
    ble 2b                        @ loop

100:   @ standard end of the program
    mov r0, #0                  @ return code
    pop {fp,lr}                 @restaur 2 registers
    mov r7, #EXIT              @ request to exit program
    svc #0                       @ perform the system call

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

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

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

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


mulTable: function [n][
    print ["    |"] ++ map 1..n => [pad to :string & 3]
    print "----+" ++ join map 1..n => "----"
    loop 1..n 'x [
        prints (pad to :string x 3) ++ " |"
        if x>1 -> loop 1..x-1 'y [prints "    "]
        loop x..n 'y [prints " " ++ pad to :string x*y 3]
        print ""
    ]
]

mulTable 12


REM Multiplication tables
N = 12
PREDN = N - 1
WDTH = 3
CLS
FOR J = 1 TO PREDN
  INTVAL = J
  GOSUB PRINTINT:
  PRINT " ";
NEXT J
INTVAL = N
GOSUB PRINTINT:
PRINT
FOR J = 0 TO PREDN
  PRINT "----";
NEXT J
PRINT "+"
FOR I = 1 TO N
  WDTH = 3
  FOR J = 1 TO N
    IF J < I THEN
      PRINT "    ";
    ELSE
      INTVAL = I * J
      GOSUB PRINTINT:
      PRINT " ";
    ENDIF
  NEXT J
  PRINT "| ";
  INTVAL = I
  WDTH = 2
  GOSUB PRINTINT:
  PRINT
NEXT I
END

PRINTINT:
REM Writes the value of INTVAL in a field of the given WDTH
S2$ = STR$(INTVAL)
S2$ = LTRIM$(S2$)
SPNUM = LEN(S2$)
SPNUM = WDTH - SPNUM
S1$ = SPACE$(SPNUM)
PRINT S1$;
PRINT S2$;
RETURN


Gui, -MinimizeBox
Gui, Margin, 0, 0
Gui, Font, s9, Fixedsys
Gui, Add, Edit, h0 w0
Gui, Add, Edit, w432 r14 -VScroll
Gosub, Table
Gui, Show,, Multiplication Table
Return

GuiClose:
GuiEscape:
    ExitApp
Return

Table:
    ; top row
    Table := "  x |"
    Loop, 12
        Table .= SubStr("   " A_Index, -3)
    Table .= "`n"

    ; underlines
    Table .= "----+"
    Loop, 48
        Table .= "-"
    Table .= "`n"

    ; table
    Loop, 12 { ; rows
        Table .= SubStr("  " Row := A_Index, -2) " |"
        Loop, 12 ; columns
            Table .= SubStr("    " (A_Index >= Row ? A_Index * Row : ""), -3)
        Table .= "`n"
    }
    GuiControl,, Edit2, %Table%
Return


#AutoIt Version: 3.2.10.0
$tableupto=12
$table=""
for $i = 1 To $tableupto
   for $j = $i to $tableupto
      $prod=string($i*$j)
      if StringLen($prod) == 1  then
	 $prod = "    "& $prod
      EndIf
      if StringLen($prod) == 2  then
	 $prod = "  "& $prod
      EndIf
      $table = $table&" "&$prod
   Next
   $table = $table&"  - "&$i&@CRLF
   for  $k = 1 to $i
      $table = $table&"       "
   Next
Next
msgbox(0,"Multiplication Tables",$table)


Fix 5
ClrDraw
For(I,1,10)
 Text(I-1*9,0,I▶Dec)
 Text(91,I*7+1,I▶Dec)
End

For(J,1,8)
 For(I,J,10)
  Text(I-1*9,J*7+1,I*J▶Dec)
 End
End

HLine(7)
VLine(89)
DispGraph
getKeyʳ
Fix 4


CLS

'header row
PRINT "     ";
FOR n = 1 TO 12
    'do it this way for alignment purposes
    o$ = "    "
    MID$(o$, LEN(o$) - LEN(STR$(n)) + 1) = STR$(n)
    PRINT o$;
NEXT
PRINT : PRINT "    "; STRING$(49, "-");

FOR n = 1 TO 12
    PRINT
    IF n < 10 THEN PRINT " ";
    PRINT n; "|";   'row labels
    FOR m = 1 TO n - 1
        PRINT "    ";
    NEXT
    FOR m = n TO 12
        'alignment again
        o$ = "    "
        MID$(o$, LEN(o$) - LEN(STR$(m * n)) + 1) = STR$(m * n)
        PRINT o$;
    NEXT
NEXT


@echo off
setlocal enabledelayedexpansion

::The Main Thing...
cls
set colum=12&set row=12
call :multable
echo.
pause
exit /b 0
::/The Main Thing.

::The Functions...
:multable
	echo.
	for /l %%. in (1,1,%colum%) do (
	call :numstr %%.
	set firstline=!firstline!!space!%%.
	set seconline=!seconline!-----
	)
	echo !firstline!
	echo !seconline!

	::The next lines here until the "goto :EOF" prints the products...

	for /l %%X in (1,1,%row%) do (
		for /l %%Y in (1,1,%colum%) do (
			if %%Y lss %%X (set "line%%X=!line%%X!     ") else (
				set /a ans=%%X*%%Y
				call :numstr !ans!
				set "line%%X=!line%%X!!space!!ans!"
			)
		)
		echo.!line%%X! ^| %%X
	)
	goto :EOF

:numstr
	::This function returns the number of whitespaces to be applied on each numbers.
	set cnt=0&set proc=%1&set space=
	:loop
	set currchar=!proc:~%cnt%,1!
	if not "!currchar!"=="" set /a cnt+=1&goto loop
	set /a numspaces=5-!cnt!
	for /l %%A in (1,1,%numspaces%) do set "space=!space! "
goto :EOF
::/The Functions.


      @% = 5 : REM Set column width
      FOR row% = 1 TO 12
        PRINT row% TAB(row% * @%) ;
        FOR col% = row% TO 12
          PRINT row% * col% ;
        NEXT col%
        PRINT
      NEXT row%


Table ← {
  m ← •Repr¨ ×⌜˜1+↕𝕩             # The numbers, formatted individually
  main ← ⟨                       # Bottom part: three sections
    >(-⌈10⋆⁼𝕩)↑¨⊏m               # Original numbers
    𝕩⥊'|'                        # Divider
    ∾˘(-1+⌈10⋆⁼𝕩×𝕩)↑¨(≤⌜˜↕𝕩)/¨m  # Multiplied numbers, padded and joined
  ⟩
  head ← ' '¨⌾⊑ ⊏¨ main          # Header: first row but with space left of |
  ∾ >⟨head, "-+-"⊣¨¨head, main⟩  # Header, divider, and main
}

•Out˘ Table 12


  ( multiplicationTable
  =     high i j row row2 matrix padFnc tmp
      , celPad leftCelPad padFnc celDashes leftDashes
    .   !arg:?high
      & ( padFnc
        =   L i w d
          .   @(!arg:? [?L)
            & 1+(!L:?i):?L
            & " ":?w
            & "-":?d
            &   whl
              ' ( !i+-1:~<0:?i
                & " " !w:?w
                & "-" !d:?d
                )
            & str$!w:?w
            & (
                ' (
                  .   @(str$(rev$!arg ()$w):?arg [($L) ?)
                    & rev$!arg
                  )
              . str$!d
              )
        )
      & padFnc$(!high^2):((=?celPad).?celDashes)
      & @(!high:?tmp [-2 ?)
      & padFnc$!tmp:((=?leftCelPad).?leftDashes)
      & 0:?i
      & :?row:?row2
      &   whl
        ' ( 1+!i:~>!high:?i
          & !row celPad$!i:?row
          & !celDashes !row2:?row2
          )
      &   str$(leftCelPad$X "|" !row \n !leftDashes "+" !row2 \n)
        : ?matrix
      & 0:?j
      &   whl
        ' ( 1+!j:~>!high:?j
          & 0:?i
          & :?row
          &   whl
            ' ( 1+!i:<!j:?i
              & celPad$() !row:?row
              )
          & leftCelPad$!j "|" !row:?row
          &   whl
            ' ( 1+!i:~>!high:?i
              & !row celPad$(!i*!j):?row
              )
          & !matrix str$(!row \n):?matrix
          )
      & str$!matrix
  )
& out$(multiplicationTable$12)
& done;


using System;

namespace multtbl
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write(" X".PadRight(4));
            for (int i = 1; i <= 12; i++)
                Console.Write(i.ToString("####").PadLeft(4));

            Console.WriteLine();
            Console.Write(" ___");

            for (int i = 1; i <= 12; i++)
                Console.Write(" ___");

            Console.WriteLine();
            for (int row = 1; row <= 12; row++)
            {
                Console.Write(row.ToString("###").PadLeft(3).PadRight(4));
                for (int col = 1; col <= 12; col++)
                {
                    if (row <= col)
                        Console.Write((row * col).ToString("###").PadLeft(4));
                    else
                        Console.Write("".PadLeft(4));
                }

                Console.WriteLine();
            }

            Console.WriteLine();
            Console.ReadLine();
        }
    }
}


#include <iostream>
#include <iomanip>
#include <cmath> // for log10()
#include <algorithm> // for max()

size_t table_column_width(const int min, const int max)
{
    unsigned int abs_max = std::max(max*max, min*min);

    // abs_max is the largest absolute value we might see.
    // If we take the log10 and add one, we get the string width
    // of the largest possible absolute value.
    // Add one more for a little whitespace guarantee.
    size_t colwidth = 2 + std::log10(abs_max);

    // If only one of them is less than 0, then some will
    // be negative. If some values may be negative, then we need to add some space
    // for a sign indicator (-)
    if (min < 0 && max > 0)
	++colwidth;
    return colwidth;
}

struct Writer_
{
    decltype(std::setw(1)) fmt_;
    Writer_(size_t w) : fmt_(std::setw(w)) {}
    template<class T_> Writer_& operator()(const T_& info) { std::cout << fmt_ << info; return *this; }
};

void print_table_header(const int min, const int max)
{
    Writer_ write(table_column_width(min, max));

    // table corner
    write(" ");
    for(int col = min; col <= max; ++col)
        write(col);

    // End header with a newline and blank line.
    std::cout << std::endl << std::endl;
}

void print_table_row(const int num, const int min, const int max)
{
    Writer_ write(table_column_width(min, max));

    // Header column
    write(num);

    // Spacing to ensure only the top half is printed
    for(int multiplicand = min; multiplicand < num; ++multiplicand)
        write(" ");

    // Remaining multiplicands for the row.
    for(int multiplicand = num; multiplicand <= max; ++multiplicand)
        write(num * multiplicand);

    // End row with a newline and blank line.
    std::cout << std::endl << std::endl;
}

void print_table(const int min, const int max)
{
    // Header row
    print_table_header(min, max);

    // Table body
    for(int row = min; row <= max; ++row)
        print_table_row(row, min, max);
}

int main()
{
    print_table(1, 12);
    return 0;
}


Multigrain Bread.

Prints out a multiplication table.

Ingredients.
12 cups flour
12 cups grains
12 cups seeds
1 cup water
9 dashes yeast
1 cup nuts
40 ml honey
1 cup sugar

Method.
Sift the flour.
 Put flour into the 1st mixing bowl.
 Put yeast into the 1st mixing bowl.
Shake the flour until sifted.
Put grains into the 2nd mixing bowl.
Fold flour into the 2nd mixing bowl.
Put water into the 2nd mixing bowl.
Add yeast into the 2nd mixing bowl.
Combine flour into the 2nd mixing bowl.
Fold nuts into the 2nd mixing bowl.
Liquify nuts.
Put nuts into the 1st mixing bowl.
Pour contents of the 1st mixing bowl into the baking dish.
Sieve the flour.
 Put yeast into the 2nd mixing bowl.
 Add water into the 2nd mixing bowl.
 Sprinkle the seeds.
   Put flour into the 2nd mixing bowl.
   Combine seeds into the 2nd mixing bowl.
   Put yeast into the 2nd mixing bowl.
   Put seeds into the 2nd mixing bowl.
   Remove flour from the 2nd mixing bowl.
   Fold honey into the 2nd mixing bowl.
   Put water into the 2nd mixing bowl.
   Fold sugar into the 2nd mixing bowl.
   Squeeze the honey.
     Put water into the 2nd mixing bowl.
     Remove water from the 2nd mixing bowl.
     Fold sugar into the 2nd mixing bowl.
     Set aside.
   Drip until squeezed.
   Scoop the sugar.
     Crush the seeds.
       Put yeast into the 2nd mixing bowl.
     Grind the seeds until crushed.
     Put water into the 2nd mixing bowl.
     Fold seeds into the 2nd mixing bowl.
     Set aside.
   Drop until scooped.
 Randomize the seeds until sprinkled.
 Fold honey into the 2nd mixing bowl.
 Put flour into the 2nd mixing bowl.
 Put grains into the 2nd mixing bowl.
 Fold seeds into the 2nd mixing bowl.
Shake the flour until sieved.
Put yeast into the 2nd mixing bowl.
Add water into the 2nd mixing bowl.
Pour contents of the 2nd mixing bowl into the 2nd baking dish.

Serves 2.


(let [size 12
      trange (range 1 (inc size))
      fmt-width (+ (.length (str (* size size))) 1)
      fmt-str (partial format (str "%" fmt-width "s"))
      fmt-dec (partial format (str "% " fmt-width "d"))]

  (doseq [s (cons
             (apply str (fmt-str " ") (map #(fmt-dec %) trange))
             (for [i trange]
               (apply str (fmt-dec i) (map #(fmt-str (str %))
                                           (map #(if (>= % i) (* i %) " ")
                                                (for [j trange] j))))))]
    (println s)))


       identification division.
       program-id. multiplication-table.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 multiplication.
          05 rows occurs 12 times.
             10 colm occurs 12 times.
                15 num    pic 999.
       77 cand pic 99.
       77 ier  pic 99.
       77 ind  pic z9.
       77 show pic zz9.

       procedure division.
       sample-main.
       perform varying cand from 1 by 1 until cand greater than 12
                  after ier from 1 by 1 until ier greater than 12
           multiply cand by ier giving num(cand, ier)
       end-perform

       perform varying cand from 1 by 1 until cand greater than 12
           move cand to ind
           display "x " ind "| " with no advancing
           perform varying ier from 1 by 1 until ier greater than 12
               if ier greater than or equal to cand then
                   move num(cand, ier) to show
                   display show with no advancing
                   if ier equal to 12 then
                       display "|"
                   else
                       display space with no advancing
                   end-if
               else
                   display "    " with no advancing
               end-if
           end-perform
       end-perform

       goback.
       end program multiplication-table.


print_multiplication_tables = (n) ->
  width = 4

  pad = (s, n=width, c=' ') ->
    s = s.toString()
    result = ''
    padding = n - s.length
    while result.length < padding
      result += c
    result + s

  s = pad('') + '|'
  for i in [1..n]
    s += pad i
  console.log s

  s = pad('', width, '-') + '+'
  for i in [1..n]
    s += pad '', width, '-'
  console.log s

  for i in [1..n]
    s = pad i
    s += '|'
    s += pad '', width*(i - 1)
    for j in [i..n]
       s += pad i*j
    console.log s

print_multiplication_tables 12


void main() {
    import std.stdio, std.array, std.range, std.algorithm;

    enum n = 12;
    writefln("    %(%4d%)\n%s", iota(1, n+1), "-".replicate(4*n + 4));
    foreach (immutable y; 1 .. n + 1)
        writefln("%4d" ~ " ".replicate(4 * (y - 1)) ~ "%(%4d%)", y,
                 iota(y, n + 1).map!(x => x * y));
}


$ max = 12
$ h = f$fao( "!4* " )
$ r = 0
$ loop1:
$  o = ""
$  c = 0
$  loop2:
$   if r .eq. 0 then $ h = h + f$fao( "!4SL", c )
$   p = r * c
$   if c .ge. r
$   then
$    o = o + f$fao( "!4SL", p )
$   else
$    o = o + f$fao( "!4* " )
$   endif
$   c = c + 1
$   if c .le. max then $ goto loop2
$  if r .eq. 0
$  then
$   write sys$output h
$   n = 4 * ( max + 2 )
$   write sys$output f$fao( "!''n*-" )
$  endif
$  write sys$output f$fao( "!4SL", r ) + o
$  r = r + 1
$  if r .le. max then $ goto loop1


program MultiplicationTables;

{$APPTYPE CONSOLE}

uses SysUtils;

const
  MAX_COUNT = 12;
var
  lRow, lCol: Integer;
begin
  Write('  | ');
  for lRow := 1 to MAX_COUNT do
    Write(Format('%4d', [lRow]));
  Writeln('');
  Writeln('--+-' + StringOfChar('-', MAX_COUNT * 4));
  for lRow := 1 to MAX_COUNT do
  begin
    Write(Format('%2d', [lRow]));
    Write('| ');
    for lCol := 1 to MAX_COUNT do
    begin
      if lCol < lRow then
        Write('    ')
      else
        Write(Format('%4d', [lRow * lCol]));
    end;
    Writeln;
  end;
end.


/* Print N-by-N multiplication table */
proc nonrec multab(byte n) void:
    byte i,j;

    /* write header */
    write("    |");
    for i from 1 upto n do write(i:4) od;
    writeln();
    write("----+");
    for i from 1 upto n do write("----") od;
    writeln();

    /* write lines */
    for i from 1 upto n do
        write(i:4, "|");
        for j from 1 upto n do
            if i <= j then write(i*j:4)
            else write("    ")
            fi
        od;
        writeln()
    od
corp

/* Print 12-by-12 multiplication table */
proc nonrec main() void: multab(12) corp


const size = 12;
var row, col : Integer;

Print('  | ');
for row:=1 to size do
   Print(Format('%4d', [row]));
PrintLn('');
PrintLn('--+-'+StringOfChar('-', size*4));
for row:=1 to size do begin
   Print(Format('%2d', [row]));
   Print('| ');
   for col:=1 to size do begin
      if col<row then
         Print('    ')
      else Print(Format('%4d', [row*col]));
   end;
   PrintLn('');
end;


  def size := 12
  println(`{|style="border-collapse: collapse; text-align: right;"`)
  println(`|`)
  for x in 1..size {
    println(`|style="border-bottom: 1px solid black; " | $x`)
  }
  for y in 1..size {
    println(`|-`)
      println(`|style="border-right: 1px solid black;" | $y`)
    for x in 1..size {
      println(`|  ${if (x >= y) { x*y } else {""}}`)
    }
  }
  println("|}")


n = 12
func out h . .
  if h < 10
    write "  "
  elif h < 100
    write " "
  .
  write " "
  write h
.
write "     "
for i = 1 to n
  call out i
.
print ""
write "     "
for i = 1 to n
  write "----"
.
print ""
for i = 1 to n
  call out i
  write "|"
  for j = 1 to n
    if j < i
      write "    "
    else
      call out i * j
    .
  .
  print ""
.


(lib 'matrix)

(define (mtable i j)
    (cond
    ((and (zero? i) (zero? j)) "😅")
    ((= i 0) j)
    ((= j 0) i)
    ((>= j i ) (* i j ))
    (else " ")))

(array-print (build-array 13 13 mtable))


defmodule RC do
  def multiplication_tables(n) do
    IO.write " X |"
    Enum.each(1..n, fn i -> :io.fwrite("~4B", [i]) end)
    IO.puts "\n---+" <> String.duplicate("----", n)
    Enum.each(1..n, fn j ->
      :io.fwrite("~2B |", [j])
      Enum.each(1..n, fn i ->
        if i<j, do: (IO.write "    "), else: :io.fwrite("~4B", [i*j])
      end)
      IO.puts ""
    end)
  end
end

RC.multiplication_tables(12)


-module( multiplication_tables ).

-export( [print_upto/1, task/0, upto/1] ).

print_upto( N ) ->
	Upto_tuples = [{X, {Y, Sum}} || {X, Y, Sum} <- upto(N)],
	io:fwrite( "  " ),
	[io:fwrite( "~5B", [X]) || X <- lists:seq(1, N)],
	io:nl(),
	io:nl(),
	[print_upto(X, proplists:get_all_values(X, Upto_tuples)) || X <- lists:seq(1, N)].

task() -> print_upto( 12 ).

upto( N ) -> [{X, Y, X*Y} || X <- lists:seq(1, N), Y <- lists:seq(1, N), Y >= X].

print_upto( N, Uptos ) ->
	io:fwrite( "~2B", [N] ),
	io:fwrite( "~*s", [5*(N - 1), " "] ),
	[io:fwrite("~5B", [Sum]) || {_Y, Sum} <- Uptos],
	io:nl().


puts(1," x")
for i = 1 to 12 do
    printf(1," %3d",i)
end for

puts(1,'\n')

for i = 1 to 12 do
  printf(1,"%2d",i)
  for j = 1 to 12 do
    if j<i then
      puts(1,"    ")
    else
      printf(1," %3d",i*j)
    end if
  end for
  puts(1,'\n')
end for


FNOVERHALFCARTESIANPRODUCT
=LAMBDA(f,
    LAMBDA(n,
        LET(
            ixs, SEQUENCE(n, n, 1, 1),

            REM, "1-based indices.",
            x, 1 + MOD(ixs - 1, n),
            y, 1 + QUOTIENT(ixs - 1, n),

            IF(x >= y,
                f(x)(y),
                ""
            )
        )
    )
)


open System

let multTable () =
    Console.Write (" X".PadRight (4))
    for i = 1 to 12 do Console.Write ((i.ToString "####").PadLeft 4)
    Console.Write "\n ___"
    for i = 1 to 12 do Console.Write " ___"
    Console.WriteLine ()
    for row = 1 to 12 do
        Console.Write (row.ToString("###").PadLeft(3).PadRight(4))
        for col = 1 to 12 do
            if row <= col then Console.Write ((row * col).ToString("###").PadLeft(4))
            else
                Console.Write ("".PadLeft 4)
        Console.WriteLine ()
    Console.WriteLine ()
    Console.ReadKey () |> ignore

multTable ()


USING: io kernel math math.parser math.ranges sequences ;
IN: multiplication-table

: print-row ( n -- )
    [ number>string 2 CHAR: space pad-head write " |" write ]
    [ 1 - [ "    " write ] times ]
    [
        dup 12 [a,b]
        [ * number>string 4 CHAR: space pad-head write ] with each
    ] tri nl ;

: print-table ( -- )
    "    " write
    1 12 [a,b] [ number>string 4 CHAR: space pad-head write ] each nl
    "   +" write
    12 [ "----" write ] times nl
    1 12 [a,b] [ print-row ] each ;


class Main
{
  static Void multiplicationTable (Int n)
  {
    // print column headings
    echo ("    |" + (1..n).map |Int a -> Str| { a.toStr.padl(4)}.join("") )
    echo ("-----" + (1..n).map { "----" }.join("") )
    // work through each row
    (1..n).each |i|
    {
      echo ( i.toStr.padl(4) + "|" +
             Str.spaces(4*(i-1)) +
             (i..n).map |Int j -> Str| { (i*j).toStr.padl(4)}.join("") )
    }
  }

  public static Void main ()
  {
    multiplicationTable (12)
  }
}


: multiplication-table
  cr 2 spaces  13 2 do i 4 u.r loop
  cr
  13 2 do
    cr i 2 u.r
    13 2 do
      i j < if 4 spaces else i j * 4 u.r then
    loop
  loop ;


' FB 1.05.0 Win64

Print "  X|";
For i As Integer = 1 To 12
  Print Using "####"; i;
Next

Print
Print "---+"; String(48, "-")

For i As Integer = 1 To 12
  Print Using "###"; i;
  Print"|"; Spc(4 * (i - 1));
  For j As Integer = i To 12
    Print Using "####"; i * j;
  Next j
  Print
Next i

Print
Print "Press any key to quit"
Sleep


a = makeArray[[13,13], {|a,b| a==0 ? b : (b==0 ? a : (a<=b ? a*b : ""))}]
formatTable[a,"right"]


'Code 'stolen' from Free Basic and altered to work in Gambas

Public Sub Main()
Dim i, j As Integer

Print "  X|";
For i = 1 To 12
  Print Format(i, "####");
Next

Print
Print "---+"; String(48, "-")

For i = 1 To 12
  Print Format(i, "###");
  Print "|"; Space(4 * (i - 1));
  For j = i To 12
    Print Format(i * j, "####");
  Next
  Print
Next

End


package main

import (
    "fmt"
)

func main() {
    fmt.Print(" x |")
    for i := 1; i <= 12; i++ {
        fmt.Printf("%4d", i)
    }
    fmt.Print("\n---+")
    for i := 1; i <= 12; i++ {
        fmt.Print("----")
    }
    for j := 1; j <= 12; j++ {
        fmt.Printf("\n%2d |", j)
        for i := 1; i <= 12; i++ {
            if i >= j {
                fmt.Printf("%4d", i*j)
            } else {
                fmt.Print("    ")
            }
        }
    }
    fmt.Println("")
}


def printMultTable = { size = 12 ->
    assert size > 1

    // factor1 line
    print '  |'; (1..size).each { f1 -> printf('%4d', f1) }; println ''

    // dividing line
    print '--+'; (1..size).each { printf('----', it) }; println ''

    // factor2 result lines
    (1..size).each { f2 ->
        printf('%2d|', f2)
        (1..<f2).each{ print '    ' }
        (f2..size).each{ f1 -> printf('%4d', f1*f2) }
        println ''
    }
}

printMultTable()


10  ' Multiplication Tables
20  LET N% = 12
30  FOR J% = 1 TO N% - 1
40   PRINT USING "###"; J%;
50   PRINT " ";
60  NEXT J%
70  PRINT USING "###"; N%
80  FOR J% = 0 TO N% - 1
90   PRINT "----";
100 NEXT J%
110 PRINT "+"
120 FOR I% = 1 TO N%
130  FOR J% = 1 TO N%
140   IF J% < I% THEN PRINT "    "; ELSE PRINT USING "###"; I% * J%;: PRINT " ";
150  NEXT J%
160  PRINT "| "; USING "##"; I%
170 NEXT I%


import Data.Maybe (fromMaybe, maybe)

------------------- MULTIPLICATION TABLE -----------------

mulTable :: [Int] -> [[Maybe Int]]
mulTable xs =
  (Nothing : labels) :
  zipWith
    (:)
    labels
    [[upperMul x y | y <- xs] | x <- xs]
  where
    labels = Just <$> xs
    upperMul x y
      | x > y = Nothing
      | otherwise = Just (x * y)

--------------------------- TEST -------------------------
main :: IO ()
main =
  putStrLn . unlines $
    showTable . mulTable
      <$> [ [13 .. 20],
            [1 .. 12],
            [95 .. 100]
          ]

------------------------ FORMATTING ----------------------
showTable :: [[Maybe Int]] -> String
showTable xs = unlines $ head rows : [] : tail rows
  where
    w = succ $ (length . show) (fromMaybe 0 $ (last . last) xs)
    gap = replicate w ' '
    rows = (maybe gap (rjust w ' ' . show) =<<) <$> xs
    rjust n c = (drop . length) <*> (replicate n c <>)


fun format n l
  let n tostr n
  while len n < l; let n (" " + n); endwhile
  return n
endfun

print   "   |"
for let i 1; i <= 12; i++; print format i 4; endfor
print "\n --+"
for let i 1; i <= 12; i++; print "----"; endfor
println ""
for let i 1; i <= 12; i++
  print format i 3 + "|"
  for let j 1; j <= 12; j++
    if j < i; print "    "
    else print format (i * j) 4; endif
  endfor
  println ""
endfor


WRITE(Row=1) " x   1   2   3   4   5   6   7   8   9  10  11  12"
DO line = 1, 12
  WRITE(Row=line+2, Format='i2') line
  DO col = line, 12
    WRITE(Row=line+2, Column=4*col, Format='i3') line*col
  ENDDO
ENDDO


procedure main()
lim := 13
wid :=  5
every writes(right("* |" | (1 to lim) | "\n",wid)|right("\n",wid*(lim+1),"_"))         # header row and separator
every (i := 1 to lim) &
   writes(right( i||" |" | (j := 1 to lim, if j < i then "" else i*j) | "\n",wid))     # table content and triangle
end


   multtable=: <:/~ * */~
   format=: 'b4.0' 8!:2 ]
   (('*' ; ,.) ,. ({. ; ])@[email protected]) >:i.12
┌──┬────────────────────────────────────────────────┐
│* │   1   2   3   4   5   6   7   8   9  10  11  12│
├──┼────────────────────────────────────────────────┤
│ 1│   1   2   3   4   5   6   7   8   9  10  11  12│
│ 2│       4   6   8  10  12  14  16  18  20  22  24│
│ 3│           9  12  15  18  21  24  27  30  33  36│
│ 4│              16  20  24  28  32  36  40  44  48│
│ 5│                  25  30  35  40  45  50  55  60│
│ 6│                      36  42  48  54  60  66  72│
│ 7│                          49  56  63  70  77  84│
│ 8│                              64  72  80  88  96│
│ 9│                                  81  90  99 108│
│10│                                     100 110 120│
│11│                                         121 132│
│12│                                             144│
└──┴────────────────────────────────────────────────┘


public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 12; i++)
            System.out.print("\t" + i);

        System.out.println();
        for (int i = 0; i < 100; i++)
            System.out.print("-");
        System.out.println();
        for (int i = 1; i <= 12; i++) {
            System.out.print(i + "|");
            for(int j = 1; j <= 12; j++) {
                System.out.print("\t");
                if (j >= i)
                    System.out.print("\t" + i * j);
            }
            System.out.println();
        }
    }
}


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<title>12 times table</title>


/* Multiplication tables, is Jsish */
var m, n, tableSize = 12;

if (console.args.length > 0) tableSize = parseInt(console.args[0]);
if (tableSize < 1 || tableSize > 20) tableSize = 12;

var width = String(tableSize * tableSize).length;
var spaces = ' '.repeat(width+1);

printf(spaces);
for (m = 1; m <= tableSize; m++) printf(' %*d', width, m);
printf('\n' + ' '.repeat(width) + '+');
printf('-'.repeat((width+1) * tableSize));
for (m = 1; m <= tableSize; m++) {
    printf('\n%*d|', width, m);
    for (n = m; n < m; n++) printf(spaces);
    for (n = 1; n <= tableSize; n++) {
        if (m <= n) printf(' %*d', width, m * n); else printf(spaces);
    }
}
printf('\n');


// version 1.0.6

fun main(args: Array<String>) {
    print("  x|")
    for (i in 1..12) print("%4d".format(i))
    println("\n---+${"-".repeat(48)}")
    for (i in 1..12) {
        print("%3d".format(i) +"|${" ".repeat(4 * i - 4)}")
        for (j in i..12) print("%4d".format(i * j))
        println()
    }
}


{def format
 {lambda {:w :c}
  {@ style="width::wpx;
            color::c;
            text-align:right;"
}}}
-> format

{def operation
 {lambda {:op :i :j}
  {if {and {= :i 0} {= :j 0}}                    // left top cell
   then {format 30 #fff}                         // is empty
   else {if {= :i 0}                             // top row
   then {format 30 #ff0}:j                       // is yellow
   else {if {= :j 0}                             // left col
   then {format 30 #0ff}:i                       // is cyan
   else {format 30 #ccc}                         // is lightgrey
        {if {<= :i :j} then {:op :i :j} else .}  // cell [i,j]
}}}}}
-> operation

{def make_table
 {lambda {:func :row :col}
  {table {@ style="box-shadow:0 0 8px #000;"}
   {S.map                                   // apply
    {{lambda {:func :col :j}                // function row
     {tr {S.map                             // apply
      {{lambda {:func :i :j}                // function cell
       {td {:func :i :j}}} :func :j}        // apply func on [i,j]
        {S.serie 0 :col}}}} :func :col}     // from 0 to col
         {S.serie 0 :row}                   // from 0 to row
}}}}
-> make_table

The following calls:

1) {make_table {operation +} 5 15}
2) {make_table {operation *} 12 12}
3) {make_table {operation pow} 6 10}


define printTimesTables(max::integer) => {
    local(result)  = ``
    local(padSize) = string(#max*#max)->size + 1

    // Print header row
    #result->append((' ' * #padSize) + '|')
    loop(#max) => {
        #result->append(loop_count->asString(-padding=#padSize))
    }
    #result->append("\n" + (`-` * #padSize) + '+' + (`-` * (#padSize * #max)))

    with left in 1 to #max do {
        // left column
        #result->append("\n" + #left->asString(-padding=#padSize) + '|')

        // Table results
        with right in 1 to #max do {
            #result->append(
                #right < #left
                    ? ' ' * #padSize
                    | (#left * #right)->asString(-padding=#padSize)
            )
        }
    }

    return #result
}

printTimesTables(12)


to mult.table :n
  type "|  | for [i 2 :n] [type form :i 4 0] (print)
  (print)
  for [i 2 :n] [
    type form :i 2 0
    for [j 2 :n] [
      type ifelse :i > :j ["|    |] [form :i*:j 4 0]
    ]
    (print)
  ]
end

mult.table 12


io.write( "   |" )
for i = 1, 12 do
    io.write( string.format( "%#5d", i ) )
end
io.write( "\n", string.rep( "-", 12*5+4 ), "\n" )

for i = 1, 12 do
    io.write( string.format( "%#2d |", i ) )

    for j = 1, 12 do
        if j < i then
            io.write( "     " )
        else
            io.write( string.format( "%#5d", i*j ) )
        end
    end
    io.write( "\n" )
end


Module CheckIt {
      Dim Base 1, A(12)
      Mult=lambda (n)-> {
            Flush  ' empty stack
            For i=1 to n : Data i*n : Next i
            =Array([])   ' copy stack in an array, and return a pointer
      }
      i=Each(A())
      Print "  |";
      while i {
            Print Format$("{0:0:-4}",i^+1);
            A(i^+1)=Mult(i^+1)
      }
      Print
      Print "--+"+string$("-",4*12)
      For i=1 to 12 {
            Print Format$("{0:0:-2}|",i);
            For j=1 to 12 {
                  If len(A(j)())>=i then {
                        Print Format$("{0:0:-4}",A(j)(i-1));
                  } Else Print "    ";
            }
            Print
      }
}
CheckIt


printf("    ");
for i to 12 do
	printf("%-3d   ", i);
end do;
printf("\n");
for i to 75 do
	printf("-");
end do;
for i to 12 do
	printf("\n%2d| ", i);
	for j to 12 do
		if j<i then
			printf("      ");
		else
			printf("%-3d   ", i * j);
		end if
	end do
end do


function table = timesTable(N)
    table = [(0:N); (1:N)' triu( kron((1:N),(1:N)') )];
end


for i: 1 thru 12 do (
  for j: 1 thru 12 do (
    if j>=i or j=1 then printf(true, "~4d", i*j) else printf(true, "    ")
    ),
  printf(true, "~%")
  );


n = 12
For j = 1 To n - 1
  TextWindow.CursorLeft = (j - 1) * 4 + (3 - Text.GetLength(j))
  TextWindow.Write(j)
  TextWindow.Write(" ")
EndFor
TextWindow.CursorLeft = (n - 1) * 4 + (3 - Text.GetLength(n))
TextWindow.Write(n)
TextWindow.WriteLine("")
For j = 0 To n - 1
  TextWindow.Write("----")
EndFor
TextWindow.WriteLine("+")
For i = 1 To n
  For j = 1 To n
    If j < i Then
      TextWindow.Write("    ")
    Else
      TextWindow.CursorLeft = (j - 1) * 4 + (3 - Text.GetLength(i * j))
      TextWindow.Write(i * j)
      TextWindow.Write(" ")
    EndIf
  EndFor
  TextWindow.Write("| ")
  TextWindow.CursorLeft = n * 4 + (4 - Text.GetLength(i))
  TextWindow.Write(i)
  TextWindow.WriteLine("")
EndFor


П0	КИП0	КИП4	КИП5	ИП4	ИП5	*	С/П
ИП5	ИП0	-	x=0	03
ИП4	ИП0	-	x#0	22	ИП4	П5	БП	02
С/П


MODULE MultiplicationTables;

FROM SWholeIO IMPORT
  WriteInt;
FROM STextIO IMPORT
  WriteString, WriteLn;

CONST
  N = 12;

VAR
  I, J: INTEGER;

BEGIN
  FOR J := 1 TO N - 1 DO
    WriteInt(J, 3);
    WriteString(" ");
  END;
  WriteInt(N, 3);
  WriteLn;
  FOR J := 0 TO N - 1 DO
    WriteString("----");
  END;
  WriteString("+");
  WriteLn;
  FOR I := 1 TO N DO
    FOR J := 1 TO N DO
      IF J < I THEN
        WriteString("    ");
      ELSE
        WriteInt(I * J, 3);
        WriteString(" ");
      END;
    END;
    WriteString("| ");
    WriteInt(I, 2);
    WriteLn;
  END;
END MultiplicationTables.


@verb me:@tables none none none rxd
@program me:@tables
player:tell("    |      1    2    3    4    5    6    7    8    9   10   11   12");
player:tell("-------------------------------------------------------------------");
for i in [1..12]
  line = ((i < 10) ? "  " | " ") + tostr(i) + " |  ";
  for j in [1..12]
    if (j >= i)
      product = i * j;
      "calculate spacing for right justification of values";
      if (product >= 100)
        spacer = "";
      elseif (product >= 10)
        spacer = " ";
      else
        spacer = "  ";
      endif
      line = line + "  " + spacer + tostr(product);
    else
      line = line + "     ";
    endif
  endfor
  player:tell(line);
endfor
.


MULTTABLE(SIZE)
 ;Print out a multiplication table
 ;SIZE is the size of the multiplication table to make
 ;MW is the maximum width of the numbers
 ;D is the down axis
 ;A is the across axis
 ;BAR is the horizontal bar under the operands
 NEW MW,D,A,BAR
 IF $DATA(SIZE)<1 SET SIZE=12
 SET MW=$LENGTH(SIZE*SIZE)
 SET BAR="" FOR I=1:1:(MW+2) SET BAR=BAR_"-"
 FOR D=1:1:(SIZE+2) DO
 .FOR A=1:1:(SIZE+1) DO
 ..WRITE:(D=1)&(A=1) !,$JUSTIFY("",MW-1)," X|"
 ..WRITE:(D=1)&(A>1) ?((A-1)*5),$JUSTIFY((A-1),MW)
 ..WRITE:(D=2)&(A=1) !,BAR
 ..WRITE:(D=2)&(A'=1) BAR
 ..WRITE:(D>2)&(A=1) !,$JUSTIFY((D-2),MW)," |"
 ..WRITE:((A-1)>=(D-2))&((D-2)>=1) ?((A-1)*5),$JUSTIFY((D-2)*(A-1),MW)
 KILL MW,D,A,BAR
 QUIT


/**
 Multiplication table, in Neko
 Tectonics:
   nekoc multiplication-table.neko
   neko multiplication-table
*/

var sprintf = $loader.loadprim("[email protected]", 2);

var i, j;

i = 1;
$print("  X |");
while i < 13 {
  $print(sprintf("%4d", i));
  i += 1;
}
$print("\n");
$print(" ---+");
i = 1;
while i < 13 {
  $print("----");
  i += 1;
}
$print("\n");

j = 1;
while j < 13 {
  $print(sprintf("%3d", j));
  $print(" |");
  i = 1;
  while i < 13 {
    if j > i {
      $print("    ");
    } else {
      $print(sprintf("%4d", i*j));
    }
    i += 1;
  }
  $print("\n");
  j += 1;
}


import strfmt

const n = 12

for j in 1..n:
  stdout.write "{:3d}{:s}".fmt(j, if n-j>0: " " else: "\n")
for j in 0..n:
  stdout.write if n-j>0: "----" else: "+\n"
for i in 1..n:
  for j in 1..n:
    stdout.write if j<i: "    " else: "{:3d} ".fmt(i*j)
  echo "| {:2d}".fmt(i)


let () =
  let max = 12 in
  let fmax = float_of_int max in

  let dgts = int_of_float (ceil (log10 (fmax *. fmax))) in
  let fmt = Printf.printf " %*d" dgts in
  let fmt2 = Printf.printf "%*s%c" dgts in

  fmt2 "" 'x';
  for i = 1 to max do fmt i done;
  print_string "\n\n";

  for j = 1 to max do
    fmt j;
    for i = 1 to pred j do fmt2 "" ' '; done;
    for i = j to max do fmt (i*j); done;
    print_newline()
  done;
  print_newline()


our $max = 12;
our $width = length($max**2) + 1;

printf "%*s", $width, $_ foreach 'x|', 1..$max;
print "\n", '-' x ($width - 1), '+', '-' x ($max*$width), "\n";
foreach my $i (1..$max) {
	printf "%*s", $width, $_
            foreach "$i|", map { $_ >= $i and $_*$i } 1..$max;
	print "\n";
}


printf(1,"  | ")
for col=1 to 12 do
    printf(1,"%4d",col)
end for
printf(1,"\n--+-"&repeat('-',12*4))
for row=1 to 12 do
    printf(1,"\n%2d| ",row)
    for col=1 to 12 do
        printf(1,iff(col<row?"    ":sprintf("%4d",row*col)))
    end for
end for


go =>
  N=12,
  make_table(N),
  nl.

%
% Make a table of size N
%
make_table(N) =>
  printf("     "),
  foreach(I in 1..N) printf("%4w", I) end,
  nl,
  println(['-' : _ in 1..(N+1)*4+1]),
  foreach(I in 1..N)
    printf("%2d | ", I),
    foreach(J in 1..N)
      if J>=I then
        printf("%4w", I*J)
      else
        printf("    ")
      end
    end,
    nl
  end,
  nl.


sp>(de mulTable (N)
   (space 4)
   (for X N
      (prin (align 4 X)) )
   (prinl)
   (prinl)
   (for Y N
      (prin (align 4 Y))
      (space (* (dec Y) 4))
      (for (X Y (>= N X) (inc X))
         (prin (align 4 (* X Y))) )
      (prinl) ) )

(mulTable 12)


/* 12 x 12 multiplication table. */

multiplication_table: procedure options (main);
   declare (i, j) fixed decimal (2);

   put skip edit ((i do i = 1 to 12)) (X(4), 12 F(4));
   put skip edit ( (49)'_') (X(3), A);

   do i = 1 to 12;
      put skip edit (i, ' |', (i*j do j = i to 12))
         (F(2), a, col(i*4+1), 12 F(4));
   end;

end multiplication_table;


#  For clarity
$Tab = "`t"

#  Create top row
$Tab + ( 1..12 -join $Tab )

#  For each row
ForEach ( $i in 1..12 )
    {
    $(  #  The number in the left column
        $i

        #  An empty slot for the bottom triangle
        @( "" ) * ( $i - 1 )

        #  Calculate the top triangle
        $i..12 | ForEach { $i * $_ }

        #  Combine them all together
        ) -join $Tab
    }


make_table(S,E) :-
	print_header(S,E),
	make_table_rows(S,E),
	fail.
make_table(_,_).

print_header(S,E) :-
	nl,
	write('      '),
	forall(between(S,E,X), print_num(X)),
	nl,
	Sp is E * 4 + 2,
	write('    '),
	forall(between(1,Sp,_), write('-')).

make_table_rows(S,E) :-
	between(S,E,N),
	nl,
	print_num(N), write(': '),
	between(S,E,N2),
	X is N * N2,
	print_row_item(N,N2,X).

print_row_item(N, N2, _) :-
	N2 < N,
	write('    ').
print_row_item(N, N2, X) :-
	N2 >= N,
	print_num(X).

print_num(X) :- X < 10,	          format('   ~p', X).
print_num(X) :- between(10,99,X), format('  ~p', X).
print_num(X) :- X > 99,	          format(' ~p', X).


Procedure PrintMultiplicationTable(maxx, maxy)
  sp       = Len(Str(maxx*maxy)) + 1
  trenner$ =  "+"
  For l1 = 1 To maxx + 1
    For l2 = 1 To sp
      trenner$ + "-"
    Next
    trenner$ + "+"
  Next
  header$ = "|" + RSet("x", sp) + "|"
  For a = 1 To maxx
    header$ + RSet(Str(a), sp)
    header$ + "|"
  Next
  PrintN(trenner$)
  PrintN(header$)
  PrintN(trenner$)
  For y = 1 To maxy
    line$ = "|" + RSet(Str(y), sp) + "|"
    For x = 1 To maxx
      If x >= y
        line$ + RSet(Str(x*y), sp)
      Else
        line$ + Space(sp)
      EndIf
      line$ + "|"
    Next
    PrintN(line$)
  Next
  PrintN(trenner$)
EndProcedure

OpenConsole()
PrintMultiplicationTable(12, 12)
Input()


  [ swap number$
    tuck size -
    times sp echo$ ] is echo-rj ( n n --> )

  say "  * |"
  12 times [ i^ 1+ 4 echo-rj ] cr
  say " ---+"
  char - 48 of echo$ cr
  [ 12 times
     [ i^ 1+
       dup 3 echo-rj
       say " |"
      12 times
        [ i^ 1+
          2dup > iff
            [ drop 4 times sp ]
          else
            [ dip dup
              * 4 echo-rj ] ]
       cr drop ] ]


multiplication_table <- function(n=12)
{
   one_to_n <- 1:n
   x <- matrix(one_to_n) %*% t(one_to_n)
   x[lower.tri(x)] <- 0
   rownames(x) <- colnames(x) <- one_to_n
   print(as.table(x), zero.print="")
   invisible(x)
}
multiplication_table()


#lang racket

(define (show-line xs)
  (for ([x xs]) (display (~a x #:width 4 #:align 'right)))
  (newline))

(show-line (cons "" (range 1 13)))
(for ([y (in-range 1 13)])
  (show-line (cons y (for/list ([x (in-range 1 13)])
                       (if (<= y x) (* x y) "")))))


rebol [
	Title: "12x12 Multiplication Table"
	URL: http://rosettacode.org/wiki/Print_a_Multiplication_Table
]

size: 12

; Because of REBOL's GUI focus, it doesn't really do pictured output,
; so I roll my own. See Formatted_Numeric_Output for more
; comprehensive version:

pad: func [pad n][
    n: to-string n
    insert/dup n " " (pad - length? n)
    n
]
p3: func [v][pad 3 v]  ; A shortcut, I hate to type...

--: has [x][repeat x size + 1 [prin "+---"]  print "+"]  ; Special chars OK.

.row: func [label y /local row x][
	row: reduce ["|" label "|"]
	repeat x size [append row reduce [either x < y ["   "][p3 x * y] "|"]]
	print rejoin row
]

--  .row " x " 1  --  repeat y size [.row  p3 y  y]  --

print rejoin [ crlf  "What about "  size: 5  "?"  crlf ]
--  .row " x " 1  --  repeat y size [.row  p3 y  y]  --

print rejoin [ crlf  "How about "  size: 20  "?"  crlf ]
--  .row " x " 1  --  repeat y size [.row  p3 y  y]  --


/*REXX program displays a  NxN  multiplication table  (in a boxed grid) to the terminal.*/
parse arg sz .                                   /*obtain optional argument from the CL.*/
if sz=='' | sz==","  then sz= 12                 /*Not specified?  Then use the default.*/
w= max(3, length(sz**2) );    __= copies('─', w) /*calculate the width of the table cell*/
                             ___= __'──'         /*literals used in the subroutines.    */
        do r=1  for sz                           /*calculate & format a row of the table*/
        if r==1  then call top left('│(x)', w+1) /*show title of multiplication table.  */
        $= '│'center(r"x", w)"│"                 /*index for a multiplication table row.*/
               do c=1  for sz;     prod=         /*build a row of multiplication table. */
               if r<=c  then prod= r * c         /*only display when the  row ≤ column. */
               $= $  ||  right(prod,  w+1) '|'   /*append product to a cell in the row. */
               end   /*k*/
        say $                                    /*show a row of multiplication table.  */
        if r\==sz  then call sep                 /*show a separator except for last row.*/
        end          /*j*/
call bot                                         /*show the bottom line of the table.   */
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
hdr: $= ?'│';   do i=1  for sz; $=$ || right(i"x|", w+3);  end;  say $;   call sep; return
dap: $= left($, length($) - 1)arg(1);                                               return
top: $= '┌'__"┬"copies(___'┬', sz);  call dap "┐";  ?= arg(1);   say $;   call hdr; return
sep: $= '├'__"┼"copies(___'┼', sz);  call dap "┤";               say $;             return
bot: $= '└'__"┴"copies(___'┴', sz);  call dap "┘";               say $;             return


multiplication_table(12)
func multiplication_table n
  nSize = 4   See "    |   "
  for t = 1 to n see  fsize(t, nSize) next
  see nl + "----+-" + copy("-", nSize*n) + nl
  for t1 = 1 to n
     see fsize(t1, nSize) + "|   "
     for t2 = 1 to n if t2 >= t1 see  fsize(t1*t2,nSize) else see copy(" ", nSize) ok next
     see nl
  next
func fsize x,n return string(x) + copy(" ",n-len(string(x)))


def multiplication_table(n)
  puts "    |" + (" %3d" * n) % [*1..n]
  puts "----+" + "----" * n
  1.upto(n) do |x|
    print "%3d |" % x
    1.upto(x-1) {|y| print "    "}
    x.upto(n)   {|y| print " %3d" % (x*y)}
    puts
  end
end

multiplication_table 12


html "

123456789101112
"
For i = 1 To 12
	html "
";i;"	"
	For ii = 1 To 12
		html ""
		If ii >= i Then   html i * ii
		html "	"
	Next ii
next i
html "
"


const LIMIT: i32 = 12;

fn main() {
    for i in 1..LIMIT+1 {
        print!("{:3}{}", i, if LIMIT - i == 0 {'\n'} else {' '})
    }
    for i in 0..LIMIT+1 {
        print!("{}", if LIMIT - i == 0 {"+\n"} else {"----"});
    }

    for i in 1..LIMIT+1 {
        for j in 1..LIMIT+1 {
            if j < i {
                print!("    ")
            } else {
                print!("{:3} ", j * i)
            }
        }
        println!("| {}", i);
    }
}


//Multiplication Table
print("%5s".format("|"))
for (i <- 1 to 12) print("%5d".format(i))
println()
println("-----" * 13)

for (i <- 1 to 12) {
  print("%4d|".format(i))

  for (j <- 1 to 12) {
    if (i <= j)
      print("%5d".format(i * j))
    else
      print("%5s".format(""))
  }

  println("")
}


(define iota
  (lambda (count start step)
    (let loop ((result (list (+ start (* (- count 1) step)))))
      (let ((acc (car result)))
        (if (= acc start)
            result
            (loop (cons (- acc step) result)))))))

(define table
  (lambda (x)
    (let loop ((count 1)
               (numbers (iota x 1 1)))
      (if (not (null? numbers))
          (begin
            (display (make-string (* 6 (- count 1)) #\space))
            (for-each
             (lambda (n)
               (let ((number (number->string (* n count))))
                 (display (string-append
                           (make-string (- 6 (string-length number)) #\space)
                           number))))
             numbers)
            (newline)
            (loop (+ count 1)
                  (cdr numbers)))))))


    nmax=12, xx=3
    s= blanks(xx)+" |"
    for j=1:nmax
        s=s+part(blanks(xx)+string(j),$-xx:$)
    end
    printf("%s\n",s)
    s=strncpy("-----",xx)+" +"
    for j=1:nmax
        s=s+" "+strncpy("-----",xx)
    end
    printf("%s\n",s)
    for i=1:nmax
        s=part(blanks(xx)+string(i),$-xx+1:$)+" |"
        for j = 1:nmax
            if j >= i then
                s=s+part(blanks(xx)+string(i*j),$-xx:$)
            else
                s=s+blanks(xx+1)
	    end
        end
        printf("%s\n",s)
    end


$ include "seed7_05.s7i";

const proc: main is func
  local
    const integer: n is 12;
    var integer: i is 0;
    var integer: j is 0;
  begin
    for j range 1 to n do
      write(j lpad 3 <& " ");
    end for;
    writeln;
    writeln("-" mult 4 * n);
    for i range 1 to n do
      for j range 1 to n do
        if j < i then
          write("    ");
        else
          write(i * j lpad 3 <& " ");
        end if;
      end for;
      writeln("|" <& i lpad 3);
    end for;
  end func;


var max = 12
var width = (max**2 -> len+1)

func fmt_row(*items) {
    items.map {|s| "%*s" % (width, s) }.join
}

say fmt_row('x┃', (1..max)...)
say "#{'━' * (width - 1)}╋#{'━' * (max * width)}"

{ |i|
    say fmt_row("#{i}┃", {|j| i <= j ? i*j : ''}.map(1..max)...)
} << 1..max


begin
    integer i, j;
    outtext( "    " );
    for i := 1 step 1 until 12 do outint( i, 4 );
    outimage;
    outtext( "   +" );
    for i := 1 step 1 until 12 do outtext( "----" );
    outimage;
    for i := 1 step 1 until 12 do
    begin
        outint( i, 3 );
        outtext( "|" );
        for j := 1 step 1 until i - 1 do outtext( "    " );
        for j := i step 1 until 12 do outint( i * j, 4 );
        outimage
    end;
end


import Foundation

let size = 12

func printRow(with:Int, upto:Int) {

    print(String(repeating: " ", count: (with-1)*4), terminator: "")

    for i in with...upto {
            print(String(format: "%l4d", i*with), terminator: "")
    }
    print()
}

print("    ", terminator: ""); printRow( with: 1, upto: size)
print( String(repeating: "–", count: (size+1)*4 ))
for i in 1...size {
    print(String(format: "%l4d",i), terminator:"")
    printRow( with: i, upto: size)
 }


$$ MODE TUSCRIPT
x=y="1'2'3'4'5'6'7'8'9'10'11'12"
LOOP n,col=x,cnt=""
 skip=n-1
 LOOP m,row=y
  IF (m==skip) THEN
   td=""
  ELSE
   td=col*row
   coleqrow=col*n
   IF (td.lt.#coleqrow) td=""
  ENDIF
 td=CENTER (td,+3," ")
 cnt=APPEND (cnt,td," ")
 ENDLOOP
 col=CENTER (col,+3," ")
 PRINT col,cnt
ENDLOOP


// Multiplication tables

function intToString(n: number, wdth: number): string {
  sn = Math.floor(n).toString();
  len = sn.length;
  return (wdth < len ? "#".repeat(wdth) : " ".repeat(wdth - len) + sn);
}

var n = 12;
console.clear();
for (j = 1; j < n; j++)
  process.stdout.write(intToString(j, 3) + " ");
console.log(intToString(n, 3));
console.log("----".repeat(n) + "+");
for (i = 1; i <= n; i++) {
  for (j = 1; j <= n; j++)
    process.stdout.write(j < i ? "    " : intToString(i * j, 3) + " ");
  console.log("| " + intToString(i, 2));
}


For R = 1 To 12
  Print R;Tab(R * 5);
  For C = R To 12
    Print Using "_____";R * C;
  Next
  Print
Next


#import std
#import nat

table "n" =

~&plrTS(
   ~&xS pad` @xS <'x  ','--'>-- --' | '*hS %nP* nrange/1 "n",
   ^CthPiC(`-!*h,~&) mat` *xSSK7 pad` *K7ihxPBSS (~&i&& %nP)** nleq&&product**iiK0lK2x nrange/1 "n")

#show+

main = table 12


Option Explicit

Sub Multiplication_Tables()
Dim strTemp As String, strBuff As String
Dim i&, j&, NbDigits As Byte

'You can adapt the following const :
Const NB_END As Byte = 12

    Select Case NB_END
        Case Is < 10: NbDigits = 3
        Case 10 To 31: NbDigits = 4
        Case 31 To 100: NbDigits = 5
        Case Else: MsgBox "Number too large": Exit Sub
    End Select
    strBuff = String(NbDigits, " ")

    For i = 1 To NB_END
        strTemp = Right(strBuff & i, NbDigits)
        For j = 2 To NB_END
            If j < i Then
                strTemp = strTemp & strBuff
            Else
                strTemp = strTemp & Right(strBuff & j * i, NbDigits)
            End If
        Next j
        Debug.Print strTemp
    Next i
End Sub


Sub Main()
    Const nmax = 12, xx = 3
    Const x = xx + 1
    Dim i As Integer, j As Integer, s As String
    s = String(xx, " ") & " |"
    For j = 1 To nmax
        s = s & Right(String(x, " ") & j, x)
    Next j
    Debug.Print s
    s = String(xx, "-") & " +"
    For j = 1 To nmax
        s = s & " " & String(xx, "-")
    Next j
    Debug.Print s
    For i = 1 To nmax
        s = Right(String(xx, " ") & i, xx) & " |"
        For j = 1 To nmax
            If j >= i _
            Then s = s & Right(String(x, " ") & i * j, x) _
            Else s = s & String(x, " ")
        Next j
        Debug.Print s
    Next i
End Sub 'Main


PROGRAM "multiplicationtables"
VERSION "0.0001"

DECLARE FUNCTION Entry()

FUNCTION Entry()
  $N = 12
  FOR j@@ = 1 TO $N - 1
    PRINT FORMAT$("### ", j@@);
  NEXT j@@
  PRINT FORMAT$("###", $N)
  FOR j@@ = 0 TO $N - 1
    PRINT "----";
  NEXT j@@
  PRINT "+"
  FOR i@@ = 1 TO $N
    FOR j@@ = 1 TO $N
      IF j@@ < i@@ THEN
        PRINT "    ";
      ELSE
        PRINT FORMAT$("### ", i@@ * j@@);
      END IF
    NEXT j@@
    PRINT "|"; FORMAT$(" ##", i@@)
  NEXT i@@
END FUNCTION
END PROGRAM


include c:\cxpl\codes;
int X, Y;
[Format(4, 0);
Text(0, "    |");  for X:= 1 to 12 do RlOut(0, float(X));
CrLf(0);
Text(0, "  --+");  for X:= 1 to 12 do Text(0, "----");
CrLf(0);
for Y:= 1 to 12 do
    [RlOut(0, float(Y));  ChOut(0, ^|);
    for X:= 1 to 12 do
        if X>=Y then RlOut(0, float(X*Y)) else Text(0, " . .");
    CrLf(0);
    ];
]


fcn multiplicationTable(n){
   w,fmt := (n*n).numDigits, " %%%dd".fmt(w).fmt;  // eg " %3".fmt
   header:=[1..n].apply(fmt).concat();	   // 1  2  3  4 ...
   println(" x ", header, "\n   ", "-"*header.len());
   dash:=String(" "*w,"-");	// eg "   -"
   foreach a in ([1..n]){
      print("%2d|".fmt(a),dash*(a-1));
      [a..n].pump(String,'*(a),fmt).println();
   }
}(12);


-V BoardSize = 8

F underAttack(col, queens)
   I col C queens
      R 1B
   L(x) queens
      I abs(col - x) == queens.len - L.index
         R 1B
   R 0B

F solve(n)
   V result = [[Int]()]
   [[Int]] newSolutions
   L(row) 1 .. n
      L(solution) result
         L(i) 1 .. BoardSize
            I !underAttack(i, solution)
               newSolutions.append(solution [+] [i])
      swap(&result, &newSolutions)
      newSolutions.clear()
   R result

print(‘Solutions for a chessboard of size ’String(BoardSize)‘x’String(BoardSize))
print()

L(answer) solve(BoardSize)
   L(col) answer
      V row = L.index
      I row > 0
         print(‘ ’, end' ‘’)
      print(Char(code' ‘a’.code + row)‘’col, end' ‘’)
   print(end' I L.index % 4 == 3 {"\n"} E ‘      ’)