Balanced ternary

Balanced ternary is a way of representing numbers.  Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1.

;Examples:
Decimal 11 = 32 + 31 - 30, thus it can be written as "++-"

Decimal  6 = 32 - 31 + 0 x 30, thus it can be written as "+-0"

;Task:
Implement balanced ternary representation of integers with the following:
# Support arbitrarily large integers, both positive and negative;
# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).
# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary).  If your native integers can't support arbitrary length, overflows during conversion must be indicated.
# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.
# Make your implementation efficient, with a reasonable definition of "efficient" (and with a reasonable definition of "reasonable").

'''Test case''' With balanced ternaries ''a'' from string "+-0++0+", ''b'' from native integer -436, ''c'' "+-++-":
* write out ''a'', ''b'' and ''c'' in decimal notation;
* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.

'''Note:''' The pages floating point balanced ternary.

Solution:
// version 1.1.3

import java.math.BigInteger

val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE
val bigThree = BigInteger.valueOf(3L)

data class BTernary(private var value: String) : Comparable<BTernary> {

    init {
        require(value.all { it in "0+-" })
        value = value.trimStart('0')
    }

    constructor(v: Int) : this(BigInteger.valueOf(v.toLong()))

    constructor(v: BigInteger) : this("") {
        value = toBT(v)
    }

    private fun toBT(v: BigInteger): String {
        if (v < bigZero) return flip(toBT(-v))
        if (v == bigZero) return ""
        val rem = mod3(v)
        return when (rem) {
            bigZero -> toBT(v / bigThree) + "0"
            bigOne  -> toBT(v / bigThree) + "+"
            else    -> toBT((v + bigOne) / bigThree) + "-"
        }
    }

    private fun flip(s: String): String {
        val sb = StringBuilder()
        for (c in s) {
            sb.append(when (c) {
                '+'  -> "-"
                '-'  -> "+"
                else -> "0"
            })
        }
        return sb.toString()
    }

    private fun mod3(v: BigInteger): BigInteger {
        if (v > bigZero) return v % bigThree
        return ((v % bigThree) + bigThree) % bigThree
    }

    fun toBigInteger(): BigInteger {
        val len = value.length
        var sum = bigZero
        var pow = bigOne
        for (i in 0 until len) {
            val c = value[len - i - 1]
            val dig = when (c) {
                '+'  -> bigOne
                '-'  -> -bigOne
                else -> bigZero
            }
            if (dig != bigZero) sum += dig * pow
            pow *= bigThree
        }
        return sum
    }

    private fun addDigits(a: Char, b: Char, carry: Char): String {
        val sum1 = addDigits(a, b)
        val sum2 = addDigits(sum1.last(), carry)
        return when {
            sum1.length == 1 -> sum2
            sum2.length == 1 -> sum1.take(1) + sum2
            else             -> sum1.take(1)
        }
    }

    private fun addDigits(a: Char, b: Char): String =
        when {
            a == '0' -> b.toString()
            b == '0' -> a.toString()
            a == '+' -> if (b == '+') "+-" else "0"
            else     -> if (b == '+') "0" else "-+"
        }

    operator fun plus(other: BTernary): BTernary {
        var a = this.value
        var b = other.value
        val longer = if (a.length > b.length) a else b
        var shorter = if (a.length > b.length) b else a
        while (shorter.length < longer.length) shorter = "0" + shorter
        a = longer
        b = shorter
        var carry = '0'
        var sum = ""
        for (i in 0 until a.length) {
            val place = a.length - i - 1
            val digisum = addDigits(a[place], b[place], carry)
            carry = if (digisum.length != 1) digisum[0] else '0'
            sum = digisum.takeLast(1) + sum
        }
        sum = carry.toString() + sum
        return BTernary(sum)
    }

    operator fun unaryMinus() = BTernary(flip(this.value))

    operator fun minus(other: BTernary) = this + (-other)

    operator fun times(other: BTernary): BTernary {
        var that = other
        val one = BTernary(1)
        val zero = BTernary(0)
        var mul = zero
        var flipFlag = false
        if (that < zero) {
            that = -that
            flipFlag = true
        }
        var i = one
        while (i <= that) {
            mul += this
            i += one
        }
        if (flipFlag) mul = -mul
        return mul
    }

    override operator fun compareTo(other: BTernary) =
        this.toBigInteger().compareTo(other.toBigInteger())

    override fun toString() = value
}

fun main(args: Array<String>) {
    val a = BTernary("+-0++0+")
    val b = BTernary(-436)
    val c = BTernary("+-++-")
    println("a = ${a.toBigInteger()}")
    println("b = ${b.toBigInteger()}")
    println("c = ${c.toBigInteger()}")
    val bResult = a * (b - c)
    val iResult = bResult.toBigInteger()
    println("a * (b - c) = $bResult = $iResult")
}


Barnsley fern

A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).

;Task:
Create this fractal fern, using the following transformations:
* f1   (chosen 1% of the time)
         xn + 1 = 0
         yn + 1 = 0.16 yn

* f2   (chosen 85% of the time)
         xn + 1 = 0.85 xn + 0.04 yn
         yn + 1 = -0.04 xn + 0.85 yn + 1.6

* f3   (chosen 7% of the time)
         xn + 1 = 0.2 xn - 0.26 yn
         yn + 1 = 0.23 xn + 0.22 yn + 1.6

* f4   (chosen 7% of the time)
         xn + 1 = -0.15 xn + 0.28 yn
         yn + 1 = 0.26 xn + 0.24 yn + 0.44.

Starting position: x = 0, y = 0

Solution:
// version 1.1.0

import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*

class BarnsleyFern(private val dim: Int) : JPanel() {
    private val img: BufferedImage

    init {
        preferredSize = Dimension(dim, dim)
        background = Color.black
        img = BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)
        createFern(dim, dim)
    }

    private fun createFern(w: Int, h: Int) {
        var x = 0.0
        var y = 0.0
        for (i in 0 until 200_000) {
            var tmpx: Double
            var tmpy: Double
            val r = Math.random()
            if (r <= 0.01) {
                tmpx = 0.0
                tmpy = 0.16 * y
            }
            else if (r <= 0.86) {
                tmpx =  0.85 * x + 0.04 * y
                tmpy = -0.04 * x + 0.85 * y + 1.6
            }
            else if (r <= 0.93) {
                tmpx = 0.2  * x - 0.26 * y
                tmpy = 0.23 * x + 0.22 * y + 1.6
            }
            else {
                tmpx = -0.15 * x + 0.28 * y
                tmpy =  0.26 * x + 0.24 * y + 0.44
            }
            x = tmpx
            y = tmpy
            img.setRGB(Math.round(w / 2.0 + x * w / 11.0).toInt(),
                       Math.round(h - y * h / 11.0).toInt(), 0xFF32CD32.toInt())
        }
    }

    override protected fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.drawImage(img, 0, 0, null)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        f.title = "Barnsley Fern"
        f.setResizable(false)
        f.add(BarnsleyFern(640), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.setVisible(true)
    }
}


Base64 decode data

See [[Base64 encode data]].

Now write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file.

When working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.

Solution:
import java.util.Base64

fun main() {
    val data =
        "VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g="
    val decoder = Base64.getDecoder()
    val decoded = decoder.decode(data)
    val decodedStr = String(decoded, Charsets.UTF_8)
    println(decodedStr)
}


Bell numbers

Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.

;So:

:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''

:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''

:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''

:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''

: and so on.

A simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.

;Task:

Write a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence.

If you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.

;See also:

:* '''OEIS:A000110 Bell or exponential numbers'''
:* '''OEIS:A011971 Aitken's array'''

Solution:
class BellTriangle(n: Int) {
    private val arr: Array<Int>

    init {
        val length = n * (n + 1) / 2
        arr = Array(length) { 0 }

        set(1, 0, 1)
        for (i in 2..n) {
            set(i, 0, get(i - 1, i - 2))
            for (j in 1 until i) {
                val value = get(i, j - 1) + get(i - 1, j - 1)
                set(i, j, value)
            }
        }
    }

    private fun index(row: Int, col: Int): Int {
        require(row > 0)
        require(col >= 0)
        require(col < row)
        return row * (row - 1) / 2 + col
    }

    operator fun get(row: Int, col: Int): Int {
        val i = index(row, col)
        return arr[i]
    }

    private operator fun set(row: Int, col: Int, value: Int) {
        val i = index(row, col)
        arr[i] = value
    }
}

