Compiler/lexical analyzer

The C and Python versions can be considered reference implementations.

;Related Tasks
* Syntax Analyzer task
* Code Generator task
* Virtual Machine Interpreter task
* AST Interpreter task

Solution:
// Input: command line argument of file to process or console input. A two or
// three character console input of digits followed by a new line will be
// checked for an integer between zero and twenty-five to select a fixed test
// case to run. Any other console input will be parsed.

// Code based on the Java version found here:
// https://rosettacode.org/mw/index.php?title=Compiler/lexical_analyzer&action=edit&section=22

// Class to halt the parsing with an exception.
class ParsingFailed(message: String): Exception(message)

// Enumerate class of tokens supported by this scanner.
enum class TokenType {
    Tk_End_of_input, Op_multiply,  Op_divide, Op_mod, Op_add, Op_subtract,
    Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,
    Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Kw_if,
    Kw_else, Kw_while, Kw_print, Kw_putc, Sy_LeftParen, Sy_RightParen,
    Sy_LeftBrace, Sy_RightBrace, Sy_Semicolon, Sy_Comma, Tk_Identifier,
    Tk_Integer, Tk_String;

    override fun toString() =
        listOf("End_of_input", "Op_multiply", "Op_divide", "Op_mod", "Op_add",
            "Op_subtract", "Op_negate", "Op_not", "Op_less", "Op_lessequal",
            "Op_greater", "Op_greaterequal", "Op_equal", "Op_notequal",
            "Op_assign", "Op_and", "Op_or", "Keyword_if", "Keyword_else",
            "Keyword_while", "Keyword_print", "Keyword_putc", "LeftParen",
            "RightParen", "LeftBrace", "RightBrace", "Semicolon", "Comma",
            "Identifier", "Integer", "String")[this.ordinal]
} // TokenType

// Data class of tokens returned by the scanner.
data class Token(val token: TokenType, val value: String, val line: Int,
        val pos: Int) {

    // Overridden method to display the token.
    override fun toString() =
        "%5d  %5d %-15s %s".format(line, pos, this.token,
            when (this.token) {
                TokenType.Tk_Integer, TokenType.Tk_Identifier ->
                    " %s".format(this.value)
                TokenType.Tk_String ->
                    this.value.toList().joinToString("", " \"", "\"") {
                        when (it) {
                            '\t' ->
                                "\\t"
                            '\n' ->
                                "\\n"
                            '\u000b' ->
                                "\\v"
                            '\u000c' ->
                                "\\f"
                            '\r' ->
                                "\\r"
                            '"' ->
                                "\\\""
                            '\\' ->
                                "\\"
                            in ' '..'~' ->
                                "$it"
                            else ->
                                "\\u%04x".format(it.code) } }
                else ->
                    "" } )
} // Token

// Function to display an error message and halt the scanner.
fun error(line: Int, pos: Int, msg: String): Nothing =
    throw ParsingFailed("(%d, %d) %s\n".format(line, pos, msg))

// Class to process the source into tokens with properties of the
// source string, the line number, the column position, the index
// within the source string, the current character being processed,
// and map of the keyword strings to the corresponding token type.
class Lexer(private val s: String) {
    private var line = 1
    private var pos = 1
    private var position = 0
    private var chr =
        if (s.isEmpty())
            ' '
        else
            s[0]
    private val keywords = mapOf<String, TokenType>(
        "if" to TokenType.Kw_if,
        "else" to TokenType.Kw_else,
        "print" to TokenType.Kw_print,
        "putc" to TokenType.Kw_putc,
        "while" to TokenType.Kw_while)

    // Method to retrive the next character from the source. Use null after
    // the end of our source.
    private fun getNextChar() =
        if (++this.position >= this.s.length) {
            this.pos++
            this.chr = '\u0000'
            this.chr
        } else {
            this.pos++
            this.chr = this.s[this.position]
            when (this.chr) {
                '\n' -> {
                    this.line++
                    this.pos = 0
                } // line
                '\t' ->
                    while (this.pos%8 != 1)
                        this.pos++
            } // when
            this.chr
        } // if

    // Method to return the division token, skip the comment, or handle the
    // error.
    private fun div_or_comment(line: Int, pos: Int): Token =
        if (getNextChar() != '*')
            Token(TokenType.Op_divide, "", line, pos);
        else {
            getNextChar() // Skip comment start
            outer@
            while (true)
                when (this.chr) {
                    '\u0000' ->
                        error(line, pos, "Lexer: EOF in comment");
                    '*' ->
                        if (getNextChar() == '/') {
                            getNextChar() // Skip comment end
                            break@outer
                        } // if
                    else ->
                        getNextChar()
                } // when
            getToken()
        } // if

    // Method to verify a character literal. Return the token or handle the
    // error.
    private fun char_lit(line: Int, pos: Int): Token {
        var c = getNextChar() // skip opening quote
        when (c) {
            '\'' ->
                error(line, pos, "Lexer: Empty character constant");
            '\\' ->
                c = when (getNextChar()) {
                    'n' ->
                        10.toChar()
                    '\\' ->
                        '\\'
                    '\'' ->
                        '\''
                    else ->
                        error(line, pos, "Lexer: Unknown escape sequence '\\%c'".
                            format(this.chr)) }
        } // when
        if (getNextChar() != '\'')
            error(line, pos, "Lexer: Multi-character constant")
        getNextChar() // Skip closing quote
        return Token(TokenType.Tk_Integer, c.code.toString(), line, pos)
    } // char_lit

    // Method to check next character to see whether it belongs to the token
    // we might be in the middle of. Return the correct token or handle the
    // error.
    private fun follow(expect: Char, ifyes: TokenType, ifno: TokenType,
            line: Int, pos: Int): Token =
        when {
            getNextChar() == expect -> {
                getNextChar()
                Token(ifyes, "", line, pos)
            } // matches
            ifno == TokenType.Tk_End_of_input ->
                error(line, pos,
                    "Lexer: %c expected: (%d) '%c'".format(expect,
                    this.chr.code, this.chr))
            else ->
                Token(ifno, "", line, pos)
        } // when

    // Method to verify a character string. Return the token or handle the
    // error.
    private fun string_lit(start: Char, line: Int, pos: Int): Token {
        var result = ""
        while (getNextChar() != start)
            when (this.chr) {
                '\u0000' ->
                    error(line, pos, "Lexer: EOF while scanning string literal")
                '\n' ->
                    error(line, pos, "Lexer: EOL while scanning string literal")
                '\\' ->
                    when (getNextChar()) {
                        '\\' ->
                            result += '\\'
                        'n' ->
                            result += '\n'
                        '"' ->
                            result += '"'
                        else ->
                            error(line, pos, "Lexer: Escape sequence unknown '\\%c'".
                                format(this.chr))
                    } // when
                else ->
                    result += this.chr
            } // when
        getNextChar() // Toss closing quote
        return Token(TokenType.Tk_String, result, line, pos)
    } // string_lit

    // Method to retrive an identifier or integer. Return the keyword
    // token, if the string matches one. Return the integer token,
    // if the string is all digits. Return the identifer token, if the
    // string is valid. Otherwise, handle the error.
    private fun identifier_or_integer(line: Int, pos: Int): Token {
        var is_number = true
        var text = ""
        while (this.chr in listOf('_')+('0'..'9')+('a'..'z')+('A'..'Z')) {
            text += this.chr
            is_number = is_number && this.chr in '0'..'9'
            getNextChar()
        } // while
        if (text.isEmpty())
            error(line, pos, "Lexer: Unrecognized character: (%d) %c".
                format(this.chr.code, this.chr))
        return when {
            text[0] in '0'..'9' ->
                if (!is_number)
                    error(line, pos, "Lexer: Invalid number: %s".
                        format(text))
                else {
                    val max = Int.MAX_VALUE.toString()
                    if (text.length > max.length || (text.length == max.length &&
                            max < text))
                        error(line, pos,
                            "Lexer: Number exceeds maximum value %s".
                            format(text))
                    Token(TokenType.Tk_Integer, text, line, pos)
                } // if
            this.keywords.containsKey(text) ->
                Token(this.keywords[text]!!, "", line, pos)
            else ->
                Token(TokenType.Tk_Identifier, text, line, pos) }
    } // identifier_or_integer

    // Method to skip whitespace both C's and Unicode ones and retrive the next
    // token.
    private fun getToken(): Token {
        while (this.chr in listOf('\t', '\n', '\u000b', '\u000c', '\r', ' ') ||
                this.chr.isWhitespace())
            getNextChar()
        val line = this.line
        val pos = this.pos
        return when (this.chr) {
            '\u0000' ->
                Token(TokenType.Tk_End_of_input, "", line, pos)
            '/' ->
                div_or_comment(line, pos)
            '\'' ->
                char_lit(line, pos)
            '<' ->
                follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos)
            '>' ->
                follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos)
            '=' ->
                follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos)
            '!' ->
                follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos)
            '&' ->
                follow('&', TokenType.Op_and, TokenType.Tk_End_of_input, line, pos)
            '|' ->
                follow('|', TokenType.Op_or, TokenType.Tk_End_of_input, line, pos)
            '"' ->
                string_lit(this.chr, line, pos)
            '{' -> {
                getNextChar()
                Token(TokenType.Sy_LeftBrace, "", line, pos)
            } // open brace
            '}' -> {
                getNextChar()
                Token(TokenType.Sy_RightBrace, "", line, pos)
            } // close brace
            '(' -> {
                getNextChar()
                Token(TokenType.Sy_LeftParen, "", line, pos)
            } // open paren
            ')' -> {
                getNextChar()
                Token(TokenType.Sy_RightParen, "", line, pos)
            } // close paren
            '+' -> {
                getNextChar()
                Token(TokenType.Op_add, "", line, pos)
            } // plus
            '-' -> {
                getNextChar()
                Token(TokenType.Op_subtract, "", line, pos)
            } // dash
            '*' -> {
                getNextChar()
                Token(TokenType.Op_multiply, "", line, pos)
            } // asterisk
            '%' -> {
                getNextChar()
                Token(TokenType.Op_mod, "", line, pos)
            } // percent
            ';' -> {
                getNextChar()
                Token(TokenType.Sy_Semicolon, "", line, pos)
            } // semicolon
            ',' -> {
                getNextChar()
                Token(TokenType.Sy_Comma, "", line, pos)
            } // comma
            else ->
                identifier_or_integer(line, pos) }
    } // getToken

    // Method to parse and display tokens.
    fun printTokens() {
        do {
            val t: Token = getToken()
            println(t)
        } while (t.token != TokenType.Tk_End_of_input)
    } // printTokens
} // Lexer