fun main() {
    val rows = 15
    val bt = BellTriangle(rows)

    println("First fifteen Bell numbers:")
    for (i in 1..rows) {
        println("%2d: %d".format(i, bt[i, 0]))
    }

    for (i in 1..10) {
        print("${bt[i, 0]}")
        for (j in 1 until i) {
            print(", ${bt[i, j]}")
        }
        println()
    }
}


Benford's law

{{Wikipedia|Benford's_law}}

'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data.

In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale.

Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.

This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.

A set of numbers is said to satisfy Benford's law if the leading digit d  (d \in \{1, \ldots, 9\}) occurs with probability

:::: P(d) = \log_{10}(d+1)-\log_{10}(d) = \log_{10}\left(1+\frac{1}{d}\right)

For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).

Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained.

You can generate them or load them from a file; whichever is easiest.

Display your actual vs expected distribution.

''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

;See also:
* numberphile.com.
* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.

Solution:
import java.math.BigInteger

interface NumberGenerator {
    val numbers: Array<BigInteger>
}

class Benford(ng: NumberGenerator) {
    override fun toString() = str

    private val firstDigits = IntArray(9)
    private val count = ng.numbers.size.toDouble()
    private val str: String

    init {
        for (n in ng.numbers) {
            firstDigits[n.toString().substring(0, 1).toInt() - 1]++
        }

        str = with(StringBuilder()) {
            for (i in firstDigits.indices) {
                append(i + 1).append('\t').append(firstDigits[i] / count)
                append('\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\n')
            }

            toString()
        }
    }
}

object FibonacciGenerator : NumberGenerator {
    override val numbers: Array<BigInteger> by lazy {
        val fib = Array<BigInteger>(1000, { BigInteger.ONE })
        for (i in 2 until fib.size)
            fib[i] = fib[i - 2].add(fib[i - 1])
        fib
    }
}

fun main(a: Array<String>) = println(Benford(FibonacciGenerator))


Best shuffle

Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible.

A shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.

Display the result as follows:

 original string, shuffled string, (score)

The score gives the number of positions whose character value did ''not'' change.

;Example:
 tree, eetr, (0)

;Test cases:
 abracadabra
 seesaw
 elk
 grrrrrr
 up
 a

;Related tasks
*   [[Anagrams/Deranged anagrams]]
*   [[Permutations/Derangements]]

Solution:
import java.util.Random

object BestShuffle {
    operator fun invoke(s1: String) : String {
        val s2 = s1.toCharArray()
        s2.shuffle()
        for (i in s2.indices)
            if (s2[i] == s1[i])
                for (j in s2.indices)
                    if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {
                        val tmp = s2[i]
                        s2[i] = s2[j]
                        s2[j] = tmp
                        break
                    }
        return s1 + ' ' + String(s2) + " (" + s2.count(s1) + ')'
    }

    private fun CharArray.shuffle() {
        val rand = Random()
        for (i in size - 1 downTo 1) {
            val r = rand.nextInt(i + 1)
            val tmp = this[i]
            this[i] = this[r]
            this[r] = tmp
        }
    }

    private fun CharArray.count(s1: String) : Int {
        var count = 0
        for (i in indices)
            if (s1[i] == this[i]) count++
        return count
    }
}

fun main(words: Array<String>) = words.forEach { println(BestShuffle(it)) }


Bioinformatics/base count

Given this string representing ordered DNA bases:

CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG
CTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG
AGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT
GGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT
CGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG
TCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA
TTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT
CGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG
TCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC
GACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT

;Task:
:*   "Pretty print" the sequence followed by a summary of the counts of each of the bases:   ('''A''', '''C''', '''G''', and '''T''')   in the sequence
:*   print the total count of each base in the string.

Solution:
fun printSequence(sequence: String, width: Int = 50) {
    fun <K, V> printWithLabel(k: K, v: V) {
        val label = k.toString().padStart(5)
        println("$label: $v")
    }

    println("SEQUENCE:")
    sequence.chunked(width).withIndex().forEach { (i, line) ->
        printWithLabel(i*width + line.length, line)
    }
    println("BASE:")
    sequence.groupingBy { it }.eachCount().forEach { (k, v) ->
        printWithLabel(k, v)
    }
    printWithLabel("TOTALS", sequence.length)
}

const val BASE_SEQUENCE = "CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT"

fun main() {
    printSequence(BASE_SEQUENCE)
}


Bitcoin/address validation

Write a program that takes a bitcoin address as argument,
and checks whether or not this address is valid.

A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:
:::*   0   zero
:::*   O   uppercase oh
:::*   I   uppercase eye
:::*   l   lowercase ell

With this encoding, a bitcoin address encodes 25 bytes:
* the first byte is the version number, which will be zero for this task ;
* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task:  you can consider them a pure arbitrary data ;
* the last four bytes are a checksum check.  They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.

To check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.

The program can either return a boolean value or throw an exception when not valid.

You can use a digest library for [[SHA-256]].

;Example of a bitcoin address:

 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i

It doesn't belong to anyone and is part of the test suite of the bitcoin software.
You can change a few characters in this string and check that it'll fail the test.

Solution:
import java.security.MessageDigest

object Bitcoin {
    private const val ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

    private fun ByteArray.contentEquals(other: ByteArray): Boolean {
        if (this.size != other.size) return false
        return (0 until this.size).none { this[it] != other[it] }
    }

    private fun decodeBase58(input: String): ByteArray? {
        val output = ByteArray(25)
        for (c in input) {
            var p = ALPHABET.indexOf(c)
            if (p == -1) return null
            for (j in 24 downTo 1) {
                p += 58 * (output[j].toInt() and 0xff)
                output[j] = (p % 256).toByte()
                p = p shr 8
            }
            if (p != 0) return null
        }
        return output
    }

    private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray {
        if (recursion == 0) return data
        val md = MessageDigest.getInstance("SHA-256")
        md.update(data.sliceArray(start until start + len))
        return sha256(md.digest(), 0, 32, recursion - 1)
    }

    fun validateAddress(address: String): Boolean {
        if (address.length !in 26..35) return false
        val decoded = decodeBase58(address)
        if (decoded == null) return false
        val hash = sha256(decoded, 0, 21, 2)
        return hash.sliceArray(0..3).contentEquals(decoded.sliceArray(21..24))
    }
}

fun main(args: Array<String>) {
    val addresses = arrayOf(
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j",
        "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X",
        "1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
        "1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i",
        "BZbvjr",
        "i55j",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz",
        "1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9",
        "1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I"
    )
    for (address in addresses)
        println("${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) "valid" else "invalid"}")
}


Bitwise IO

The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of
bits, most significant bit first. While the output of a asciiprint "STRING" is the ASCII byte sequence
"S", "T", "R", "I", "N", "G", the output of a "print" of the bits sequence
0101011101010 (13 bits) must be 0101011101010; real I/O is performed always
''quantized'' by byte (avoiding endianness issues and relying on underlying
buffering for performance), therefore you must obtain as output the bytes
0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.

As test, you can implement a '''rough''' (e.g. don't care about error handling or
other issues) compression/decompression program for ASCII sequences
of bytes, i.e. bytes for which the most significant bit is always unused, so that you can write
seven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).

These bit oriented I/O functions can be used to implement compressors and
decompressors; e.g. Dynamic and Static Huffman encodings use variable length
bits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''
nine (or more) bits long.

* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.
* Errors handling is not mandatory

Solution:
// version 1.2.31

import java.io.File

class BitFilter(val f: File, var accu: Int = 0, var bits: Int = 0) {

    private val bw = f.bufferedWriter()
    private val br = f.bufferedReader()

    fun write(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) {
        var nBits = _nBits
        var index = start + _shift / 8
        var shift = _shift % 8

        while (nBits != 0 || bits >= 8) {
            while (bits >= 8) {
                bits -= 8
                bw.write(accu ushr bits)
                accu = accu and ((1 shl bits) - 1)
            }
            while (bits < 8 && nBits != 0) {
                val b = buf[index].toInt()
                accu = (accu shl 1) or (((128 ushr shift) and b) ushr (7 - shift))
                nBits--
                bits++
                if (++shift == 8) { shift = 0; index++ }
            }
        }
    }

    fun read(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) {
        var nBits = _nBits
        var index = start + _shift / 8
        var shift = _shift % 8

        while (nBits != 0) {
            while (bits != 0 && nBits != 0) {
                val mask = 128 ushr shift
                if ((accu and (1 shl (bits - 1))) != 0)
                    buf[index] = (buf[index].toInt() or mask).toByte()
                else
                    buf[index] = (buf[index].toInt() and mask.inv()).toByte()
                nBits--
                bits--
                if (++shift >= 8) { shift = 0; index++ }
            }
            if (nBits == 0) break
            accu = (accu shl 8) or br.read()
            bits += 8
        }
    }

    fun closeWriter() {
        if (bits != 0) {
            accu = (accu shl (8 - bits))
            bw.write(accu)
        }
        bw.close()
        accu = 0
        bits = 0
    }

    fun closeReader() {
        br.close()
        accu = 0
        bits = 0
    }
}

fun main(args: Array<String>) {
    val s = "abcdefghijk".toByteArray(Charsets.UTF_8)
    val f = File("test.bin")
    val bf = BitFilter(f)

    /* for each byte in s, write 7 bits skipping 1 */
    for (i in 0 until s.size) bf.write(s, i, 7, 1)
    bf.closeWriter()

    /* read 7 bits and expand to each byte of s2 skipping 1 bit */
    val s2 = ByteArray(s.size)
    for (i in 0 until s2.size) bf.read(s2, i, 7, 1)
    bf.closeReader()
    println(String(s2, Charsets.UTF_8))
}


Box the compass

Avast me hearties!
There be many a land lubber that knows naught of the pirate ways and gives direction by degree!
They know not how to box the compass!

;Task description:
# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.
# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:
:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).

;Notes;
* The headings and indices can be calculated from this pseudocode:
for i in 0..32 inclusive:
    heading = i * 11.25
    case i %3:
      if 1: heading += 5.62; break
      if 2: heading -= 5.62; break
    end
    index = ( i mod 32) + 1
* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..

Solution:
// version 1.1.2

fun expand(cp: String): String {
    val sb = StringBuilder()
    for (c in cp) {
        sb.append(when (c) {
            'N'  -> "north"
            'E'  -> "east"
            'S'  -> "south"
            'W'  -> "west"
            'b'  -> " by "
            else -> "-"
        })
    }
    return sb.toString().capitalize()
}

fun main(args: Array<String>) {
    val cp = arrayOf(
        "N", "NbE", "N-NE", "NEbN", "NE", "NEbE", "E-NE", "EbN",
        "E", "EbS", "E-SE", "SEbE", "SE", "SEbS", "S-SE", "SbE",
        "S", "SbW", "S-SW", "SWbS", "SW", "SWbW", "W-SW", "WbS",
        "W", "WbN", "W-NW", "NWbW", "NW", "NWbN", "N-NW", "NbW"
    )
    println("Index  Degrees  Compass point")
    println("-----  -------  -------------")
    val f = "%2d     %6.2f   %s"
    for (i in 0..32) {
        val index  = i % 32
        var heading = i * 11.25
        when (i % 3) {
            1 -> heading += 5.62
            2 -> heading -= 5.62
        }
        println(f.format(index + 1, heading, expand(cp[index])))
    }
}


Brazilian numbers

Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.

Brazilian numbers are defined as:

The set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.

;E.G.:

:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.
:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.
:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.
:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.
:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.
:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.
:* ''and so on...''

All even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.
More common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''
The only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3.
All prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes >  2

;Task:

Write a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;

:* the first '''20''' Brazilian numbers;
:* the first '''20 odd''' Brazilian numbers;
:* the first '''20 prime''' Brazilian numbers;

;See also:

:* '''OEIS:A125134 - Brazilian numbers'''
:* '''OEIS:A257521 - Odd Brazilian numbers'''
:* '''OEIS:A085104 - Prime Brazilian numbers'''

Solution:
fun sameDigits(n: Int, b: Int): Boolean {
    var n2 = n
    val f = n % b
    while (true) {
        n2 /= b
        if (n2 > 0) {
            if (n2 % b != f) {
                return false
            }
        } else {
            break
        }
    }
    return true
}

fun isBrazilian(n: Int): Boolean {
    if (n < 7) return false
    if (n % 2 == 0) return true
    for (b in 2 until n - 1) {
        if (sameDigits(n, b)) {
            return true
        }
    }
    return false
}

fun isPrime(n: Int): Boolean {
    if (n < 2) return false
    if (n % 2 == 0) return n == 2
    if (n % 3 == 0) return n == 3
    var d = 5
    while (d * d <= n) {
        if (n % d == 0) return false
        d += 2
        if (n % d == 0) return false
        d += 4
    }
    return true
}

fun main() {
    val bigLim = 99999
    val limit = 20
    for (kind in ",odd ,prime".split(',')) {
        var quiet = false
        println("First $limit ${kind}Brazilian numbers:")
        var c = 0
        var n = 7
        while (c < bigLim) {
            if (isBrazilian(n)) {
                if (!quiet) print("%,d ".format(n))
                if (++c == limit) {
                    print("\n\n")
                    quiet = true
                }
            }
            if (quiet && kind != "") continue
            when (kind) {
                "" -> n++
                "odd " -> n += 2
                "prime" -> {
                    while (true) {
                        n += 2
                        if (isPrime(n)) break
                    }
                }
            }
        }
        if (kind == "") println("The %,dth Brazilian number is: %,d".format(bigLim + 1, n))
    }
}


Break OO privacy

Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy.
The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object  but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism.
The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.

Note that cheating on your type system is almost universally regarded
as unidiomatic at best, and poor programming practice at worst.
Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.

Solution:
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible

class ToBeBroken {
    @Suppress("unused")
    private val secret: Int = 42
}

fun main(args: Array<String>) {
    val tbb = ToBeBroken()
    val props = ToBeBroken::class.declaredMemberProperties
    for (prop in props) {
        prop.isAccessible = true  // make private properties accessible
        println("${prop.name} -> ${prop.get(tbb)}")
    }
}


Burrows–Wheeler transform

{{Wikipedia|Burrows-Wheeler_transform}}

The Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters.

This is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding.

More importantly, the transformation is reversible, without needing to store any additional data.

The BWT is thus a "free" method of improving the efficiency of text compression algorithms, costing only some extra computation.

Source: Burrows-Wheeler transform

Solution:
// Version 1.2.60

const val STX = "\u0002"
const val ETX = "\u0003"

fun bwt(s: String): String {
    if (s.contains(STX) || s.contains(ETX)) {
        throw RuntimeException("String can't contain STX or ETX")
    }
    val ss = STX + s + ETX
    val table = Array<String>(ss.length) { ss.substring(it) + ss.substring(0, it) }
    table.sort()
    return String(table.map { it[it.lastIndex] }.toCharArray())
}

fun ibwt(r: String): String {
    val len = r.length
    val table = Array<String>(len) { "" }
    repeat(len) {
        for (i in 0 until len) {
            table[i] = r[i].toString() + table[i]
        }
        table.sort()
    }
    for (row in table) {
        if (row.endsWith(ETX)) {
            return row.substring(1, len - 1)
        }
    }
    return ""
}

fun makePrintable(s: String): String {
    // substitute ^ for STX and | for ETX to print results
    return s.replace(STX, "^").replace(ETX, "|")
}

fun main(args: Array<String>) {
    val tests = listOf(
        "banana",
        "appellee",
        "dogwood",
        "TO BE OR NOT TO BE OR WANT TO BE OR NOT?",
        "SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES",
        "\u0002ABC\u0003"
    )
    for (test in tests) {
        println(makePrintable(test))
        print(" --> ")
        var t = ""
        try {
            t = bwt(test)
            println(makePrintable(t))
        }
        catch (ex: RuntimeException) {
            println("ERROR: " + ex.message)
        }
        val r = ibwt(t)
        println(" --> $r\n")
    }
}


CSV data manipulation

CSV spreadsheet files are suitable for storing tabular data in a relatively portable way.

The CSV format is flexible but somewhat ill-defined.

For present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.

;Task:
Read a CSV file, change some values and save the changes back to a file.

For this task we will use the following CSV file:

 C1,C2,C3,C4,C5
 1,5,9,13,17
 2,6,10,14,18
 3,7,11,15,19
 4,8,12,16,20

Suggestions

 Show how to add a column, headed 'SUM', of the sums of the rows.
 If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.

Solution:
// version 1.1.3

import java.io.File

fun main(args: Array<String>) {
    val lines = File("example.csv").readLines().toMutableList()
    lines[0] += ",SUM"
    for (i in 1 until lines.size) {
        lines[i] += "," + lines[i].split(',').sumBy { it.toInt() }
    }
    val text = lines.joinToString("\n")
    File("example2.csv").writeText(text)  // write to new file
    println(text)  // print to console
}