// Function to test all good tests from the website and produce all of the
// error messages this program supports.
fun tests(number: Int) {

    // Function to generate test case 0 source: Hello World/Text.
    fun hello() {
        Lexer(
"""/*
Hello world
*/
print("Hello, World!\n");
""").printTokens()
    } // hello

    // Function to generate test case 1 source: Phoenix Number.
    fun phoenix() {
        Lexer(
"""/*
Show Ident and Integers
*/
phoenix_number = 142857;
print(phoenix_number, "\n");""").printTokens()
    } // phoenix

    // Function to generate test case 2 source: All Symbols.
    fun symbols() {
        Lexer(
"""/*
  All lexical tokens - not syntactically correct, but that will
  have to wait until syntax analysis
 */
/* Print   */  print    /* Sub     */  -
/* Putc    */  putc     /* Lss     */  <
/* If      */  if       /* Gtr     */  >
/* Else    */  else     /* Leq     */  <=
/* While   */  while    /* Geq     */  >=
/* Lbrace  */  {        /* Eq      */  ==
/* Rbrace  */  }        /* Neq     */  !=
/* Lparen  */  (        /* And     */  &&
/* Rparen  */  )        /* Or      */  ||
/* Uminus  */  -        /* Semi    */  ;
/* Not     */  !        /* Comma   */  ,
/* Mul     */  *        /* Assign  */  =
/* Div     */  /        /* Integer */  42
/* Mod     */  %        /* String  */  "String literal"
/* Add     */  +        /* Ident   */  variable_name
/* character literal */  '\n'
/* character literal */  '\\'
/* character literal */  ' '""").printTokens()
    } // symbols

    // Function to generate test case 3 source: Test Case 4.
    fun four() {
        Lexer(
"""/*** test printing, embedded \n and comments with lots of '*' ***/
print(42);
print("\nHello World\nGood Bye\nok\n");
print("Print a slash n - \\n.\n");""").printTokens()
    } // four

    // Function to generate test case 4 source: Count.
    fun count() {
        Lexer(
"""count = 1;
while (count < 10) {
    print("count is: ", count, "\n");
    count = count + 1;
}""").printTokens()
    } // count

    // Function to generate test case 5 source: 100 Doors.
    fun doors() {
        Lexer(
"""/* 100 Doors */
i = 1;
while (i * i <= 100) {
    print("door ", i * i, " is open\n");
    i = i + 1;
}""").printTokens()
    } // doors

    // Function to generate test case 6 source: Negative Tests.
    fun negative() {
        Lexer(
"""a = (-1 * ((-1 * (5 * 15)) / 10));
print(a, "\n");
b = -a;
print(b, "\n");
print(-b, "\n");
print(-(1), "\n");""").printTokens()
    } // negative

    // Function to generate test case 7 source: Deep.
    fun deep() {
        Lexer(
"""print(---------------------------------+++5, "\n");
print(((((((((3 + 2) * ((((((2))))))))))))), "\n");

if (1) { if (1) { if (1) { if (1) { if (1) { print(15, "\n"); } } } } }""").printTokens()
    } // deep

    // Function to generate test case 8 source: Greatest Common Divisor.
    fun gcd() {
        Lexer(
"""/* Compute the gcd of 1071, 1029: 21 */

a = 1071;
b = 1029;

while (b != 0) {
    new_a = b;
    b = a % b;
    a = new_a;
}
print(a);""").printTokens()
    } // gcd

    // Function to generate test case 9 source: Factorial.
    fun factorial() {
        Lexer(
"""/* 12 factorial is 479001600 */

n = 12;
result = 1;
i = 1;
while (i <= n) {
    result = result * i;
    i = i + 1;
}
print(result);""").printTokens()
    } // factorial

    // Function to generate test case 10 source: Fibonacci Sequence.
    fun fibonacci() {
        Lexer(
"""/* fibonacci of 44 is 701408733 */

n = 44;
i = 1;
a = 0;
b = 1;
while (i < n) {
    w = a + b;
    a = b;
    b = w;
    i = i + 1;
}
print(w, "\n");""").printTokens()
    } // fibonacci

    // Function to generate test case 11 source: FizzBuzz.
    fun fizzbuzz() {
        Lexer(
"""/* FizzBuzz */
i = 1;
while (i <= 100) {
    if (!(i % 15))
        print("FizzBuzz");
    else if (!(i % 3))
        print("Fizz");
    else if (!(i % 5))
        print("Buzz");
    else
        print(i);

    print("\n");
    i = i + 1;
}""").printTokens()
    } // fizzbuzz

    // Function to generate test case 12 source: 99 Bottles of Beer.
    fun bottles() {
        Lexer(
"""/* 99 bottles */
bottles = 99;
while (bottles > 0) {
    print(bottles, " bottles of beer on the wall\n");
    print(bottles, " bottles of beer\n");
    print("Take one down, pass it around\n");
    bottles = bottles - 1;
    print(bottles, " bottles of beer on the wall\n\n");
}""").printTokens()
    } // bottles

    // Function to generate test case 13 source: Primes.
    fun primes() {
        Lexer(
"""/*
Simple prime number generator
*/
count = 1;
n = 1;
limit = 100;
while (n < limit) {
    k=3;
    p=1;
    n=n+2;
    while ((k*k<=n) && (p)) {
        p=n/k*k!=n;
        k=k+2;
    }
    if (p) {
        print(n, " is prime\n");
        count = count + 1;
    }
}
print("Total primes found: ", count, "\n");""").printTokens()
    } // primes

    // Function to generate test case 14 source: Ascii Mandelbrot.
    fun ascii() {
        Lexer(
"""{
/*
 This is an integer ascii Mandelbrot generator
 */
    left_edge   = -420;
    right_edge  =  300;
    top_edge    =  300;
    bottom_edge = -300;
    x_step      =    7;
    y_step      =   15;

    max_iter    =  200;

    y0 = top_edge;
    while (y0 > bottom_edge) {
        x0 = left_edge;
        while (x0 < right_edge) {
            y = 0;
            x = 0;
            the_char = ' ';
            i = 0;
            while (i < max_iter) {
                x_x = (x * x) / 200;
                y_y = (y * y) / 200;
                if (x_x + y_y > 800 ) {
                    the_char = '0' + i;
                    if (i > 9) {
                        the_char = '@';
                    }
                    i = max_iter;
                }
                y = x * y / 100 + y0;
                x = x_x - y_y + x0;
                i = i + 1;
            }
            putc(the_char);
            x0 = x0 + x_step;
        }
        putc('\n');
        y0 = y0 - y_step;
    }
}
""").printTokens()
    } // ascii

    when (number) {
        0 ->
            hello()
        1 ->
            phoenix()
        2 ->
            symbols()
        3 ->
            four()
        4 ->
            count()
        5 ->
            doors()
        6 ->
            negative()
        7 ->
            deep()
        8 ->
            gcd()
        9 ->
            factorial()
        10 ->
            fibonacci()
        11 ->
            fizzbuzz()
        12 ->
            bottles()
        13 ->
            primes()
        14 ->
            ascii()
        15 -> // Lexer: Empty character constant
            Lexer("''").printTokens()
        16 -> // Lexer: Unknown escape sequence
            Lexer("'\\x").printTokens()
        17 -> // Lexer: Multi-character constant
            Lexer("'  ").printTokens()
        18 -> // Lexer: EOF in comment
            Lexer("/*").printTokens()
        19 -> // Lexer: EOL in string
            Lexer("\"\n").printTokens()
        20 -> // Lexer: EOF in string
            Lexer("\"").printTokens()
        21 -> // Lexer: Escape sequence unknown
            Lexer("\"\\x").printTokens()
        22 -> // Lexer: Unrecognized character
            Lexer("~").printTokens()
        23 -> // Lexer: invalid number
            Lexer("9a9").printTokens()
        24 -> // Lexer: Number exceeds maximum value
            Lexer("2147483648\n9223372036854775808").printTokens()
        25 -> // Lexer: Operator expected
            Lexer("|.").printTokens()
        else ->
            println("Invalid test number %d!".format(number))
    } // when
} // tests

// Main function to check our source and read its data before parsing it.
// With no source specified, run the test of all symbols.
fun main(args: Array<String>) {
    try {
        val s =
            if (args.size > 0 && args[0].isNotEmpty()) // file on command line
                java.util.Scanner(java.io.File(args[0]))
            else  // use the console
                java.util.Scanner(System.`in`)
        var source = ""
        while (s.hasNext())
            source += s.nextLine()+
                if (s.hasNext())
                    "\n"
                else
                    ""
        if (args.size > 0 && args[0].isNotEmpty()) // file on command line
            Lexer(source).printTokens()
        else {
            val digits = source.filter { it in '0'..'9' }
            when {
                source.isEmpty() -> // nothing given
                    tests(2)
                source.length in 1..2 && digits.length == source.length &&
                        digits.toInt() in 0..25 ->
                    tests(digits.toInt())
                else ->
                    Lexer(source).printTokens()
            } // when
        } // if
    } catch(e: Throwable) {
        println(e.message)
        System.exit(1)
    } // try
} // main


Conjugate transpose

Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.

::: (M^H)_{ji} = \overline{M_{ij}}

This means that   row j, column i of the conjugate transpose equals the
complex conjugate of row i, column j of the original matrix.

In the next list, M must also be a square matrix.

* A Hermitian matrix equals its own conjugate transpose: M^H = M.
* A multiplication with its conjugate transpose: M^HM = MM^H.
* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.

;Task:
Given some matrix of complex numbers, find its conjugate transpose.

Also determine if the matrix is a:
::* Hermitian matrix,
::* normal matrix,  or
::* unitary matrix.

;See also:
* MathWorld entry: conjugate transpose
* MathWorld entry: Hermitian matrix
* MathWorld entry: normal matrix
* MathWorld entry: unitary matrix

Solution:
// version 1.1.3

typealias C = Complex
typealias Vector = Array<C>
typealias Matrix = Array<Vector>

class Complex(val real: Double, val imag: Double) {

    operator fun plus(other: Complex) =
        Complex(this.real + other.real, this.imag + other.imag)

    operator fun times(other: Complex) =
        Complex(this.real * other.real - this.imag * other.imag,
                this.real * other.imag + this.imag * other.real)

    fun conj() = Complex(this.real, -this.imag)

    /* tolerable equality allowing for rounding of Doubles */
    infix fun teq(other: Complex) =
        Math.abs(this.real - other.real) <= 1e-14 &&
        Math.abs(this.imag - other.imag) <= 1e-14

    override fun toString() = "${"%.3f".format(real)} " + when {
        imag > 0.0   -> "+ ${"%.3f".format(imag)}i"
        imag == 0.0  -> "+ 0.000i"
        else         -> "- ${"%.3f".format(-imag)}i"
    }
}

fun Matrix.conjTranspose(): Matrix {
    val rows = this.size
    val cols = this[0].size
    return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } }
}