CSV to HTML translation

Consider a simplified CSV format where all rows are separated by a newline
and all columns are separated by commas.

No commas are allowed as field data, but the data may contain
other characters and character sequences that would
normally be   ''escaped''   when converted to HTML

;Task:
Create a function that takes a string representation of the CSV data
and returns a text string of an HTML table representing the CSV data.

Use the following  data as the CSV text to convert, and show your output.
: Character,Speech
: The multitude,The messiah! Show us the messiah!
: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!
: The multitude,Who are you?
: Brians mother,I'm his mother; that's who!
: The multitude,Behold his mother! Behold his mother!

;Extra credit:
''Optionally'' allow special formatting for the first row of the table as if it is the tables header row
(via  preferably; CSS if you must).

Solution:
// version 1.1.3

val csv =
    "Character,Speech\n" +
    "The multitude,The messiah! Show us the messiah!\n" +
    "Brians mother,<angry>Now you listen here! He's not the messiah; " +
    "he's a very naughty boy! Now go away!</angry>\n" +
    "The multitude,Who are you?\n" +
    "Brians mother,I'm his mother; that's who!\n" +
    "The multitude,Behold his mother! Behold his mother!"

fun main(args: Array<String>) {
    val i = "   "  // indent
    val sb = StringBuilder("
\n$i
\n$i$i")
    for (c in csv) {
        sb.append( when (c) {
            '\n' -> "	\n$i
\n$i
\n$i$i"
            ','  -> "	\n$i$i"
            '&'  -> "&"
            '\'' -> "'"
            '<'  -> "<"
            '>'  -> ">"
            else -> c.toString()
        })
    }
    sb.append("	\n$i
\n
")
    println(sb.toString())
    println()

    // now using first row as a table header
    sb.setLength(0)
    sb.append("
\n$i
\n$i$i
\n$i$i$i")
    val hLength = csv.indexOf('\n') + 1  // find length of first row including CR
    for (c in csv.take(hLength)) {
        sb.append( when (c) {
            '\n' -> "	\n$i$i
\n$i
\n$i
\n$i$i
\n$i$i$i"
            ','  -> "	\n$i$i$i"
            else -> c.toString()
        })
    }
    for (c in csv.drop(hLength)) {
        sb.append( when (c) {
            '\n' -> "	\n$i$i
\n$i$i
\n$i$i$i"
            ','  -> "	\n$i$i$i"
            '&'  -> "&"
            '\'' -> "'"
            '<'  -> "<"
            '>'  -> ">"
            else -> c.toString()
        })
    }
    sb.append("	\n$i$i
\n$i
\n
")
    println(sb.toString())
}


Calculating the value of e

Calculate the value of   ''e''.

(''e''   is also known as   ''Euler's number''   and   ''Napier's constant''.)

See details: Calculating the value of e

Solution:
// Version 1.2.40

import kotlin.math.abs

const val EPSILON = 1.0e-15

fun main(args: Array<String>) {
    var fact = 1L
    var e = 2.0
    var n = 2
    do {
        val e0 = e
        fact *= n++
        e += 1.0 / fact
    }
    while (abs(e - e0) >= EPSILON)
    println("e = %.15f".format(e))
}


Call a function

Demonstrate the different syntax and semantics provided for calling a function.

This may include:
:*   Calling a function that requires no arguments
:*   Calling a function with a fixed number of arguments
:*   Calling a function with optional arguments
:*   Calling a function with a variable number of arguments
:*   Calling a function with named arguments
:*   Using a function in statement context
:*   Using a function in first-class context within an expression
:*   Obtaining the return value of a function
:*   Distinguishing built-in functions and user-defined functions
:*   Distinguishing subroutines and functions
;*   Stating whether arguments are passed by value or by reference
;*   Is partial application possible and how

This task is ''not'' about defining functions.

Solution:
fun fun1() = println("No arguments")

fun fun2(i: Int) = println("One argument = $i")

fun fun3(i: Int, j: Int = 0) = println("One required argument = $i, one optional argument = $j")

fun fun4(vararg v: Int) = println("Variable number of arguments = ${v.asList()}")

fun fun5(i: Int) = i * i

fun fun6(i: Int, f: (Int) -> Int) = f(i)

fun fun7(i: Int): Double = i / 2.0

fun fun8(x: String) = { y: String -> x + " " + y }

fun main() {
    fun1()              // no arguments
    fun2(2)             // fixed number of arguments, one here
    fun3(3)             // optional argument, default value used here
    fun4(4, 5, 6)       // variable number of arguments
    fun3(j = 8, i = 7)  // using named arguments, order unimportant
    val b = false
    if (b) fun1() else fun2(9)        // statement context
    println(1 + fun6(4, ::fun5) + 3)  // first class context within an expression
    println(fun5(5))    // obtaining return value
    println(kotlin.math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver
    fun1()              // calling sub-routine which has a Unit return type by default
    println(fun7(11))   // calling function with a return type of Double (here explicit but can be implicit)
    println(fun8("Hello")("world"))   // partial application isn't supported though you can do this
}


Cantor set

Draw a Cantor set.

See details at this Wikipedia webpage:   Cantor set

Solution:
// Version 1.2.31

const val WIDTH = 81
const val HEIGHT = 5

val lines = List(HEIGHT) { CharArray(WIDTH) { '*' } }

fun cantor(start: Int, len: Int, index: Int) {
    val seg = len / 3
    if (seg == 0) return
    for (i in index until HEIGHT) {
        for (j in start + seg until start + seg * 2) lines[i][j] = ' '
    }
    cantor(start, seg, index + 1)
    cantor(start + seg * 2, seg, index + 1)
}

fun main(args: Array<String>) {
    cantor(0, WIDTH, 1)
    lines.forEach { println(it) }
}


Cartesian product of two or more lists

Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.

Demonstrate that your function/method correctly returns:
::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}

and, in contrast:
::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}

Also demonstrate, using your function/method, that the product of an empty list with any other list is empty.
:: {1, 2} x {} = {}
:: {} x {1, 2} = {}

For extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.

Use your n-ary Cartesian product function to show the following products:
:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}
:: {1, 2, 3} x {30} x {500, 100}
:: {1, 2, 3} x {} x {500, 100}

Solution:
// version 1.1.2

fun flattenList(nestList: List<Any>): List<Any> {
    val flatList = mutableListOf<Any>()

    fun flatten(list: List<Any>) {
        for (e in list) {
            if (e !is List<*>)
                flatList.add(e)
            else
                @Suppress("UNCHECKED_CAST")
                flatten(e as List<Any>)
        }
    }

    flatten(nestList)
    return flatList
}

operator fun List<Any>.times(other: List<Any>): List<List<Any>> {
    val prod = mutableListOf<List<Any>>()
    for (e in this) {
        for (f in other) {
            prod.add(listOf(e, f))
        }
    }
    return prod
}

fun nAryCartesianProduct(lists: List<List<Any>>): List<List<Any>> {
    require(lists.size >= 2)
    return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) }
}

fun printNAryProduct(lists: List<List<Any>>) {
    println("${lists.joinToString(" x ")} = ")
    println("[")
    println(nAryCartesianProduct(lists).joinToString("\n    ", "    "))
    println("]\n")
}

fun main(args: Array<String>) {
   println("[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}")
   println("[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}")
   println("[1, 2] x []     = ${listOf(1, 2) * listOf()}")
   println("[]     x [1, 2] = ${listOf<Any>() * listOf(1, 2)}")
   println("[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}")
   println()
   printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1)))
   printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100)))
   printNAryProduct(listOf(listOf(1, 2, 3), listOf<Int>(), listOf(500, 100)))
   printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b')))
}


Casting out nines

Task   (in three parts):

;Part 1
Write a procedure (say \mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.

Note that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.

With that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be "casting out nines", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.

;Part 2
Notwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:
: Consider the statement "318682 is 101558 + 217124 and squared is 101558217124" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).
: note that 318682 has the same checksum as (101558 + 217124);
: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);
: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.

Demonstrate that your procedure can be used to generate or filter a range of numbers with the property \mathit{co9}(k) = \mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

;Part 3
Considering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:
: \mathit{co9}(x) is the residual of x mod 9;
: the procedure can be extended to bases other than 9.

Demonstrate your algorithm by generating or filtering a range of numbers with the property k%(\mathit{Base}-1) == (k^2)%(\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.

;related tasks
* [[First perfect square in base N with N unique digits]]
* [[Kaprekar numbers]]

Solution:
// version 1.1.3

fun castOut(base: Int, start: Int, end: Int): List<Int> {
    val b = base - 1
    val ran = (0 until b).filter { it % b == (it * it) % b }
    var x = start / b
    val result = mutableListOf<Int>()
    while (true) {
        for (n in ran) {
            val k = b * x + n
            if (k < start) continue
            if (k > end) return result
            result.add(k)
        }
        x++
    }
}

fun main(args: Array<String>) {
    println(castOut(16, 1, 255))
    println()
    println(castOut(10, 1, 99))
    println()
    println(castOut(17, 1, 288))
}


Catalan numbers/Pascal's triangle

Print out the first   '''15'''   Catalan numbers by extracting them from Pascal's triangle.

;See:
*   Catalan Numbers and the Pascal Triangle.      This method enables calculation of Catalan Numbers using only addition and subtraction.

*   Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.
*   Sequence A000108 on OEIS has a lot of information on Catalan Numbers.

;Related Tasks:
[[Pascal's triangle]]

Solution:
// version 1.1.2

import java.math.BigInteger

val ONE = BigInteger.ONE

fun pascal(n: Int, k: Int): BigInteger {
    if (n == 0 || k == 0) return ONE
    val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
    val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }
    return num / den
}

fun catalanFromPascal(n: Int) {
    for (i in 1 until n step 2) {
        val mi = i / 2 + 1
        val catalan = pascal(i, mi) - pascal(i, mi - 2)
        println("${"%2d".format(mi)} : $catalan")
    }
}

fun main(args: Array<String>) {
    val n = 15
    catalanFromPascal(n * 2)
}


Catamorphism

''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.

;Task:
Show how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.

;See also:
* Wikipedia article:   Fold
* Wikipedia article:   Catamorphism

Solution:
fun main(args: Array<String>) {
    val a = intArrayOf(1, 2, 3, 4, 5)
    println("Array       : ${a.joinToString(", ")}")
    println("Sum         : ${a.reduce { x, y -> x + y }}")
    println("Difference  : ${a.reduce { x, y -> x - y }}")
    println("Product     : ${a.reduce { x, y -> x * y }}")
    println("Minimum     : ${a.reduce { x, y -> if (x < y) x else y }}")
    println("Maximum     : ${a.reduce { x, y -> if (x > y) x else y }}")
}


Chaocipher

Description:
The Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.

The algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.

;Task:
Code the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.

Solution:
// Version 1.2.40

enum class Mode { ENCRYPT, DECRYPT }

object Chao {
    private val lAlphabet = "HXUCZVAMDSLKPEFJRIGTWOBNYQ"
    private val rAlphabet = "PTLNBQDEOYSFAVZKGJRIHWXUMC"

    fun exec(text: String, mode: Mode, showSteps: Boolean = false): String {
        var left  = lAlphabet
        var right = rAlphabet
        val eText = CharArray(text.length)
        val temp  = CharArray(26)

        for (i in 0 until text.length) {
            if (showSteps) println("$left  $right")
            var index: Int
            if (mode == Mode.ENCRYPT) {
                index = right.indexOf(text[i])
                eText[i] = left[index]
            }
            else {
                index = left.indexOf(text[i])
                eText[i] = right[index]
            }
            if (i == text.length - 1) break

            // permute left

            for (j in index..25) temp[j - index] = left[j]
            for (j in 0 until index) temp[26 - index + j] = left[j]
            var store = temp[1]
            for (j in 2..13) temp[j - 1] = temp[j]
            temp[13] = store
            left = String(temp)

            // permute right

            for (j in index..25) temp[j - index] = right[j]
            for (j in 0 until index) temp[26 - index + j] = right[j]
            store = temp[0]
            for (j in 1..25) temp[j - 1] = temp[j]
            temp[25] = store
            store = temp[2]
            for (j in 3..13) temp[j - 1] = temp[j]
            temp[13] = store
            right = String(temp)
        }

        return String(eText)
    }
}

fun main(args: Array<String>) {
    val plainText = "WELLDONEISBETTERTHANWELLSAID"
    println("The original plaintext is : $plainText")
    println("\nThe left and right alphabets after each permutation" +
             " during encryption are :\n")
    val cipherText = Chao.exec(plainText, Mode.ENCRYPT, true)
    println("\nThe ciphertext is : $cipherText")
    val plainText2 = Chao.exec(cipherText, Mode.DECRYPT)
    println("\nThe recovered plaintext is : $plainText2")
}


Chaos game

The Chaos Game is a method of generating the attractor of an iterated function system (IFS).

One of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.

;Task
Play the Chaos Game using the corners of an equilateral triangle as the reference points.   Add a starting point at random (preferably inside the triangle).   Then add the next point halfway between the starting point and one of the reference points.   This reference point is chosen at random.

After a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.

;See also
* The Game of Chaos

Solution:
//Version 1.1.51

import java.awt.*
import java.util.Stack
import java.util.Random
import javax.swing.JPanel
import javax.swing.JFrame
import javax.swing.Timer
import javax.swing.SwingUtilities

class ChaosGame : JPanel() {

    class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)

    val stack = Stack<ColoredPoint>()
    val points: List<Point>
    val colors = listOf(Color.red, Color.green, Color.blue)
    val r = Random()

    init {
        val dim = Dimension(640, 640)
        preferredSize = dim
        background = Color.white
        val margin = 60
        val size = dim.width - 2 * margin
        points = listOf(
            Point(dim.width / 2, margin),
            Point(margin, size),
            Point(margin + size, size)
        )
        stack.push(ColoredPoint(-1, -1, 0))

        Timer(10) {
            if (stack.size < 50_000) {
                for (i in 0 until 1000) addPoint()
                repaint()
            }
        }.start()
    }

    private fun addPoint() {
        val colorIndex = r.nextInt(3)
        val p1 = stack.peek()
        val p2 = points[colorIndex]
        stack.add(halfwayPoint(p1, p2, colorIndex))
    }

    fun drawPoints(g: Graphics2D) {
        for (cp in stack) {
            g.color = colors[cp.colorIndex]
            g.fillOval(cp.x, cp.y, 1, 1)
        }
    }

    fun halfwayPoint(a: Point, b: Point, idx: Int) =
        ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)

    override fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON)
        drawPoints(g)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = JFrame()
        with (f) {
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
            title = "Chaos Game"
            isResizable = false
            add(ChaosGame(), BorderLayout.CENTER)
            pack()
            setLocationRelativeTo(null)
            isVisible = true
        }
    }
}


Check Machin-like formulas

Machin-like formulas   are useful for efficiently computing numerical approximations for \pi