operator fun Matrix.times(other: Matrix): Matrix {
    val rows1 = this.size
    val cols1 = this[0].size
    val rows2 = other.size
    val cols2 = other[0].size
    require(cols1 == rows2)
    val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } }
    for (i in 0 until rows1) {
        for (j in 0 until cols2) {
            for (k in 0 until rows2) {
                result[i][j] += this[i][k] * other[k][j]
            }
        }
    }
    return result
}

/* tolerable matrix equality using the same concept as for complex numbers */
infix fun Matrix.teq(other: Matrix): Boolean {
    if (this.size != other.size || this[0].size != other[0].size) return false
    for (i in 0 until this.size) {
        for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false
    }
    return true
}

fun Matrix.isHermitian() = this teq this.conjTranspose()

fun Matrix.isNormal(): Boolean {
    val ct = this.conjTranspose()
    return (this * ct) teq (ct * this)
}

fun Matrix.isUnitary(): Boolean {
    val ct = this.conjTranspose()
    val prod = this * ct
    val ident = identityMatrix(prod.size)
    val prod2 = ct * this
    return (prod teq ident) && (prod2 teq ident)
}

fun Matrix.print() {
    val rows = this.size
    val cols = this[0].size
    for (i in 0 until rows) {
        for (j in 0 until cols) {
            print(this[i][j])
            print(if(j < cols - 1) ",  " else "\n")
        }
    }
    println()
}

fun identityMatrix(n: Int): Matrix {
    require(n >= 1)
    val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } }
    for (i in 0 until n) ident[i][i] = C(1.0, 0.0)
    return ident
}

fun main(args: Array<String>) {
    val x = Math.sqrt(2.0) / 2.0
    val matrices = arrayOf(
        arrayOf(
            arrayOf(C(3.0,  0.0), C(2.0, 1.0)),
            arrayOf(C(2.0, -1.0), C(1.0, 0.0))
        ),
        arrayOf(
            arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)),
            arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)),
            arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0))
        ),
        arrayOf(
            arrayOf(C(x,   0.0), C(x,   0.0), C(0.0, 0.0)),
            arrayOf(C(0.0,  -x), C(0.0,   x), C(0.0, 0.0)),
            arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0))
        )
    )

    for (m in matrices) {
        println("Matrix:")
        m.print()
        val mct = m.conjTranspose()
        println("Conjugate transpose:")
        mct.print()
        println("Hermitian? ${mct.isHermitian()}")
        println("Normal?    ${mct.isNormal()}")
        println("Unitary?   ${mct.isUnitary()}\n")
    }
}


Continued fraction

A number may be represented as a continued fraction (see Mathworld for more information) as follows:
:a_0 + \cfrac{b_1}{a_1 + \cfrac{b_2}{a_2 + \cfrac{b_3}{a_3 + \ddots}}}

The task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:

For the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.

:\sqrt{2} = 1 + \cfrac{1}{2 + \cfrac{1}{2 + \cfrac{1}{2 + \ddots}}}

For Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.

:e = 2 + \cfrac{1}{1 + \cfrac{1}{2 + \cfrac{2}{3 + \cfrac{3}{4 + \ddots}}}}

For Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.

:\pi = 3 + \cfrac{1}{6 + \cfrac{9}{6 + \cfrac{25}{6 + \ddots}}}

;See also:
:*   [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.

Solution:
// version 1.1.2

typealias Func = (Int) -> IntArray

fun calc(f: Func, n: Int): Double {
    var temp = 0.0
    for (i in n downTo 1) {
        val p = f(i)
        temp = p[1] / (p[0] + temp)
    }
    return f(0)[0] + temp
}

fun main(args: Array<String>) {
    val pList = listOf<Pair<String, Func>>(
        "sqrt(2)" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) },
        "e      " to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) },
        "pi     " to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) }
    )
    for (pair in pList) println("${pair.first} = ${calc(pair.second, 200)}")
}


Continued fraction/Arithmetic/Construct from rational number

To understand this task in context please see [[Continued fraction arithmetic]]
The purpose of this task is to write a function \mathit{r2cf}(\mathrm{int} N_1, \mathrm{int} N_2), or \mathit{r2cf}(\mathrm{Fraction} N), which will output a continued fraction assuming:
:N_1 is the numerator
:N_2 is the denominator

The function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.

To achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \mathrm{abs}(N_2) is zero.

Demonstrate the function by outputing the continued fraction for:
: 1/2
: 3
: 23/8
: 13/11
: 22/7
: -151/77
\sqrt 2 should approach [1; 2, 2, 2, 2, \ldots] try ever closer rational approximations until boredom gets the better of you:
: 14142,10000
: 141421,100000
: 1414214,1000000
: 14142136,10000000

Try :
: 31,10
: 314,100
: 3142,1000
: 31428,10000
: 314285,100000
: 3142857,1000000
: 31428571,10000000
: 314285714,100000000

Observe how this rational number behaves differently to \sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\infty] when an extra term is required.

Solution:
// version 1.1.2
// compile with -Xcoroutines=enable flag from command line

import kotlin.coroutines.experimental.buildSequence

fun r2cf(frac: Pair<Int, Int>) =
    buildSequence {
        var num = frac.first
        var den = frac.second
        while (Math.abs(den) != 0) {
            val div = num / den
            val rem = num % den
            num = den
            den = rem
            yield(div)
        }
    }

fun iterate(seq: Sequence<Int>) {
    for (i in seq) print("$i ")
    println()
}

fun main(args: Array<String>) {
    val fracs = arrayOf(1 to 2, 3 to 1, 23 to 8, 13 to 11, 22 to 7, -151 to 77)
    for (frac in fracs) {
        print("${"%4d".format(frac.first)} / ${"%-2d".format(frac.second)} = ")
        iterate(r2cf(frac))
    }
    val root2 = arrayOf(14142 to 10000, 141421 to 100000,
                        1414214 to 1000000, 14142136 to 10000000)
    println("\nSqrt(2) ->")
    for (frac in root2) {
        print("${"%8d".format(frac.first)} / ${"%-8d".format(frac.second)} = ")
        iterate(r2cf(frac))
    }
    val pi = arrayOf(31 to 10, 314 to 100, 3142 to 1000, 31428 to 10000,
                     314285 to 100000, 3142857 to 1000000,
                     31428571 to 10000000, 314285714 to 100000000)
    println("\nPi ->")
    for (frac in pi) {
        print("${"%9d".format(frac.first)} / ${"%-9d".format(frac.second)} = ")
        iterate(r2cf(frac))
    }
}


Continued fraction/Arithmetic/G(matrix ng, continued fraction n)

This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:
: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix}
I may perform perform the following operations:
:Input the next term of N1
:Output a term of the continued fraction resulting from the operation.

I output a term if the integer parts of \frac{a}{b} and \frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \infty.

When I input a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a + a_1 * t & a_1  \\
  b + b_1 * t & b_1
\end{bmatrix}

When I output a term t my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} b_1 & b  \\
  a_1 - b_1 * t & a - b * t
\end{bmatrix}

When I need a term t but there are no more my internal state: \begin{bmatrix}
  a_1 & a \\
  b_1 & b
\end{bmatrix} is transposed thus \begin{bmatrix} a_1 & a_1 \\
  b_1 & b_1
\end{bmatrix}

I am done when b1 and b are zero.

Demonstrate your solution by calculating:
:[1;5,2] + 1/2
:[3;7] + 1/2
:[3;7] divided by 4
Using a generator for \sqrt{2} (e.g., from [[Continued fraction]]) calculate \frac{1}{\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.

The first step in implementing [[Arithmetic-geometric mean]] is to calculate \frac{1 + \frac{1}{\sqrt{2}}}{2} do this now to cross the starting line and begin the race.

Solution:
// version 1.1.3
// compile with -Xcoroutines=enable flag from command line

import kotlin.coroutines.experimental.*

typealias CFGenerator = (Pair<Int, Int>) -> Sequence<Int>

data class CFData(
    val str: String,
    val ng: IntArray,
    val r: Pair<Int,Int>,
    val gen: CFGenerator
)

fun r2cf(frac: Pair<Int, Int>) =
    buildSequence {
        var num = frac.first
        var den = frac.second
        while (Math.abs(den) != 0) {
            val div = num / den
            val rem = num % den
            num = den
            den = rem
            yield(div)
        }
    }

fun d2cf(d: Double) =
    buildSequence {
        var dd  = d
        while (true) {
            val div = Math.floor(dd)
            val rem = dd - div
            yield(div.toInt())
            if (rem == 0.0) break
            dd = 1.0 / rem
        }
    }

@Suppress("UNUSED_PARAMETER")
fun root2(dummy: Pair<Int, Int>) =
    buildSequence {
        yield(1)
        while (true) yield(2)
    }

@Suppress("UNUSED_PARAMETER")
fun recipRoot2(dummy: Pair<Int, Int>) =
    buildSequence {
       yield(0)
       yield(1)
       while (true) yield(2)
    }

class NG(var a1: Int, var a: Int, var b1: Int, var b: Int) {

    fun ingress(n: Int) {
        var t = a
        a = a1
        a1 = t + a1 * n
        t = b
        b = b1
        b1 = t + b1 * n
    }

    fun egress(): Int {
        val n = a / b
        var t = a
        a = b
        b = t - b * n
        t = a1
        a1 = b1
        b1 = t - b1 * n
        return n
    }

    val needTerm get() = (b == 0 || b1 == 0) || ((a / b) != (a1 / b1))

    val egressDone: Int
        get() {
            if (needTerm) {
                a = a1
                b = b1
            }
            return egress()
        }

    val done get() = b == 0 &&  b1 == 0
}

fun main(args: Array<String>) {
    val data = listOf(
        CFData("[1;5,2] + 1/2        ", intArrayOf(2, 1, 0, 2), 13 to 11, ::r2cf),
        CFData("[3;7] + 1/2          ", intArrayOf(2, 1, 0, 2), 22 to 7,  ::r2cf),
        CFData("[3;7] divided by 4   ", intArrayOf(1, 0, 0, 4), 22 to 7,  ::r2cf),
        CFData("sqrt(2)              ", intArrayOf(0, 1, 1, 0),  0 to 0,  ::recipRoot2),
        CFData("1 / sqrt(2)          ", intArrayOf(0, 1, 1, 0),  0 to 0,  ::root2),
        CFData("(1 + sqrt(2)) / 2    ", intArrayOf(1, 1, 0, 2),  0 to 0,  ::root2),
        CFData("(1 + 1 / sqrt(2)) / 2", intArrayOf(1, 1, 0, 2),  0 to 0,  ::recipRoot2)
    )
    println("Produced by NG class:")
    for ((str, ng, r, gen) in data) {
        print("$str -> ")
        val (a1, a, b1, b) = ng
        val op = NG(a1, a, b1, b)
        for (n in gen(r).take(20)) {
            if (!op.needTerm) print(" ${op.egress()} ")
            op.ingress(n)
        }
        while (true) {
            print(" ${op.egressDone} ")
            if (op.done) break
        }
        println()
    }
    println("\nProduced by direct calculation:")
    val data2 = listOf(
        Pair("(1 + sqrt(2)) / 2    ", (1 + Math.sqrt(2.0)) / 2),
        Pair("(1 + 1 / sqrt(2)) / 2", (1 + 1 / Math.sqrt(2.0)) / 2)
    )
    for ((str, d) in data2) {
        println("$str ->  ${d2cf(d).take(20).joinToString("  ")}")
    }
}


Convert decimal number to rational

The task is to write a program to transform a decimal number into a fraction in lowest terms.

It is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...

Because of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:
* 67 / 74 = 0.9(054) = 0.9054054...
* 14 / 27 = 0.(518)  = 0.518518...

Acceptable output:

* 0.9054054 - 4527027 / 5000000
* 0.518518  - 259259 / 500000

Finite decimals are of course no problem:

* 0.75      - 3 / 4

Solution:
// version 1.1.2

class Rational(val num: Long, val den: Long) {
    override fun toString() = "$num/$den"
}

fun decimalToRational(d: Double): Rational {
    val ds = d.toString().trimEnd('0').trimEnd('.')
    val index = ds.indexOf('.')
    if (index == -1) return Rational(ds.toLong(), 1L)
    var num = ds.replace(".", "").toLong()
    var den = 1L
    for (n in 1..(ds.length - index - 1)) den *= 10L
    while (num % 2L == 0L && den % 2L == 0L) {
        num /= 2L
        den /= 2L
    }
    while (num % 5L == 0L && den % 5L == 0L) {
        num /= 5L
        den /= 5L
    }
    return Rational(num, den)
}

fun main(args: Array<String>) {
    val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6)
    for (decimal in decimals)
        println("${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}")
}