;Task:
Verify the following Machin-like formulas are correct by calculating the value of '''tan'''   (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':

: {\pi\over4} = \arctan{1\over2} + \arctan{1\over3}
: {\pi\over4} = 2 \arctan{1\over3} + \arctan{1\over7}
: {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over239}
: {\pi\over4} = 5 \arctan{1\over7} + 2 \arctan{3\over79}
: {\pi\over4} = 5 \arctan{29\over278} + 7 \arctan{3\over79}
: {\pi\over4} = \arctan{1\over2} + \arctan{1\over5} + \arctan{1\over8}
: {\pi\over4} = 4 \arctan{1\over5} - \arctan{1\over70} + \arctan{1\over99}
: {\pi\over4} = 5 \arctan{1\over7} + 4 \arctan{1\over53} + 2 \arctan{1\over4443}
: {\pi\over4} = 6 \arctan{1\over8} + 2 \arctan{1\over57} + \arctan{1\over239}
: {\pi\over4} = 8 \arctan{1\over10} - \arctan{1\over239} - 4 \arctan{1\over515}
: {\pi\over4} = 12 \arctan{1\over18} + 8 \arctan{1\over57} - 5 \arctan{1\over239}
: {\pi\over4} = 16 \arctan{1\over21} + 3 \arctan{1\over239} + 4 \arctan{3\over1042}
: {\pi\over4} = 22 \arctan{1\over28} + 2 \arctan{1\over443} - 5 \arctan{1\over1393} - 10 \arctan{1\over11018}
: {\pi\over4} = 22 \arctan{1\over38} + 17 \arctan{7\over601} + 10 \arctan{7\over8149}
: {\pi\over4} = 44 \arctan{1\over57} + 7 \arctan{1\over239} - 12 \arctan{1\over682} + 24 \arctan{1\over12943}
: {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12943}

and confirm that the following formula is ''incorrect'' by showing   '''tan'''   (''right hand side)''   is ''not''   '''1''':

: {\pi\over4} = 88 \arctan{1\over172} + 51 \arctan{1\over239} + 32 \arctan{1\over682} + 44 \arctan{1\over5357} + 68 \arctan{1\over12944}

These identities are useful in calculating the values:
: \tan(a + b) = {\tan(a) + \tan(b) \over 1 - \tan(a) \tan(b)}

: \tan\left(\arctan{a \over b}\right) = {a \over b}

: \tan(-a) = -\tan(a)

You can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.

Note: to formally prove the formula correct, it would have to be shown that ''{-3 pi \over 4} < right hand side < {5 pi \over 4}'' due to ''\tan()'' periodicity.

Solution:
// version 1.1.3

import java.math.BigInteger

val bigZero = BigInteger.ZERO
val bigOne = BigInteger.ONE

class BigRational : Comparable<BigRational> {

    val num: BigInteger
    val denom: BigInteger

    constructor(n: BigInteger, d: BigInteger) {
        require(d != bigZero)
        var nn = n
        var dd = d
        if (nn == bigZero) {
            dd = bigOne
        }
        else if (dd < bigZero) {
            nn = -nn
            dd = -dd
        }
        val g = nn.gcd(dd)
        if (g > bigOne) {
            nn /= g
            dd /= g
        }
        num = nn
        denom = dd
    }

    constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d))

    operator fun plus(other: BigRational) =
        BigRational(num * other.denom + denom * other.num, other.denom * denom)

    operator fun unaryMinus() = BigRational(-num, denom)

    operator fun minus(other: BigRational) = this + (-other)

    operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom)

    fun inverse(): BigRational {
        require(num != bigZero)
        return BigRational(denom, num)
    }

    operator fun div(other: BigRational) = this * other.inverse()

    override fun compareTo(other: BigRational): Int {
        val diff = this - other
        return when {
            diff.num < bigZero -> -1
            diff.num > bigZero -> +1
            else               ->  0
        }
    }

    override fun equals(other: Any?): Boolean {
       if (other == null || other !is BigRational) return false
       return this.compareTo(other) == 0
    }

    override fun toString() = if (denom == bigOne) "$num" else "$num/$denom"

    companion object {
        val ZERO = BigRational(bigZero, bigOne)
        val ONE  = BigRational(bigOne, bigOne)
    }
}

/** represents a term of the form: c * atan(n / d) */
class Term(val c: Long, val n: Long, val d: Long) {

    override fun toString() = when {
        c ==  1L   -> " + "
        c == -1L   -> " - "
        c <   0L   -> " - ${-c}*"
        else       -> " + $c*"
    } + "atan($n/$d)"
}

val one = BigRational.ONE

fun tanSum(terms: List<Term>): BigRational {
    if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d))
    val half = terms.size / 2
    val a = tanSum(terms.take(half))
    val b = tanSum(terms.drop(half))
    return (a + b) / (one - (a * b))
}

fun tanEval(c: Long, f: BigRational): BigRational {
    if (c == 1L)  return f
    if (c < 0L) return -tanEval(-c, f)
    val ca = c / 2
    val cb = c - ca
    val a = tanEval(ca, f)
    val b = tanEval(cb, f)
    return (a + b) / (one - (a * b))
}

fun main(args: Array<String>) {
    val termsList = listOf(
        listOf(Term(1, 1, 2), Term(1, 1, 3)),
        listOf(Term(2, 1, 3), Term(1, 1, 7)),
        listOf(Term(4, 1, 5), Term(-1, 1, 239)),
        listOf(Term(5, 1, 7), Term(2, 3, 79)),
        listOf(Term(5, 29, 278), Term(7, 3, 79)),
        listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)),
        listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)),
        listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)),
        listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)),
        listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)),
        listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)),
        listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)),
        listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)),
        listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)),
        listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)),
        listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)),
        listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944))
    )

    for (terms in termsList) {
        val f = String.format("%-5s << 1 == tan(", tanSum(terms) == one)
        print(f)
        print(terms[0].toString().drop(3))
        for (i in 1 until terms.size) print(terms[i])
        println(")")
    }
}


Cheryl's birthday

Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.

Cheryl gave them a list of ten possible dates:
      May 15,     May 16,     May 19
      June 17,    June 18
      July 14,    July 16
      August 14,  August 15,  August 17

Cheryl then tells Albert the   ''month''   of birth,   and Bernard the   ''day''   (of the month)   of birth.
  1)  Albert:   I don't know when Cheryl's birthday is, but I know that Bernard does not know too.
  2)  Bernard:  At first I don't know when Cheryl's birthday is, but I know now.
  3)  Albert:   Then I also know when Cheryl's birthday is.

;Task
Write a computer program to deduce, by successive elimination, Cheryl's birthday.

;Related task:
* [[Sum and Product Puzzle]]

;References
* Wikipedia article of the same name.
* Tuple Relational Calculus

Solution:
// Version 1.2.71

val months = listOf(
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
)

class Birthday(val month: Int, val day: Int) {
    public override fun toString() = "${months[month - 1]} $day"

    public fun monthUniqueIn(bds: List<Birthday>): Boolean {
        return bds.count { this.month == it.month } == 1
    }

    public fun dayUniqueIn(bds: List<Birthday>): Boolean {
        return bds.count { this.day == it.day } == 1
    }

    public fun monthWithUniqueDayIn(bds: List<Birthday>): Boolean {
        return bds.any { (this.month == it.month) && it.dayUniqueIn(bds) }
    }
}

fun main(args: Array<String>) {
    val choices = listOf(
        Birthday(5, 15), Birthday(5, 16), Birthday(5, 19), Birthday(6, 17),
        Birthday(6, 18), Birthday(7, 14), Birthday(7, 16), Birthday(8, 14),
        Birthday(8, 15), Birthday(8, 17)
    )

    // Albert knows the month but doesn't know the day.
    // So the month can't be unique within the choices.
    var filtered = choices.filterNot { it.monthUniqueIn(choices) }

    // Albert also knows that Bernard doesn't know the answer.
    // So the month can't have a unique day.
    filtered = filtered.filterNot { it.monthWithUniqueDayIn(filtered) }

    // Bernard now knows the answer.
    // So the day must be unique within the remaining choices.
    filtered = filtered.filter { it.dayUniqueIn(filtered) }

    // Albert now knows the answer too.
    // So the month must be unique within the remaining choices.
    filtered = filtered.filter { it.monthUniqueIn(filtered) }

    if (filtered.size == 1)
        println("Cheryl's birthday is ${filtered[0]}")
    else
        println("Something went wrong!")
}


Chinese remainder theorem

Suppose   n_1,   n_2,   \ldots,   n_k   are positive [[integer]]s that are pairwise co-prime.

Then, for any given sequence of integers   a_1,   a_2,   \dots,   a_k,   there exists an integer   x   solving the following system of simultaneous congruences:

::: \begin{align}
  x &\equiv a_1 \pmod{n_1} \\
  x &\equiv a_2 \pmod{n_2} \\
    &{}\  \  \vdots \\
  x &\equiv a_k \pmod{n_k}
\end{align}

Furthermore, all solutions   x   of this system are congruent modulo the product,    N=n_1n_2\ldots n_k.

;Task:
Write a program to solve a system of linear congruences by applying the   Chinese Remainder Theorem.

If the system of equations cannot be solved, your program must somehow indicate this.

(It may throw an exception or return a special false value.)

Since there are infinitely many solutions, the program should return the unique solution   s   where   0 \leq s \leq n_1n_2\ldots n_k.

''Show the functionality of this program'' by printing the result such that the   n's   are   [3,5,7]   and the   a's   are   [2,3,2].

'''Algorithm''':   The following algorithm only applies if the   n_i's   are pairwise co-prime.

Suppose, as above, that a solution is required for the system of congruences:

::: x \equiv a_i \pmod{n_i} \quad\mathrm{for}\; i = 1, \ldots, k

Again, to begin, the product   N = n_1n_2 \ldots n_k   is defined.

Then a solution   x   can be found as follows:

For each   i,   the integers   n_i   and   N/n_i   are co-prime.

Using the   Extended Euclidean algorithm,   we can find integers   r_i   and   s_i   such that   r_i n_i + s_i N/n_i = 1.

Then, one solution to the system of simultaneous congruences is:

::: x = \sum_{i=1}^k a_i s_i N/n_i

and the minimal solution,

::: x \pmod{N}.

Solution:
// version 1.1.2

/* returns x where (a * x) % b == 1 */
fun multInv(a: Int, b: Int): Int {
    if (b == 1) return 1
    var aa = a
    var bb = b
    var x0 = 0
    var x1 = 1
    while (aa > 1) {
        val q = aa / bb
        var t = bb
        bb = aa % bb
        aa = t
        t = x0
        x0 = x1 - q * x0
        x1 = t
    }
    if (x1 < 0) x1 += b
    return x1
}

fun chineseRemainder(n: IntArray, a: IntArray): Int {
    val prod = n.fold(1) { acc, i -> acc * i }
    var sum = 0
    for (i in 0 until n.size) {
        val p = prod / n[i]
        sum += a[i] * multInv(p, n[i]) * p
    }
    return sum % prod
}

fun main(args: Array<String>) {
    val n = intArrayOf(3, 5, 7)
    val a = intArrayOf(2, 3, 2)
    println(chineseRemainder(n, a))
}


Chinese zodiac

Determine the Chinese zodiac sign and related associations for a given year.
Traditionally, the Chinese have counted years using two lists of labels, one of length 10 (the "celestial stems") and one of length 12 (the "terrestrial branches"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.

Years cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.

Mapping the branches to twelve traditional animal deities results in the well-known "Chinese zodiac", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.

The celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.

Thus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.

;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.

You may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).

;Requisite information:
* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.
* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water.
* Each element gets two consecutive years; a yang followed by a yin.
* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.

Thus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle.

;Information for optional task:
* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written "jia3", "yi3", "bing3", "ding1", "wu4", "ji3", "geng1", "xin1", "ren2", and "gui3".
* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are "zi3", "chou3", "yin2", "mao3", "chen2", "si4", "wu3", "wei4", "shen1", "you3", "xu1", and "hai4".

Therefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3).  2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).

Solution:
// version 1.1.2

class ChineseZodiac(val year: Int) {
    val stem   : Char
    val branch : Char
    val sName  : String
    val bName  : String
    val element: String
    val animal : String
    val aspect : String
    val cycle  : Int

    private companion object {
        val animals  = listOf("Rat", "Ox", "Tiger", "Rabbit", "Dragon", "Snake",
                              "Horse", "Goat", "Monkey", "Rooster", "Dog", "Pig")
        val aspects  = listOf("Yang","Yin")
        val elements = listOf("Wood", "Fire", "Earth", "Metal", "Water")
        val stems    = listOf('甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸')
        val branches = listOf('子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥')
        val sNames   = listOf("jiă", "yĭ", "bĭng", "dīng", "wù", "jĭ", "gēng", "xīn", "rén", "gŭi")
        val bNames   = listOf("zĭ", "chŏu", "yín", "măo", "chén", "sì", "wŭ", "wèi", "shēn", "yŏu",  "xū", "hài")
        val fmt      = "%d    %c%c   %-9s  %-7s  %-7s   %-6s %02d/60"
    }

    init {
        val y = year - 4
        val s = y % 10
        val b = y % 12
        stem    = stems[s]
        branch  = branches[b]
        sName   = sNames[s]
        bName   = bNames[b]
        element = elements[s / 2]
        animal  = animals[b]
        aspect  = aspects[s % 2]
        cycle   = y % 60 + 1
    }

    override fun toString() =
        fmt.format(year, stem, branch, sName + "-" + bName, element, animal, aspect, cycle)
}

fun main(args: Array<String>) {
    val years = intArrayOf(1935, 1938, 1968, 1972, 1976, 1984, 2017)
    println("Year  Chinese  Pinyin     Element  Animal   Aspect  Cycle")
    println("----  -------  ---------  -------  -------  ------  -----")
    for (year in years) println(ChineseZodiac(year))
}


Circles of given radius through two points

2 circles with a given radius through 2 points in 2D space.

Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
;Exceptions:
# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).
# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.
# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.
# If the points are too far apart then no circles can be drawn.

;Task detail:
* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.
* Show here the output for the following inputs:

      p1                p2           r
0.1234, 0.9876    0.8765, 0.2345    2.0
0.0000, 2.0000    0.0000, 0.0000    1.0
0.1234, 0.9876    0.1234, 0.9876    2.0
0.1234, 0.9876    0.8765, 0.2345    0.5
0.1234, 0.9876    0.1234, 0.9876    0.0

;Related task:
*   [[Total circles area]].

;See also:
*   Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel

Solution:
// version 1.1.51

typealias IAE = IllegalArgumentException

class Point(val x: Double, val y: Double) {
    fun distanceFrom(other: Point): Double {
        val dx = x - other.x
        val dy = y - other.y
        return Math.sqrt(dx * dx + dy * dy )
    }

    override fun equals(other: Any?): Boolean {
        if (other == null || other !is Point) return false
        return (x == other.x && y == other.y)
    }

    override fun toString() = "(%.4f, %.4f)".format(x, y)
}

fun findCircles(p1: Point, p2: Point, r: Double): Pair<Point, Point> {
    if (r < 0.0) throw IAE("the radius can't be negative")
    if (r == 0.0 && p1 != p2) throw IAE("no circles can ever be drawn")
    if (r == 0.0) return p1 to p1
    if (p1 == p2) throw IAE("an infinite number of circles can be drawn")
    val distance = p1.distanceFrom(p2)
    val diameter = 2.0 * r
    if (distance > diameter) throw IAE("the points are too far apart to draw a circle")
    val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0)
    if (distance == diameter) return center to center
    val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0)
    val dx =  (p2.x - p1.x) * mirrorDistance / distance
    val dy =  (p2.y - p1.y) * mirrorDistance / distance
    return Point(center.x - dy, center.y + dx) to
           Point(center.x + dy, center.y - dx)
}

fun main(args: Array<String>) {
    val p = arrayOf(
        Point(0.1234, 0.9876),
        Point(0.8765, 0.2345),
        Point(0.0000, 2.0000),
        Point(0.0000, 0.0000)
    )
    val points = arrayOf(
        p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0]
    )
    val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0)
    for (i in 0..4) {
        try {
            val (p1, p2) = points[i]
            val r  = radii[i]
            println("For points $p1 and $p2 with radius $r")
            val (c1, c2) = findCircles(p1, p2, r)
            if (c1 == c2)
                println("there is just one circle with center at $c1")
            else
                println("there are two circles with centers at $c1 and $c2")
        }
        catch(ex: IllegalArgumentException) {
            println(ex.message)
        }
        println()
    }
}


Cistercian numerals

Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.

;How they work
All Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:

:* The '''upper-right''' quadrant represents the '''ones''' place.
:* The '''upper-left''' quadrant represents the '''tens''' place.
:* The '''lower-right''' quadrant represents the '''hundreds''' place.
:* The '''lower-left''' quadrant represents the '''thousands''' place.

Please consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]

;Task

:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).

:* Use the routine to show the following Cistercian numerals:

::* 0
::* 1
::* 20
::* 300
::* 4000
::* 5555
::* 6789
::* And a number of your choice!

;Notes
Due to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.

;See also

:* '''Numberphile - The Forgotten Number System'''
:* '''dcode.fr - Online Cistercian numeral converter'''

Solution:
import java.io.StringWriter

class Cistercian() {
    constructor(number: Int) : this() {
        draw(number)
    }

    private val size = 15
    private var canvas = Array(size) { Array(size) { ' ' } }

    init {
        initN()
    }

    private fun initN() {
        for (row in canvas) {
            row.fill(' ')
            row[5] = 'x'
        }
    }