Convert seconds to compound duration

Write a function or program which:
*   takes a positive integer representing a duration in seconds as input (e.g., 100), and
*   returns a string which shows the same duration decomposed into:
:::*   weeks,
:::*   days,
:::*   hours,
:::*   minutes,   and
:::*   seconds.

This is detailed below (e.g., "2 hr, 59 sec").

Demonstrate that it passes the following three test-cases:

'''''Test Cases'''''

:::::{| class="wikitable"
|-
! input number
! output string
|-
| 7259
| 2 hr, 59 sec
|-
| 86400
| 1 d
|-
| 6000000
| 9 wk, 6 d, 10 hr, 40 min
|}

'''''Details'''''

The following five units should be used:
:::::{| class="wikitable"
|-
! unit
! suffix used in output
! conversion
|-
| week
| wk
| 1 week = 7 days
|-
| day
| d
| 1 day = 24 hours
|-
| hour
| hr
| 1 hour = 60 minutes
|-
| minute
| min
| 1 minute = 60 seconds
|-
| second
| sec
|
|}

However, '''only''' include quantities with non-zero values in the output (e.g., return "1 d" and not "0 wk, 1 d, 0 hr, 0 min, 0 sec").

Give larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)

Mimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).

Solution:
fun compoundDuration(n: Int): String {
    if (n < 0) return "" // task doesn't ask for negative integers to be converted
    if (n == 0) return "0 sec"
    val weeks  : Int
    val days   : Int
    val hours  : Int
    val minutes: Int
    val seconds: Int
    var divisor: Int = 7 * 24 * 60 * 60
    var rem    : Int
    var result = ""

    weeks = n / divisor
    rem   = n % divisor
    divisor /= 7
    days  = rem / divisor
    rem  %= divisor
    divisor /= 24
    hours = rem / divisor
    rem  %= divisor
    divisor /= 60
    minutes = rem / divisor
    seconds = rem % divisor

    if (weeks > 0)   result += "$weeks wk, "
    if (days > 0)    result += "$days d, "
    if (hours > 0)   result += "$hours hr, "
    if (minutes > 0) result += "$minutes min, "
    if (seconds > 0)
        result += "$seconds sec"
    else
        result = result.substring(0, result.length - 2)
    return result
}

fun main(args: Array<String>) {
    val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)
    durations.forEach { println("$it\t-> ${compoundDuration(it)}") }
}


Copy stdin to stdout

Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.

Solution:
fun main() {
    var c: Int
    do {
        c = System.`in`.read()
        System.out.write(c)
    } while (c >= 0)
}


Count the coins

There are four types of common coins in   US   currency:
:::#   quarters   (25 cents)
:::#   dimes   (10 cents)
:::#   nickels   (5 cents),   and
:::#   pennies   (1 cent)

There are six ways to make change for 15 cents:
:::#   A dime and a nickel
:::#   A dime and 5 pennies
:::#   3 nickels
:::#   2 nickels and 5 pennies
:::#   A nickel and 10 pennies
:::#   15 pennies

;Task:
How many ways are there to make change for a dollar using these common coins?     (1 dollar = 100 cents).

;Optional:
Less common are dollar coins (100 cents);   and very rare are half dollars (50 cents).   With the addition of these two coins, how many ways are there to make change for $1000?

(Note:   the answer is larger than   232).

;References:
* an algorithm from the book ''Structure and Interpretation of Computer Programs''.
* an article in the algorithmist.
* Change-making problem on Wikipedia.

Solution:
// version 1.0.6

fun countCoins(c: IntArray, m: Int, n: Int): Long {
    val table = LongArray(n + 1)
    table[0] = 1
    for (i in 0 until m)
        for (j in c[i]..n) table[j] += table[j - c[i]]
    return table[n]
}

fun main(args: Array<String>) {
    val c = intArrayOf(1, 5, 10, 25, 50, 100)
    println(countCoins(c, 4, 100))
    println(countCoins(c, 6, 1000 * 100))
}


Create an HTML table

Create an HTML table.
* The table body should have at least three rows of three columns.
* Each of these three columns should be labelled "X", "Y", and "Z".
* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers.
* The rows of the "X", "Y", and "Z" columns should be filled with random or sequential integers having 4 digits or less.
* The numbers should be aligned in the same fashion for all columns.

Solution:
// version 1.1.3

import java.util.Random