    private fun horizontal(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r][c] = 'x'
        }
    }

    private fun vertical(r1: Int, r2: Int, c: Int) {
        for (r in r1..r2) {
            canvas[r][c] = 'x'
        }
    }

    private fun diagd(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r + c - c1][c] = 'x'
        }
    }

    private fun diagu(c1: Int, c2: Int, r: Int) {
        for (c in c1..c2) {
            canvas[r - c + c1][c] = 'x'
        }
    }

    private fun drawPart(v: Int) {
        when (v) {
            1 -> {
                horizontal(6, 10, 0)
            }
            2 -> {
                horizontal(6, 10, 4)
            }
            3 -> {
                diagd(6, 10, 0)
            }
            4 -> {
                diagu(6, 10, 4)
            }
            5 -> {
                drawPart(1)
                drawPart(4)
            }
            6 -> {
                vertical(0, 4, 10)
            }
            7 -> {
                drawPart(1)
                drawPart(6)
            }
            8 -> {
                drawPart(2)
                drawPart(6)
            }
            9 -> {
                drawPart(1)
                drawPart(8)
            }

            10 -> {
                horizontal(0, 4, 0)
            }
            20 -> {
                horizontal(0, 4, 4)
            }
            30 -> {
                diagu(0, 4, 4)
            }
            40 -> {
                diagd(0, 4, 0)
            }
            50 -> {
                drawPart(10)
                drawPart(40)
            }
            60 -> {
                vertical(0, 4, 0)
            }
            70 -> {
                drawPart(10)
                drawPart(60)
            }
            80 -> {
                drawPart(20)
                drawPart(60)
            }
            90 -> {
                drawPart(10)
                drawPart(80)
            }

            100 -> {
                horizontal(6, 10, 14)
            }
            200 -> {
                horizontal(6, 10, 10)
            }
            300 -> {
                diagu(6, 10, 14)
            }
            400 -> {
                diagd(6, 10, 10)
            }
            500 -> {
                drawPart(100)
                drawPart(400)
            }
            600 -> {
                vertical(10, 14, 10)
            }
            700 -> {
                drawPart(100)
                drawPart(600)
            }
            800 -> {
                drawPart(200)
                drawPart(600)
            }
            900 -> {
                drawPart(100)
                drawPart(800)
            }

            1000 -> {
                horizontal(0, 4, 14)
            }
            2000 -> {
                horizontal(0, 4, 10)
            }
            3000 -> {
                diagd(0, 4, 10)
            }
            4000 -> {
                diagu(0, 4, 14)
            }
            5000 -> {
                drawPart(1000)
                drawPart(4000)
            }
            6000 -> {
                vertical(10, 14, 0)
            }
            7000 -> {
                drawPart(1000)
                drawPart(6000)
            }
            8000 -> {
                drawPart(2000)
                drawPart(6000)
            }
            9000 -> {
                drawPart(1000)
                drawPart(8000)
            }
        }
    }

    private fun draw(v: Int) {
        var v2 = v

        val thousands = v2 / 1000
        v2 %= 1000

        val hundreds = v2 / 100
        v2 %= 100

        val tens = v2 / 10
        val ones = v % 10

        if (thousands > 0) {
            drawPart(1000 * thousands)
        }
        if (hundreds > 0) {
            drawPart(100 * hundreds)
        }
        if (tens > 0) {
            drawPart(10 * tens)
        }
        if (ones > 0) {
            drawPart(ones)
        }
    }

    override fun toString(): String {
        val sw = StringWriter()
        for (row in canvas) {
            for (cell in row) {
                sw.append(cell)
            }
            sw.appendLine()
        }
        return sw.toString()
    }
}

fun main() {
    for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {
        println("$number:")

        val c = Cistercian(number)
        println(c)
    }

}


Closures/Value capture

Create a list of ten functions, in the simplest manner possible   (anonymous functions are encouraged),   such that the function at index   '' i ''    (you may choose to start    '' i ''    from either    '''0'''    or    '''1'''),     when run, should return the square of the index,   that is,    '' i '' 2.

Display the result of running any but the last function, to demonstrate that the function indeed remembers its value.

;Goal:
Demonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over.

In imperative languages, one would generally use a loop with a mutable counter variable.

For each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.

See also: [[Multiple distinct objects]]

Solution:
// version 1.0.6

fun main(args: Array<String>) {
    // create an array of 10 anonymous functions which return the square of their index
    val funcs = Array(10){ fun(): Int = it * it }
    // call all but the last
    (0 .. 8).forEach { println(funcs[it]()) }
}


Colour bars/Display

Display a series of vertical color bars across the width of the display.

The color bars should either use:
:::*   the system palette,   or
:::*   the sequence of colors:
::::::*   black
::::::*   red
::::::*   green
::::::*   blue
::::::*   magenta
::::::*   cyan
::::::*   yellow
::::::*   white

Solution:
import java.awt.Color
import java.awt.Graphics
import javax.swing.JFrame

class ColorFrame(width: Int, height: Int): JFrame() {
    init {
        defaultCloseOperation = EXIT_ON_CLOSE
        setSize(width, height)
        isVisible = true
    }

    override fun paint(g: Graphics) {
        val colors = listOf(Color.black, Color.red,  Color.green,  Color.blue,
		            Color.pink,  Color.cyan, Color.yellow, Color.white)
        val size = colors.size
        for (i in 0 until size) {
            g.color = colors[i]
            g.fillRect(width / size * i, 0, width / size, height)
        }
    }
}

fun main(args: Array<String>) {
    ColorFrame(400, 400)
}


Comma quibbling

Comma quibbling is a task originally set by Eric Lippert in his blog.

;Task:

Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
# An input of no words produces the output string of just the two brace characters "{}".
# An input of just one word, e.g. ["ABC"], produces the output string of the word inside the two braces, e.g. "{ABC}".
# An input of two words, e.g. ["ABC", "DEF"], produces the output string of the two words inside the two braces with the words separated by the string " and ", e.g. "{ABC and DEF}".
# An input of three or more words, e.g. ["ABC", "DEF", "G", "H"], produces the output string of all but the last word separated by ", " with the last word separated by " and " and all within braces; e.g. "{ABC, DEF, G and H}".

Test your function with the following series of inputs showing your output here on this page:
* []                       # (No input words).
* ["ABC"]
* ["ABC", "DEF"]
* ["ABC", "DEF", "G", "H"]

Note: Assume words are non-empty strings of uppercase characters for this task.

Solution:
// version 1.0.6

fun commaQuibble(s: String): String {
    val t = s.trim('[', ']').replace(" ", "").replace("\"", "")
    val words = t.split(',')
    val sb = StringBuilder("{")
    for (i in 0 until words.size) {
        sb.append(when (i) {
            0                -> ""
            words.lastIndex  -> " and "
            else             -> ", "
        })
        sb.append(words[i])
    }
    return sb.append("}").toString()
}

fun main(args: Array<String>) {
    val inputs = arrayOf(
        """[]""",
        """["ABC"]""",
        """["ABC", "DEF"]""",
        """["ABC", "DEF", "G", "H"]"""
    )
    for (input in inputs) println("${input.padEnd(24)}  ->  ${commaQuibble(input)}")
}


Command-line arguments

{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].
See also [[Program name]].

For parsing command line arguments intelligently, see [[Parsing command-line arguments]].

Example command line:

 myprogram -c "alpha beta" -h "gamma"

Solution:
fun main(args: Array<String>) {
     println("There are " + args.size + " arguments given.")
     args.forEachIndexed { i, a -> println("The argument #${i+1} is $a and is at index $i") }
}


Compare a list of strings

Given a   list   of arbitrarily many strings, show how to:

*   test if they are all lexically '''equal'''
*   test if every string is lexically '''less than''' the one after it  ''(i.e. whether the list is in strict ascending order)''

Each of those two tests should result in a single true or false value, which could be used as the condition of an    if    statement or similar.

If the input list has less than two elements, the tests should always return true.

There is ''no'' need to provide a complete program and output.

Assume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name   strings,   and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs),   with as little distractions as possible.

Try to write your solution in a way that does not modify the original list,   but if it does then please add a note to make that clear to readers.

If you need further guidance/clarification,   see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops,   and [[#Raku]] for a solution that gets away with simply using a built-in language feature.

Solution:
// version 1.0.6

fun areEqual(strings: Array<String>): Boolean {
    if (strings.size < 2) return true
    return (1 until strings.size).all { strings[it] == strings[it - 1] }
}

fun areAscending(strings: Array<String>): Boolean {
    if (strings.size < 2) return true
    return (1 until strings.size).all { strings[it] > strings[it - 1] }
}

// The strings are given in the command line arguments

fun main(args: Array<String>) {
    println("The strings are : ${args.joinToString()}")
    if (areEqual(args)) println("They are all equal")
    else if (areAscending(args)) println("They are in strictly ascending order")
    else println("They are neither equal nor in ascending order")
}


Compile-time calculation

Some programming languages allow calculation of values at compile time.

;Task:
Calculate    10!    (ten factorial)   at compile time.

Print the result when the program is run.

Discuss what limitations apply to compile-time calculations in your language.

Solution:
// version 1.0.6
const val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2

fun main(args: Array<String>) {
    println("10! = $TEN_FACTORIAL")
}