fun main(args: Array<String>) {
    val r = Random()
    val sb = StringBuilder()
    val i = "   "  // indent
    with (sb) {
        append("\n\n")
        append("\n\n\n")
        append("
\n")
        append("$i
\n")
        append("$i$i
	")
        for (c in 'X'..'Z') append("$c	")
        append("
\n")
        append("$i
\n")
        append("$i
\n")
        val f = "$i$i
%d	%d	%d	%d
\n"
        for (j in 1..4) {
            append(f.format(j, r.nextInt(10000), r.nextInt(10000), r.nextInt(10000)))
        }
        append("$i
\n")
        append("
\n")
        append("\n")
    }
    println(sb.toString())
}


Currency

Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents.

;Note:
The '''IEEE 754''' binary floating point representations of numbers like   '''2.86'''   and   '''.0765'''   are not exact.

For this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate.

Use the values:
::* 4000000000000000 hamburgers at $5.50 each       (four quadrillion burgers)
::* 2 milkshakes at $2.86 each, and
::* a tax rate of 7.65%.

(That number of hamburgers is a 4 with 15 zeros after it.    The number is contrived to exclude naive task solutions using 64 bit floating point types.)

Compute and output (show results on this page):
::* the total price before tax
::* the tax
::* the total with tax

The tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax.

The output must show dollars and cents with a decimal point.

The three results displayed should be:
::* 22000000000000005.72
::* 1683000000000000.44
::* 23683000000000006.16

Dollar signs and thousands separators are optional.

Solution:
// version 1.1.2

import java.math.BigDecimal
import java.math.MathContext

fun main(args: Array<String>) {
    val mc = MathContext.DECIMAL128
    val nHamburger  = BigDecimal("4000000000000000", mc)
    val pHamburger  = BigDecimal("5.50")
    val nMilkshakes = BigDecimal("2", mc)
    val pMilkshakes = BigDecimal("2.86")
    val taxRate     = BigDecimal("0.0765")
    val price = nHamburger * pHamburger + nMilkshakes * pMilkshakes
    val tax = price * taxRate
    val fmt = "%20.2f"
    println("Total price before tax : ${fmt.format(price)}")
    println("Tax thereon @ 7.65%    : ${fmt.format(tax)}")
    println("Total price after tax  : ${fmt.format(price + tax)}")
}


Currying

{{Wikipedia|Currying}}

;Task:
Create a simple demonstrative example of Currying in a specific language.

Add any historic details as to how the feature made its way into the language.

Solution:
// version 1.1.2

fun curriedAdd(x: Int) = { y: Int -> x + y }

fun main(args: Array<String>) {
    val a = 2
    val b = 3
    val sum = curriedAdd(a)(b)
    println("$a + $b = $sum")
}


Cut a rectangle

A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.

[[file:rect-cut.svg]]

Write a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle.  Optionally, show each of the cuts.

Possibly related task: [[Maze generation]] for depth-first search.

Solution:
// version 1.0.6

object RectangleCutter {
    private var w: Int = 0
    private var h: Int = 0
    private var len: Int = 0
    private var cnt: Long = 0

    private lateinit var grid: ByteArray
    private val next = IntArray(4)
    private val dir = arrayOf(
        intArrayOf(0, -1),
        intArrayOf(-1, 0),
        intArrayOf(0, 1),
        intArrayOf(1, 0)
    )

    private fun walk(y: Int, x: Int) {
        if (y == 0 || y == h || x == 0 || x == w) {
            cnt += 2
            return
        }
        val t = y * (w + 1) + x
        grid[t]++
        grid[len - t]++
        (0..3).filter { grid[t + next[it]] == 0.toByte() }
            .forEach { walk(y + dir[it][0], x + dir[it][1]) }
        grid[t]--
        grid[len - t]--
    }

    fun solve(hh: Int, ww: Int, recur: Boolean): Long {
        var t: Int
        h = hh
        w = ww
        if ((h and 1) != 0) {
            t = w
            w = h
            h = t
        }
        if ((h and 1) != 0) return 0L
        if (w == 1) return 1L
        if (w == 2) return h.toLong()
        if (h == 2) return w.toLong()
        val cy = h / 2
        val cx = w / 2
        len = (h + 1) * (w + 1)
        grid = ByteArray(len)
        len--
        next[0] = -1
        next[1] = -w - 1
        next[2] = 1
        next[3] = w + 1
        if (recur) cnt = 0L
        for (x in cx + 1 until w) {
            t = cy * (w + 1) + x
            grid[t] = 1
            grid[len - t] = 1
            walk(cy - 1, x)
        }
        cnt++
        if (h == w) cnt *= 2
        else if ((w and 1) == 0 && recur) solve(w, h, false)
        return cnt
    }
}

fun main(args: Array<String>) {
    for (y in 1..10) {
        for (x in 1..y) {
            if ((x and 1) == 0 || (y and 1) == 0) {
                println("${"%2d".format(y)} x ${"%2d".format(x)}: ${RectangleCutter.solve(y, x, true)}")
            }
        }
    }
}


Cyclotomic polynomial

The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.

;Task:
*   Find and print the first 30 cyclotomic polynomials.
*   Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.

;See also
*   Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.
*   The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.

Solution:
import java.util.TreeMap
import kotlin.math.abs
import kotlin.math.pow
import kotlin.math.sqrt

private const val algorithm = 2

fun main() {
    println("Task 1:  cyclotomic polynomials for n <= 30:")
    for (i in 1..30) {
        val p = cyclotomicPolynomial(i)
        println("CP[$i] = $p")
    }
    println()

    println("Task 2:  Smallest cyclotomic polynomial with n or -n as a coefficient:")
    var n = 0
    for (i in 1..10) {
        while (true) {
            n++
            val cyclo = cyclotomicPolynomial(n)
            if (cyclo!!.hasCoefficientAbs(i)) {
                println("CP[$n] has coefficient with magnitude = $i")
                n--
                break
            }
        }
    }
}

private val COMPUTED: MutableMap<Int, Polynomial> = HashMap()
private fun cyclotomicPolynomial(n: Int): Polynomial? {
    if (COMPUTED.containsKey(n)) {
        return COMPUTED[n]
    }
    if (n == 1) {
        //  Polynomial:  x - 1
        val p = Polynomial(1, 1, -1, 0)
        COMPUTED[1] = p
        return p
    }
    val factors = getFactors(n)
    if (factors.containsKey(n)) {
        //  n prime
        val termList: MutableList<Term> = ArrayList()
        for (index in 0 until n) {
            termList.add(Term(1, index.toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {
        //  n = 2p
        val prime = n / 2
        val termList: MutableList<Term> = ArrayList()
        var coeff = -1
        for (index in 0 until prime) {
            coeff *= -1
            termList.add(Term(coeff.toLong(), index.toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 1 && factors.containsKey(2)) {
        //  n = 2^h
        val h = factors[2]!!
        val termList: MutableList<Term> = ArrayList()
        termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))
        termList.add(Term(1, 0))
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 1 && !factors.containsKey(n)) {
        // n = p^k
        var p = 0
        for (prime in factors.keys) {
            p = prime
        }
        val k = factors[p]!!
        val termList: MutableList<Term> = ArrayList()
        for (index in 0 until p) {
            termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.size == 2 && factors.containsKey(2)) {
        //  n = 2^h * p^k
        var p = 0
        for (prime in factors.keys) {
            if (prime != 2) {
                p = prime
            }
        }
        val termList: MutableList<Term> = ArrayList()
        var coeff = -1
        val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()
        val k = factors[p]!!
        for (index in 0 until p) {
            coeff *= -1
            termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    } else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {
        //  CP(2m)[x] = CP(-m)[x], n odd integer > 1
        val cycloDiv2 = cyclotomicPolynomial(n / 2)
        val termList: MutableList<Term> = ArrayList()
        for (term in cycloDiv2!!.polynomialTerms) {
            termList.add(if (term.exponent % 2 == 0L) term else term.negate())
        }
        val cyclo = Polynomial(termList)
        COMPUTED[n] = cyclo
        return cyclo
    }

    //  General Case
    return when (algorithm) {
        0 -> {
            //  Slow - uses basic definition.
            val divisors = getDivisors(n)
            //  Polynomial:  ( x^n - 1 )
            var cyclo = Polynomial(1, n, -1, 0)
            for (i in divisors) {
                val p = cyclotomicPolynomial(i)
                cyclo = cyclo.divide(p)
            }
            COMPUTED[n] = cyclo
            cyclo
        }
        1 -> {
            //  Faster.  Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor
            val divisors = getDivisors(n)
            var maxDivisor = Int.MIN_VALUE
            for (div in divisors) {
                maxDivisor = maxDivisor.coerceAtLeast(div)
            }
            val divisorsExceptMax: MutableList<Int> = ArrayList()
            for (div in divisors) {
                if (maxDivisor % div != 0) {
                    divisorsExceptMax.add(div)
                }
            }

            //  Polynomial:  ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor
            var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))
            for (i in divisorsExceptMax) {
                val p = cyclotomicPolynomial(i)
                cyclo = cyclo.divide(p)
            }
            COMPUTED[n] = cyclo
            cyclo
        }
        2 -> {
            //  Fastest
            //  Let p ; q be primes such that p does not divide n, and q q divides n.
            //  Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]
            var m = 1
            var cyclo = cyclotomicPolynomial(m)
            val primes = factors.keys.toMutableList()
            primes.sort()
            for (prime in primes) {
                //  CP(m)[x]
                val cycloM = cyclo
                //  Compute CP(m)[x^p].
                val termList: MutableList<Term> = ArrayList()
                for (t in cycloM!!.polynomialTerms) {
                    termList.add(Term(t.coefficient, t.exponent * prime))
                }
                cyclo = Polynomial(termList).divide(cycloM)
                m *= prime
            }
            //  Now, m is the largest square free divisor of n
            val s = n / m
            //  Compute CP(n)[x] = CP(m)[x^s]
            val termList: MutableList<Term> = ArrayList()
            for (t in cyclo!!.polynomialTerms) {
                termList.add(Term(t.coefficient, t.exponent * s))
            }
            cyclo = Polynomial(termList)
            COMPUTED[n] = cyclo
            cyclo
        }
        else -> {
            throw RuntimeException("ERROR 103:  Invalid algorithm.")
        }
    }
}

private fun getDivisors(number: Int): List<Int> {
    val divisors: MutableList<Int> = ArrayList()
    val sqrt = sqrt(number.toDouble()).toLong()
    for (i in 1..sqrt) {
        if (number % i == 0L) {
            divisors.add(i.toInt())
            val div = (number / i).toInt()
            if (div.toLong() != i && div != number) {
                divisors.add(div)
            }
        }
    }
    return divisors
}

private fun crutch(): MutableMap<Int, Map<Int, Int>> {
    val allFactors: MutableMap<Int, Map<Int, Int>> = TreeMap()

    val factors: MutableMap<Int, Int> = TreeMap()
    factors[2] = 1

    allFactors[2] = factors
    return allFactors
}

private val allFactors = crutch()

var MAX_ALL_FACTORS = 100000

fun getFactors(number: Int): Map<Int, Int> {
    if (allFactors.containsKey(number)) {
        return allFactors[number]!!
    }
    val factors: MutableMap<Int, Int> = TreeMap()
    if (number % 2 == 0) {
        val factorsDivTwo = getFactors(number / 2)
        factors.putAll(factorsDivTwo)
        factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
        if (number < MAX_ALL_FACTORS) allFactors[number] = factors
        return factors
    }
    val sqrt = sqrt(number.toDouble()).toLong()
    var i = 3
    while (i <= sqrt) {
        if (number % i == 0) {
            factors.putAll(getFactors(number / i))
            factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
            if (number < MAX_ALL_FACTORS) {
                allFactors[number] = factors
            }
            return factors
        }
        i += 2
    }
    factors[number] = 1
    if (number < MAX_ALL_FACTORS) {
        allFactors[number] = factors
    }
    return factors
}

private class Polynomial {
    val polynomialTerms: MutableList<Term>

    //  Format - coeff, exp, coeff, exp, (repeating in pairs) . . .
    constructor(vararg values: Int) {
        require(values.size % 2 == 0) { "ERROR 102:  Polynomial constructor.  Length must be even.  Length = " + values.size }
        polynomialTerms = mutableListOf()
        var i = 0
        while (i < values.size) {
            val t = Term(values[i].toLong(), values[i + 1].toLong())
            polynomialTerms.add(t)
            i += 2
        }
        polynomialTerms.sortWith(TermSorter())
    }

    constructor() {
        //  zero
        polynomialTerms = ArrayList()
        polynomialTerms.add(Term(0, 0))
    }

    fun hasCoefficientAbs(coeff: Int): Boolean {
        for (term in polynomialTerms) {
            if (abs(term.coefficient) == coeff.toLong()) {
                return true
            }
        }
        return false
    }

    constructor(termList: MutableList<Term>) {
        if (termList.isEmpty()) {
            //  zero
            termList.add(Term(0, 0))
        } else {
            //  Remove zero terms if needed
            termList.removeIf { t -> t.coefficient == 0L }
        }
        if (termList.size == 0) {
            //  zero
            termList.add(Term(0, 0))
        }
        polynomialTerms = termList
        polynomialTerms.sortWith(TermSorter())
    }

    fun divide(v: Polynomial?): Polynomial {
        var q = Polynomial()
        var r = this
        val lcv = v!!.leadingCoefficient()
        val dv = v.degree()
        while (r.degree() >= v.degree()) {
            val lcr = r.leadingCoefficient()
            val s = lcr / lcv //  Integer division
            val term = Term(s, r.degree() - dv)
            q = q.add(term)
            r = r.add(v.multiply(term.negate()))
        }
        return q
    }

    fun add(polynomial: Polynomial): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        var thisCount = polynomialTerms.size
        var polyCount = polynomial.polynomialTerms.size
        while (thisCount > 0 || polyCount > 0) {
            val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]
            val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]
            when {
                thisTerm == null -> {
                    termList.add(polyTerm!!.clone())
                    polyCount--
                }
                polyTerm == null -> {
                    termList.add(thisTerm.clone())
                    thisCount--
                }
                thisTerm.degree() == polyTerm.degree() -> {
                    val t = thisTerm.add(polyTerm)
                    if (t.coefficient != 0L) {
                        termList.add(t)
                    }
                    thisCount--
                    polyCount--
                }
                thisTerm.degree() < polyTerm.degree() -> {
                    termList.add(thisTerm.clone())
                    thisCount--
                }
                else -> {
                    termList.add(polyTerm.clone())
                    polyCount--
                }
            }
        }
        return Polynomial(termList)
    }

    fun add(term: Term): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        var added = false
        for (currentTerm in polynomialTerms) {
            if (currentTerm.exponent == term.exponent) {
                added = true
                if (currentTerm.coefficient + term.coefficient != 0L) {
                    termList.add(currentTerm.add(term))
                }
            } else {
                termList.add(currentTerm.clone())
            }
        }
        if (!added) {
            termList.add(term.clone())
        }
        return Polynomial(termList)
    }

    fun multiply(term: Term): Polynomial {
        val termList: MutableList<Term> = ArrayList()
        for (currentTerm in polynomialTerms) {
            termList.add(currentTerm.clone().multiply(term))
        }
        return Polynomial(termList)
    }

    fun leadingCoefficient(): Long {
        return polynomialTerms[0].coefficient
    }

    fun degree(): Long {
        return polynomialTerms[0].exponent
    }

    override fun toString(): String {
        val sb = StringBuilder()
        var first = true
        for (term in polynomialTerms) {
            if (first) {
                sb.append(term)
                first = false
            } else {
                sb.append(" ")
                if (term.coefficient > 0) {
                    sb.append("+ ")
                    sb.append(term)
                } else {
                    sb.append("- ")
                    sb.append(term.negate())
                }
            }
        }
        return sb.toString()
    }
}

private class TermSorter : Comparator<Term> {
    override fun compare(o1: Term, o2: Term): Int {
        return (o2.exponent - o1.exponent).toInt()
    }
}

//  Note:  Cyclotomic Polynomials have small coefficients.  Not appropriate for general polynomial usage.
private class Term(var coefficient: Long, var exponent: Long) {
    fun clone(): Term {
        return Term(coefficient, exponent)
    }

    fun multiply(term: Term): Term {
        return Term(coefficient * term.coefficient, exponent + term.exponent)
    }

    fun add(term: Term): Term {
        if (exponent != term.exponent) {
            throw RuntimeException("ERROR 102:  Exponents not equal.")
        }
        return Term(coefficient + term.coefficient, exponent)
    }

    fun negate(): Term {
        return Term(-coefficient, exponent)
    }

    fun degree(): Long {
        return exponent
    }

    override fun toString(): String {
        if (coefficient == 0L) {
            return "0"
        }
        if (exponent == 0L) {
            return "" + coefficient
        }
        if (coefficient == 1L) {
            return if (exponent == 1L) {
                "x"
            } else {
                "x^$exponent"
            }
        }
        return if (exponent == 1L) {
            coefficient.toString() + "x"
        } else coefficient.toString() + "x^" + exponent
    }
}


Damm algorithm

The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors.

The algorithm is named after H. Michael Damm.

;Task:
Verify the checksum, stored as last digit of an input.

Solution:
// version 1.1.2

val table = arrayOf(
    intArrayOf(0, 3, 1,	7, 5, 9, 8, 6, 4, 2),
    intArrayOf(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),
    intArrayOf(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),
    intArrayOf(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),
    intArrayOf(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),
    intArrayOf(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),
    intArrayOf(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),
    intArrayOf(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),
    intArrayOf(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),
    intArrayOf(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)
)

fun damm(s: String): Boolean {
    var interim = 0
    for (c in s) interim = table[interim][c - '0']
    return interim == 0
}

fun main(args: Array<String>) {
    val numbers = intArrayOf(5724, 5727, 112946, 112949)
    for (number in numbers) {
        val isValid = damm(number.toString())
        println("${"%6d".format(number)} is ${if (isValid) "valid" else "invalid"}")
    }
}


De Bruijn sequences

{{DISPLAYTITLE:de Bruijn sequences}}
The sequences are named after the Dutch mathematician   Nicolaas Govert de Bruijn.

A note on Dutch capitalization:   Nicolaas' last name is   '''de Bruijn''',   the   '''de'''   isn't normally capitalized
unless it's the first word in a sentence.   Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be
capitalized.

In combinatorial mathematics,   a   '''de Bruijn sequence'''   of order    ''n''    on
a    size-''k''    alphabet (computer science)    ''A''    is a cyclic sequence in which every
possible    length-''n''    string (computer science, formal theory)   on    ''A''    occurs
exactly once as a contiguous substring.

Such a sequence is denoted by    ''B''(''k'', ''n'')    and has
length   ''k''''n'',   which is also the number of distinct substrings of
length   ''n''   on   ''A'';
de Bruijn sequences are therefore optimally short.

There are:
                          (k!)k(n-1)   /   kn
distinct de Bruijn sequences    ''B''(''k'', ''n'').

;Task:
For this Rosetta Code task,   a   '''de Bruijn'''   sequence is to be generated that can be used to shorten a brute-force attack on
a   PIN-like   code lock that does not have an "enter"
key and accepts the last    ''n''    digits entered.

Note:   automated teller machines (ATMs)   used to work like
this,   but their software has been updated to not allow a brute-force attack.

;Example:
A   digital door lock   with a 4-digit code would
have ''B'' (10, 4) solutions,   with a length of   '''10,000'''   (digits).

Therefore, only at most     '''10,000 + 3'''     (as the solutions are cyclic or ''wrap-around'')   presses are needed to
open the lock.

Trying all 4-digit codes separately would require   '''4 x 10,000'''   or   '''40,000'''   presses.

;Task requirements:
:*   Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.
:::*   Show the length of the generated de Bruijn sequence.
:::*   (There are many possible de Bruijn sequences that solve this task,   one solution is shown on the ''discussion'' page).
:::*   Show the first and last   '''130'''   digits of the de Bruijn sequence.
:*   Verify that all four-digit (decimal)   '''1,000'''   PIN codes are contained within the de Bruijn sequence.
:::*   0000, 0001, 0002, 0003,   ...   9996, 9997, 9998, 9999   (note the leading zeros).
:*   Reverse the de Bruijn sequence.
:*   Again, perform the (above) verification test.
:*   Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.
:::*   Perform the verification test (again).   There should be four PIN codes missing.

(The last requirement is to ensure that the verification tests performs correctly.   The verification processes should list
any and all missing PIN codes.)

Show all output here, on this page.

;References:
:*   Wikipedia           entry:   de Bruijn sequence.
:*   MathWorld           entry:   de Bruijn sequence.
:*   An  OEIS  entry:   A166315 lexicographically earliest binary de Bruijn sequences, B(2,n)     --- Not B(10,4),   but possibly relevant.

Solution:
const val digits = "0123456789"

fun deBruijn(k: Int, n: Int): String {
    val alphabet = digits.substring(0, k)
    val a = ByteArray(k * n)
    val seq = mutableListOf<Byte>()
    fun db(t: Int, p: Int) {
        if (t > n) {
            if (n % p == 0) {
                seq.addAll(a.sliceArray(1..p).asList())
            }
        } else {
            a[t] = a[t - p]
            db(t + 1, p)
            var j = a[t - p] + 1
            while (j < k) {
                a[t] = j.toByte()
                db(t + 1, t)
                j++
            }
        }
    }
    db(1, 1)
    val buf = StringBuilder()
    for (i in seq) {
        buf.append(alphabet[i.toInt()])
    }
    val b = buf.toString()
    return b + b.subSequence(0, n - 1)
}

fun allDigits(s: String): Boolean {
    for (c in s) {
        if (c < '0' || '9' < c) {
            return false
        }
    }
    return true
}

fun validate(db: String) {
    val le = db.length
    val found = MutableList(10_000) { 0 }
    val errs = mutableListOf<String>()
    // Check all strings of 4 consecutive digits within 'db'
    // to see if all 10,000 combinations occur without duplication.
    for (i in 0 until le - 3) {
        val s = db.substring(i, i + 4)
        if (allDigits(s)) {
            val n = s.toInt()
            found[n]++
        }
    }
    for (i in 0 until 10_000) {
        if (found[i] == 0) {
            errs.add("    PIN number %04d missing".format(i))
        } else if (found[i] > 1) {
            errs.add("    PIN number %04d occurs %d times".format(i, found[i]))
        }
    }
    val lerr = errs.size
    if (lerr == 0) {
        println("  No errors found")
    } else {
        val pl = if (lerr == 1) {
            ""
        } else {
            "s"
        }
        println("  $lerr error$pl found:")
        println(errs.joinToString("\n"))
    }
}

fun main() {
    var db = deBruijn(10, 4)
    val le = db.length

    println("The length of the de Bruijn sequence is $le")
    println("\nThe first 130 digits of the de Bruijn sequence are: ${db.subSequence(0, 130)}")
    println("\nThe last 130 digits of the de Bruijn sequence are: ${db.subSequence(le - 130, le)}")

    println("\nValidating the deBruijn sequence:")
    validate(db)

    println("\nValidating the reversed deBruijn sequence:")
    validate(db.reversed())

    val bytes = db.toCharArray()
    bytes[4443] = '.'
    db = String(bytes)
    println("\nValidating the overlaid deBruijn sequence:")
    validate(db)
}


Deepcopy

Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics.

This is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.

If this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.

The task should show:

* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.

* Any limitations of the method.

* That the structure and its copy are different.

* Suitable links to external documentation for common libraries.

Solution:
// Version 1.2.31

import java.io.Serializable
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.ObjectOutputStream
import java.io.ObjectInputStream

fun <T : Serializable> deepCopy(obj: T?): T? {
    if (obj == null) return null
    val baos = ByteArrayOutputStream()
    val oos  = ObjectOutputStream(baos)
    oos.writeObject(obj)
    oos.close()
    val bais = ByteArrayInputStream(baos.toByteArray())
    val ois  = ObjectInputStream(bais)
    @Suppress("unchecked_cast")
    return ois.readObject() as T
}

class Person(
    val name: String,
    var age: Int,
    val sex: Char,
    var income: Double,
    var partner: Person?
) : Serializable

fun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) {
    with (p3) {
        println("Name    : $name")
        println("Age     : $age")
        println("Sex     : $sex")
        println("Income  : $income")
        if (p4 == null) {
            println("Partner : None")
        }
        else {
            println("Partner :-")
            with (p4) {
                println("  Name   : $name")
                println("  Age    : $age")
                println("  Sex    : $sex")
                println("  Income : $income")
            }
        }
        println("\nSame person as original '$name' == ${p1 === p3}")
        if (p4 != null) {
            println("Same person as original '${p2!!.name}' == ${p2 === p4}")
        }
    }
    println()
}

fun main(args: Array<String>) {
    var p1 = Person("John", 35, 'M', 50000.0, null)
    val p2 = Person("Jane", 32, 'F', 25000.0, p1)
    p1.partner = p2
    var p3 = deepCopy(p1)
    val p4 = p3!!.partner
    printDetails(p1, p2, p3, p4)

    println("..or, say, after 2 years have elapsed:-\n")
    with (p1) {
        age = 37
        income = 55000.0
        partner = null
    }
    p3 = deepCopy(p1)
    printDetails(p1, null, p3!!, null)
}


Deming's funnel

W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings.  In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern.  He applied a sequence of "rules" to try to improve performance.  In each case the experiment begins with the funnel positioned directly over the target.

* '''Rule 1''': The funnel remains directly above the target.
* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop.  E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.
* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment.  E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.
* '''Rule 4''': The funnel is moved directly over the last place a marble landed.

Apply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys.  '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule.

Note that rules 2, 3, and 4 give successively worse results.  Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.

'''Stretch goal 1''': Generate fresh pseudorandom data.  The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.

'''Stretch goal 2''': Show scatter plots of all four results.

;Further information:
* Further explanation and interpretation
* Video demonstration of the funnel experiment at the Mayo Clinic.

Solution:
// version 1.1.3

typealias Rule = (Double, Double) -> Double

val dxs = doubleArrayOf(
    -0.533,  0.270,  0.859, -0.043, -0.205, -0.127, -0.071,  0.275,
     1.251, -0.231, -0.401,  0.269,  0.491,  0.951,  1.150,  0.001,
    -0.382,  0.161,  0.915,  2.080, -2.337,  0.034, -0.126,  0.014,
     0.709,  0.129, -1.093, -0.483, -1.193,  0.020, -0.051,  0.047,
    -0.095,  0.695,  0.340, -0.182,  0.287,  0.213, -0.423, -0.021,
    -0.134,  1.798,  0.021, -1.099, -0.361,  1.636, -1.134,  1.315,
     0.201,  0.034,  0.097, -0.170,  0.054, -0.553, -0.024, -0.181,
    -0.700, -0.361, -0.789,  0.279, -0.174, -0.009, -0.323, -0.658,
     0.348, -0.528,  0.881,  0.021, -0.853,  0.157,  0.648,  1.774,
    -1.043,  0.051,  0.021,  0.247, -0.310,  0.171,  0.000,  0.106,
     0.024, -0.386,  0.962,  0.765, -0.125, -0.289,  0.521,  0.017,
     0.281, -0.749, -0.149, -2.436, -0.909,  0.394, -0.113, -0.598,
     0.443, -0.521, -0.799,  0.087
)

val dys = doubleArrayOf(
     0.136,  0.717,  0.459, -0.225,  1.392,  0.385,  0.121, -0.395,
     0.490, -0.682, -0.065,  0.242, -0.288,  0.658,  0.459,  0.000,
     0.426,  0.205, -0.765, -2.188, -0.742, -0.010,  0.089,  0.208,
     0.585,  0.633, -0.444, -0.351, -1.087,  0.199,  0.701,  0.096,
    -0.025, -0.868,  1.051,  0.157,  0.216,  0.162,  0.249, -0.007,
     0.009,  0.508, -0.790,  0.723,  0.881, -0.508,  0.393, -0.226,
     0.710,  0.038, -0.217,  0.831,  0.480,  0.407,  0.447, -0.295,
     1.126,  0.380,  0.549, -0.445, -0.046,  0.428, -0.074,  0.217,
    -0.822,  0.491,  1.347, -0.141,  1.230, -0.044,  0.079,  0.219,
     0.698,  0.275,  0.056,  0.031,  0.421,  0.064,  0.721,  0.104,
    -0.729,  0.650, -1.103,  0.154, -1.720,  0.051, -0.385,  0.477,
     1.537, -0.901,  0.939, -0.411,  0.341, -0.411,  0.106,  0.224,
    -0.947, -1.424, -0.542, -1.032
)

fun funnel(da: DoubleArray, rule: Rule): DoubleArray {
    var x = 0.0
    val result = DoubleArray(da.size)
    for ((i, d) in da.withIndex()) {
        result[i] = x + d
        x = rule(x, d)
    }
    return result
}

fun mean(da: DoubleArray) = da.average()

fun stdDev(da: DoubleArray): Double {
    val m = mean(da)
    return Math.sqrt(da.map { (it - m) * (it - m) }.average())
}

fun experiment(label: String, rule: Rule) {
    val rxs = funnel(dxs, rule)
    val rys = funnel(dys, rule)
    println("$label  :      x        y")
    println("Mean    :  ${"%7.4f, %7.4f".format(mean(rxs), mean(rys))}")
    println("Std Dev :  ${"%7.4f, %7.4f".format(stdDev(rxs), stdDev(rys))}")
    println()
}

fun main(args: Array<String>) {
    experiment("Rule 1") { _, _  -> 0.0 }
    experiment("Rule 2") { _, dz -> -dz }
    experiment("Rule 3") { z, dz -> -(z + dz) }
    experiment("Rule 4") { z, dz -> z + dz }
}


Department numbers

There is a highly organized city that has decided to assign a number to each of their departments:
::*   police department
::*   sanitation department
::*   fire department

Each department can have a number between   '''1'''   and   '''7'''   (inclusive).

The three department numbers are to be unique (different from each other) and must add up to   '''12'''.

The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.

;Task:
Write a computer program which outputs all valid combinations.

Possible output   (for the 1st and 14th solutions):

  --police--  --sanitation--  --fire--
      2             3            7
      6             5            1

Solution:
// version 1.1.2

fun main(args: Array<String>) {
    println("Police  Sanitation  Fire")
    println("------  ----------  ----")
    var count = 0
    for (i in 2..6 step 2) {
        for (j in 1..7) {
            if (j == i) continue
            for (k in 1..7) {
                if (k == i || k == j) continue
                if (i + j + k != 12) continue
                println("  $i         $j         $k")
                count++
            }
        }
    }
    println("\n$count valid combinations")
}


Detect division by zero

Write a function to detect a   ''divide by zero error''   without checking if the denominator is zero.

Solution:
// version 1.1

fun divideByZero(x: Int, y:Int): Boolean =
    try {
        x / y
        false
    } catch(e: ArithmeticException) {
        true
    }

fun main(args: Array<String>) {
    val x = 1
    val y = 0
    if (divideByZero(x, y)) {
        println("Attempted to divide by zero")
    } else {
        @Suppress("DIVISION_BY_ZERO")
        println("$x / $y = ${x / y}")
    }
}


Determinant and permanent

permanent of the matrix.

The determinant is given by
:: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i}
while the permanent is given by
::  \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i}
In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)

More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.

;Related task:
* [[Permutations by swapping]]

Solution:
// version 1.1.2

typealias Matrix = Array<DoubleArray>

fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
    val p = IntArray(n) { it }  // permutation
    val q = IntArray(n) { it }  // inverse permutation
    val d = IntArray(n) { -1 }  // direction = 1 or -1
    var sign = 1
    val perms = mutableListOf<IntArray>()
    val signs = mutableListOf<Int>()

    fun permute(k: Int) {
        if (k >= n) {
            perms.add(p.copyOf())
            signs.add(sign)
            sign *= -1
            return
        }
        permute(k + 1)
        for (i in 0 until k) {
            val z = p[q[k] + d[k]]
            p[q[k]] = z
            p[q[k] + d[k]] = k
            q[z] = q[k]
            q[k] += d[k]
            permute(k + 1)
        }
        d[k] *= -1
    }

    permute(0)
    return perms to signs
}

fun determinant(m: Matrix): Double {
    val (sigmas, signs) = johnsonTrotter(m.size)
    var sum = 0.0
    for ((i, sigma) in sigmas.withIndex()) {
        var prod = 1.0
        for ((j, s) in sigma.withIndex()) prod *= m[j][s]
        sum += signs[i] * prod
    }
    return sum
}

fun permanent(m: Matrix) : Double {
    val (sigmas, _) = johnsonTrotter(m.size)
    var sum = 0.0
    for (sigma in sigmas) {
        var prod = 1.0
        for ((i, s) in sigma.withIndex()) prod *= m[i][s]
        sum += prod
    }
    return sum
}

fun main(args: Array<String>) {
    val m1 = arrayOf(
        doubleArrayOf(1.0)
    )

    val m2 = arrayOf(
        doubleArrayOf(1.0, 2.0),
        doubleArrayOf(3.0, 4.0)
    )

    val m3 = arrayOf(
        doubleArrayOf(2.0, 9.0, 4.0),
        doubleArrayOf(7.0, 5.0, 3.0),
        doubleArrayOf(6.0, 1.0, 8.0)
    )

    val m4 = arrayOf(
        doubleArrayOf( 1.0,  2.0,  3.0,  4.0),
        doubleArrayOf( 4.0,  5.0,  6.0,  7.0),
        doubleArrayOf( 7.0,  8.0,  9.0, 10.0),
        doubleArrayOf(10.0, 11.0, 12.0, 13.0)
    )

    val matrices = arrayOf(m1, m2, m3, m4)
    for (m in matrices) {
        println("m${m.size} -> ")
        println("  determinant = ${determinant(m)}")
        println("  permanent   = ${permanent(m)}\n")
    }
}


Determine if a string has all the same characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are the same
::::*    indicate if or which character is different from the previous character
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as all the same character(s)
::*   process the strings from left-to-right
::*   if       all the same character,   display a message saying such
::*   if                  not all the same character,   then:
::::*    display a message saying such
::::*    display what character is different
::::*    only the 1st different character need be displayed
::::*    display where the different character is in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the different character

Use (at least) these seven test values   (strings):
:::*   a string of length   0   (an empty string)
:::*   a string of length   3   which contains three blanks
:::*   a string of length   1   which contains:   '''2'''
:::*   a string of length   3   which contains:   '''333'''
:::*   a string of length   3   which contains:   '''.55'''
:::*   a string of length   6   which contains:   '''tttTTT'''
:::*   a string of length   9   with a blank in the middle:   '''4444   444k'''

Show all output here on this page.

Solution:
fun analyze(s: String) {
    println("Examining [$s] which has a length of ${s.length}:")
    if (s.length > 1) {
        val b = s[0]
        for ((i, c) in s.withIndex()) {
            if (c != b) {
                println("    Not all characters in the string are the same.")
                println("    '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i")
                return
            }
        }
    }
    println("    All characters in the string are the same.")
}

fun main() {
    val strs = listOf("", "   ", "2", "333", ".55", "tttTTT", "4444 444k")
    for (str in strs) {
        analyze(str)
    }
}


Determine if a string has all unique characters

Given a character string   (which may be empty, or have a length of zero characters):
::*   create a function/procedure/routine to:
::::*    determine if all the characters in the string are unique
::::*    indicate if or which character is duplicated and where
::*   display each string and its length   (as the strings are being examined)
::*   a zero-length (empty) string shall be considered as unique
::*   process the strings from left-to-right
::*   if       unique,   display a message saying such
::*   if                  not unique,   then:
::::*    display a message saying such
::::*    display what character is duplicated
::::*    only the 1st non-unique character need be displayed
::::*    display where "both" duplicated characters are in the string
::::*    the above messages can be part of a single message
::::*    display the hexadecimal value of the duplicated character

Use (at least) these five test values   (strings):
:::*   a string of length     0   (an empty string)
:::*   a string of length     1   which is a single period   ('''.''')
:::*   a string of length     6   which contains:   '''abcABC'''
:::*   a string of length     7   which contains a blank in the middle:   '''XYZ  ZYX'''
:::*   a string of length         36   which   ''doesn't''   contain the letter "oh":
::::::::  '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''

Show all output here on this page.

Solution:
import java.util.HashMap

fun main() {
    System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "String", "Length", "All Unique", "1st Diff", "Hex", "Positions")
    System.out.printf("%-40s  %2s  %10s  %8s  %s  %s%n", "------------------------", "------", "----------", "--------", "---", "---------")
    for (s in arrayOf("", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ")) {
        processString(s)
    }
}

private fun processString(input: String) {
    val charMap: MutableMap<Char, Int?> = HashMap()
    var dup = 0.toChar()
    var index = 0
    var pos1 = -1
    var pos2 = -1
    for (key in input.toCharArray()) {
        index++
        if (charMap.containsKey(key)) {
            dup = key
            pos1 = charMap[key]!!
            pos2 = index
            break
        }
        charMap[key] = index
    }
    val unique = if (dup.toInt() == 0) "yes" else "no"
    val diff = if (dup.toInt() == 0) "" else "'$dup'"
    val hex = if (dup.toInt() == 0) "" else Integer.toHexString(dup.toInt()).toUpperCase()
    val position = if (dup.toInt() == 0) "" else "$pos1 $pos2"
    System.out.printf("%-40s  %-6d  %-10s  %-8s  %-3s  %-5s%n", input, input.length, unique, diff, hex, position)
}


Determine if a string is collapsible

Determine if a character string is   ''collapsible''.

And if so,   collapse the string   (by removing   ''immediately repeated''   characters).

If a character string has   ''immediately repeated''   character(s),   the repeated characters are to be
deleted (removed),   but not the primary (1st) character(s).

An   ''immediately repeated''   character is any character that is   immediately   followed by an
identical character (or characters).   Another word choice could've been   ''duplicated character'',   but that
might have ruled out   (to some readers)   triplicated characters   ***   or more.

{This Rosetta Code task was inspired by a newly introduced   (as of around November 2019)   '''PL/I'''   BIF:   '''collapse'''.}

;Examples:
In the following character string:

  The better the 4-wheel drive, the further you'll be from help when ya get stuck!

Only the 2nd   '''t''',   '''e''', and   '''l'''   are repeated characters,   indicated
by underscores (above),   even though they (those characters) appear elsewhere in the character string.

So, after ''collapsing'' the string, the result would be:

  The beter the 4-whel drive, the further you'l be from help when ya get stuck!

Another example:
In the following character string:

  headmistressship

The "collapsed" string would be:

  headmistreship

;Task:
Write a subroutine/function/procedure/routine***   to
locate   ''repeated''   characters and   ''collapse''   (delete)   them from the character
string.   The character string can be processed from either direction.

Show all output here, on this page:
:*   the   original string and its length
:*   the       resultant string and its length
:*   the above strings should be "bracketed" with   '''<<<'''   and   '''>>>'''   (to delineate blanks)
;*   <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here>>>>>>

Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except
the 1st string:

  string
  number
         ++
    1    |+-----------------------------------------------------------------------+   <######  a null string  (length zero)
    2    |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |
    3    |..1111111111111111111111111111111111111111111111111111111111111117777888|
    4    |I never give 'em hell, I just tell the truth, and they think it's hell. |
    5    |                                                    --- Harry S Truman  |   <######  has many repeated blanks
         +------------------------------------------------------------------------+

Solution:
fun collapse(s: String): String {
    val cs = StringBuilder()
    var last: Char = 0.toChar()
    for (c in s) {
        if (c != last) {
            cs.append(c)
            last = c
        }
    }
    return cs.toString()
}

fun main() {
    val strings = arrayOf(
        "",
        "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                   ---  Harry S Truman  ",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship",
        "aardvark"
    )
    for (s in strings) {
        val c = collapse(s)
        println("original : length = ${s.length}, string = «««$s»»»")
        println("collapsed : length = ${c.length}, string = «««$c»»»")
        println()
    }
}


Determine if a string is squeezable

Determine if a character string is   ''squeezable''.

And if so,   squeeze the string   (by removing any number of
a   ''specified''   ''immediately repeated''   character).

This task is very similar to the task     '''Determine if a character string is collapsible'''     except
that only a specified character is   ''squeezed''   instead of any character that is ''immediately repeated''.

If a character string has a specified   ''immediately repeated''   character(s),   the repeated characters are to be
deleted (removed),   but not the primary (1st) character(s).

A specified   ''immediately repeated''   character is any specified character that is   immediately
followed by an identical character (or characters).   Another word choice could've been   ''duplicated
character'',   but that might have ruled out   (to some readers)   triplicated characters   ***   or more.

{This Rosetta Code task was inspired by a newly introduced   (as of around
November 2019)   '''PL/I'''   BIF:   '''squeeze'''.}

;Examples:
In the following character string with a specified   ''immediately repeated''   character of   '''e''':

  The better the 4-wheel drive, the further you'll be from help when ya get stuck!

Only the 2nd   '''e'''   is an specified repeated character,   indicated by an underscore
(above),   even though they (the characters) appear elsewhere in the character string.

So, after ''squeezing'' the string, the result would be:

  The better the 4-whel drive, the further you'll be from help when ya get stuck!

Another example:
In the following character string,   using a specified immediately repeated character   '''s''':

  headmistressship

The "squeezed" string would be:

  headmistreship

;Task:
Write a subroutine/function/procedure/routine***   to locate a   ''specified immediately repeated''   character
and   ''squeeze''   (delete)   them from the character string.   The
character string can be processed from either direction.

Show all output here, on this page:
:*   the   specified repeated character   (to be searched for and possibly ''squeezed''):
:*   the   original string and its length
:*   the       resultant string and its length
:*   the above strings should be "bracketed" with   '''<<<'''   and   '''>>>'''   (to delineate blanks)
;*   <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers,   shown used here>>>>>>

Use (at least) the following five strings,   all strings are length seventy-two (characters, including blanks),   except
the 1st string:

                                                                                immediately
  string                                                                            repeated
  number                                                                            character
                                                                                ( |   a blank,  a minus,  a seven,  a period)
         ++
    1    |+-----------------------------------------------------------------------+    ' '    <######  a null string  (length zero)
    2    |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln |    '-'
    3    |..1111111111111111111111111111111111111111111111111111111111111117777888|    '7'
    4    |I never give 'em hell, I just tell the truth, and they think it's hell. |    '.'
    5    |                                                    --- Harry S Truman  |  (below)  <######  has many repeated blanks
         +------------------------------------------------------------------------+     |
                                                                                |
                                                                                |
         For the 5th string  (Truman's signature line),  use each of these  specified immediately  repeated characters:
                                   *  a blank
                                   *  a minus
                                   *  a lowercase  '''r'''

Note:   there should be seven results shown,   one each for the 1st four strings,   and three results for
the 5th string.

Solution:
fun main() {
    val testStrings = arrayOf(
        "",
        "\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln ",
        "..1111111111111111111111111111111111111111111111111111111111111117777888",
        "I never give 'em hell, I just tell the truth, and they think it's hell. ",
        "                                                    --- Harry S Truman  ",
        "122333444455555666666777777788888888999999999",
        "The better the 4-wheel drive, the further you'll be from help when ya get stuck!",
        "headmistressship")
    val testChar = arrayOf(
        " ",
        "-",
        "7",
        ".",
        " -r",
        "5",
        "e",
        "s")
    for (testNum in testStrings.indices) {
        val s = testStrings[testNum]
        for (c in testChar[testNum].toCharArray()) {
            val result = squeeze(s, c)
            System.out.printf("use: '%c'%nold:  %2d >>>%s<<<%nnew:  %2d >>>%s<<<%n%n", c, s.length, s, result.length, result)
        }
    }
}

private fun squeeze(input: String, include: Char): String {
    val sb = StringBuilder()
    for (i in input.indices) {
        if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {
            sb.append(input[i])
        }
    }
    return sb.toString()
}


Determine if two triangles overlap

Solution:
// version 1.1.0

typealias Point = Pair<Double, Double>

data class Triangle(var p1: Point, var p2: Point, var p3: Point) {
    override fun toString() = "Triangle: $p1, $p2, $p3"
}

fun det2D(t: Triangle): Double {
    val (p1, p2, p3) = t
    return  p1.first * (p2.second - p3.second) +
            p2.first * (p3.second - p1.second) +
            p3.first * (p1.second - p2.second)
}

fun checkTriWinding(t: Triangle, allowReversed: Boolean) {
    val detTri = det2D(t)
    if (detTri < 0.0) {
        if (allowReversed) {
           val a = t.p3
	   t.p3  = t.p2
	   t.p2 =  a
        }
        else throw RuntimeException("Triangle has wrong winding direction")
    }
}

fun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps

fun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps

fun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0,
             allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean {
    // Triangles must be expressed anti-clockwise
    checkTriWinding(t1, allowReversed)
    checkTriWinding(t2, allowReversed)
    // 'onBoundary' determines whether points on boundary are considered as colliding or not
    val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk
    val lp1 = listOf(t1.p1, t1.p2, t1.p3)
    val lp2 = listOf(t2.p1, t2.p2, t2.p3)

    // for each edge E of t1
    for (i in 0 until 3) {
        val j = (i + 1) % 3
        // Check all points of t2 lay on the external side of edge E.
        // If they do, the triangles do not overlap.
	if (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&
            chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&
            chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false
    }

    // for each edge E of t2
    for (i in 0 until 3) {
        val j = (i + 1) % 3
        // Check all points of t1 lay on the external side of edge E.
        // If they do, the triangles do not overlap.
        if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&
            chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&
            chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false
    }

    // The triangles overlap
    return true
}

fun main(args: Array<String>) {
    var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)
    var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0)
    println("$t1 and\n$t2")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    // need to allow reversed for this pair to avoid exception
    t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0)
    t2 = t1
    println("\n$t1 and\n$t2")
    println(if (triTri2D(t1, t2, 0.0, true)) "overlap (reversed)" else "do not overlap")

    t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)
    t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0)
    println("\n$t1 and\n$t2")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    t1.p3 = 2.5 to 5.0
    t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0)
    println("\n$t1 and\n$t2")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0)
    t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0)
    println("\n$t1 and\n$t2")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0)
    println("\n$t1 and\n$t2")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0)
    t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1)
    println("\n$t1 and\n$t2")
    println("which have only a single corner in contact, if boundary points collide")
    println(if (triTri2D(t1, t2)) "overlap" else "do not overlap")

    println("\n$t1 and\n$t2")
    println("which have only a single corner in contact, if boundary points do not collide")
    println(if (triTri2D(t1, t2, 0.0, false, false)) "overlap" else "do not overlap")
}