Find palindromic numbers in both binary and ternary bases

*   Find and show (in decimal) the first six numbers (non-negative integers) that are   palindromes   in   ''both'':
:::*   base 2
:::*   base 3
*   Display   '''0'''   (zero) as the first number found, even though some other definitions ignore it.
*   Optionally, show the decimal number found in its binary and ternary form.
*   Show all output here.

It's permissible to assume the first two numbers and simply list them.

;See also
*   Sequence A60792,   numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.

Solution:
// version 1.0.5-2

/** converts decimal 'n' to its ternary equivalent */
fun Long.toTernaryString(): String = when {
    this < 0L  -> throw IllegalArgumentException("negative numbers not allowed")
    this == 0L -> "0"
    else   -> {
        var result = ""
        var n = this
        while (n > 0) {
            result += n % 3
            n /= 3
        }
        result.reversed()
    }
}

/** wraps java.lang.Long.toBinaryString in a Kotlin extension function */
fun Long.toBinaryString(): String = java.lang.Long.toBinaryString(this)

/** check if a binary or ternary numeric string 's' is palindromic */
fun isPalindromic(s: String): Boolean = (s == s.reversed())

/** print a number which is both a binary and ternary palindrome in all three bases */
fun printPalindrome(n: Long) {
    println("Decimal : $n")
    println("Binary  : ${n.toBinaryString()}")
    println("Ternary : ${n.toTernaryString()}")
    println()
}

/** create a ternary palindrome whose left part is the ternary equivalent of 'n' and return its decimal equivalent */
fun createPalindrome3(n: Long): Long {
    val ternary = n.toTernaryString()
    var power3 = 1L
    var sum = 0L
    val length = ternary.length
    for (i in 0 until length) {  // right part of palindrome is mirror image of left part
        if (ternary[i] > '0') sum += (ternary[i].toInt() - 48) * power3
        power3 *= 3L
    }
    sum += power3 // middle digit must be 1
    power3 *= 3L
    sum += n * power3  // value of left part is simply 'n' multiplied by appropriate power of 3
    return sum
}

fun main(args: Array<String>) {
    var i = 1L
    var p3: Long
    var count = 2
    var binStr: String
    println("The first 6 numbers which are palindromic in both binary and ternary are:\n")
    // we can assume the first two palindromic numbers as per the task description
    printPalindrome(0L)  // 0 is a palindrome in all 3 bases
    printPalindrome(1L)  // 1 is a palindrome in all 3 bases

    do {
        p3 = createPalindrome3(i)
        if (p3 % 2 > 0L)  { // cannot be even as binary equivalent would end in zero
            binStr = p3.toBinaryString()
            if (binStr.length % 2 == 1) { // binary palindrome must have an odd number of digits
                if (isPalindromic(binStr)) {
                    printPalindrome(p3)
                    count++
                }
            }
        }
        i++
    }
    while (count < 6)
}


Find the intersection of a line with a plane

Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.

;Task:
Find the point of intersection for the infinite ray with direction   (0, -1, -1)   passing through position   (0, 0, 10)   with the infinite plane with a normal vector of   (0, 0, 1)   and which passes through [0, 0, 5].

Solution:
// version 1.1.51

class Vector3D(val x: Double, val y: Double, val z: Double) {

    operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)

    operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)

    operator fun times(s: Double) = Vector3D(s * x, s * y, s * z)

    infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z

    override fun toString() = "($x, $y, $z)"
}

fun intersectPoint(
    rayVector: Vector3D,
    rayPoint: Vector3D,
    planeNormal: Vector3D,
    planePoint: Vector3D
): Vector3D {
    val diff  = rayPoint - planePoint
    val prod1 = diff dot planeNormal
    val prod2 = rayVector dot planeNormal
    val prod3 = prod1 / prod2
    return rayPoint - rayVector * prod3
}

fun main(args: Array<String>) {
    val rv = Vector3D(0.0, -1.0, -1.0)
    val rp = Vector3D(0.0,  0.0, 10.0)
    val pn = Vector3D(0.0,  0.0,  1.0)
    val pp = Vector3D(0.0,  0.0,  5.0)
    val ip = intersectPoint(rv, rp, pn, pp)
    println("The ray intersects the plane at $ip")
}


Find the intersection of two lines

Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]

;Task:
Find the point of intersection of two lines in 2D.

The 1st     line passes though    (4,0)    and    (6,10) .
The 2nd line passes though    (0,3)    and    (10,7) .

Solution:
// version 1.1.2

class PointF(val x: Float, val y: Float) {
    override fun toString() = "{$x, $y}"
}

class LineF(val s: PointF, val e: PointF)

fun findIntersection(l1: LineF, l2: LineF): PointF {
    val a1 = l1.e.y - l1.s.y
    val b1 = l1.s.x - l1.e.x
    val c1 = a1 * l1.s.x + b1 * l1.s.y

    val a2 = l2.e.y - l2.s.y
    val b2 = l2.s.x - l2.e.x
    val c2 = a2 * l2.s.x + b2 * l2.s.y

    val delta = a1 * b2 - a2 * b1
    // If lines are parallel, intersection point will contain infinite values
    return PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)
}

fun main(args: Array<String>) {
    var l1 = LineF(PointF(4f, 0f), PointF(6f, 10f))
    var l2 = LineF(PointF(0f, 3f), PointF(10f, 7f))
    println(findIntersection(l1, l2))
    l1 = LineF(PointF(0f, 0f), PointF(1f, 1f))
    l2 = LineF(PointF(1f, 2f), PointF(4f, 5f))
    println(findIntersection(l1, l2))
}


Find the last Sunday of each month

Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29

;Related tasks
* [[Day of the week]]
* [[Five weekends]]
* [[Last Friday of each month]]

Solution:
// version 1.0.6

import java.util.*

fun main(args: Array<String>) {
    print("Enter a year : ")
    val year = readLine()!!.toInt()

    println("The last Sundays of each month in $year are as follows:")
    val calendar = GregorianCalendar(year, 0, 31)
    for (month in 1..12) {
        val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
        val lastSunday = daysInMonth - (calendar[Calendar.DAY_OF_WEEK] - Calendar.SUNDAY)
        println("$year-" + "%02d-".format(month) + "%02d".format(lastSunday))
        if (month < 12) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            calendar.add(Calendar.MONTH, 1)
            calendar.add(Calendar.DAY_OF_MONTH, -1)
        }
    }
}


Find the missing permutation

ABCD
                    CABD
                    ACDB
                    DACB
                    BCDA
                    ACBD
                    ADCB
                    CDAB
                    DABC
                    BCAD
                    CADB
                    CDBA
                    CBAD
                    ABDC
                    ADBC
                    BDCA
                    DCBA
                    BACD
                    BADC
                    BDAC
                    CBDA
                    DBCA
                    DCAB

Listed above are   all-but-one   of the permutations of the symbols   '''A''',   '''B''',   '''C''',   and   '''D''',   ''except''   for one permutation that's   ''not''   listed.

;Task:
Find that missing permutation.

;Methods:
* Obvious method:
         enumerate all permutations of   '''A''',  '''B''',  '''C''',  and  '''D''',
         and then look for the missing permutation.

* alternate method:
         Hint:  if all permutations were shown above,  how many
         times would  '''A'''  appear in each position?
         What is the  ''parity''  of this number?

* another alternate method:
         Hint:  if you add up the letter values of each column,
         does a missing letter   '''A''',  '''B''',  '''C''',  and  '''D'''   from each
         column cause the total value for each column to be unique?

;Related task:
*   [[Permutations]])

Solution:
// version 1.1.2

fun <T> permute(input: List<T>): List<List<T>> {
    if (input.size == 1) return listOf(input)
    val perms = mutableListOf<List<T>>()
    val toInsert = input[0]
    for (perm in permute(input.drop(1))) {
        for (i in 0..perm.size) {
            val newPerm = perm.toMutableList()
            newPerm.add(i, toInsert)
            perms.add(newPerm)
        }
    }
    return perms
}

fun <T> missingPerms(input: List<T>, perms: List<List<T>>) = permute(input) - perms

fun main(args: Array<String>) {
    val input = listOf('A', 'B', 'C', 'D')
    val strings = listOf(
        "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
        "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
        "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
    )
    val perms = strings.map { it.toList() }
    val missing = missingPerms(input, perms)
    if (missing.size == 1)
        print("The missing permutation is ${missing[0].joinToString("")}")
    else {
        println("There are ${missing.size} missing permutations, namely:\n")
        for (perm in missing) println(perm.joinToString(""))
    }
}


First-class functions/Use numbers analogously

In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.

This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.

Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
   x  = 2.0
   xi = 0.5
   y  = 4.0
   yi = 0.25
   z  = x + y
   zi = 1.0 / ( x + y )

Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:
  new_function = multiplier(n1,n2)
  # where new_function(m) returns the result of n1 * n2 * m

Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.
'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.

To paraphrase the task description: Do what was done before, but with numbers rather than functions

Solution:
// version 1.1.2

fun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m}

fun main(args: Array<String>) {
    val x  = 2.0
    val xi = 0.5
    val y  = 4.0
    val yi = 0.25
    val z  = x + y
    val zi = 1.0 / ( x + y)
    val a  = doubleArrayOf(x, y, z)
    val ai = doubleArrayOf(xi, yi, zi)
    val m  = 0.5
    for (i in 0 until a.size) {
        println("${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)")
    }
}


First perfect square in base n with n unique digits

Find the first perfect square in a given base '''N''' that has at least '''N''' digits and
exactly '''N''' ''significant unique'' digits when expressed in base '''N'''.

E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').

You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.

;Task

* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.

* (optional) Do the same for bases '''13''' through '''16'''.

* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)

;See also:

;* OEIS A260182: smallest square that is pandigital in base n.

;Related task

;* [[Casting out nines]]

Solution:
import java.math.BigInteger
import java.time.Duration
import java.util.ArrayList
import java.util.HashSet
import kotlin.math.sqrt

const val ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|"
var base: Byte = 0
var bmo: Byte = 0
var blim: Byte = 0
var ic: Byte = 0
var st0: Long = 0
var bllim: BigInteger? = null
var threshold: BigInteger? = null
var hs: MutableSet<Byte> = HashSet()
var o: MutableSet<Byte> = HashSet()
val chars = ALPHABET.toCharArray()
var limits: MutableList<BigInteger?>? = null
var ms: String? = null

fun indexOf(c: Char): Int {
    for (i in chars.indices) {
        if (chars[i] == c) {
            return i
        }
    }
    return -1
}

// convert BigInteger to string using current base
fun toStr(b: BigInteger): String {
    var b2 = b
    val bigBase = BigInteger.valueOf(base.toLong())
    val res = StringBuilder()
    while (b2 > BigInteger.ZERO) {
        val divRem = b2.divideAndRemainder(bigBase)
        res.append(chars[divRem[1].toInt()])
        b2 = divRem[0]
    }
    return res.toString()
}

// check for a portion of digits, bailing if uneven
fun allInQS(b: BigInteger): Boolean {
    var b2 = b
    val bigBase = BigInteger.valueOf(base.toLong())
    var c = ic.toInt()
    hs.clear()
    hs.addAll(o)
    while (b2 > bllim) {
        val divRem = b2.divideAndRemainder(bigBase)
        hs.add(divRem[1].toByte())
        c++
        if (c > hs.size) {
            return false
        }
        b2 = divRem[0]
    }
    return true
}

// check for a portion of digits, all the way to the end
fun allInS(b: BigInteger): Boolean {
    var b2 = b
    val bigBase = BigInteger.valueOf(base.toLong())
    hs.clear()
    hs.addAll(o)
    while (b2 > bllim) {
        val divRem = b2.divideAndRemainder(bigBase)
        hs.add(divRem[1].toByte())
        b2 = divRem[0]
    }
    return hs.size == base.toInt()
}

// check for all digits, bailing if uneven
fun allInQ(b: BigInteger): Boolean {
    var b2 = b
    val bigBase = BigInteger.valueOf(base.toLong())
    var c = 0
    hs.clear()
    while (b2 > BigInteger.ZERO) {
        val divRem = b2.divideAndRemainder(bigBase)
        hs.add(divRem[1].toByte())
        c++
        if (c > hs.size) {
            return false
        }
        b2 = divRem[0]
    }
    return true
}

// check for all digits, all the way to the end
fun allIn(b: BigInteger): Boolean {
    var b2 = b
    val bigBase = BigInteger.valueOf(base.toLong())
    hs.clear()
    while (b2 > BigInteger.ZERO) {
        val divRem = b2.divideAndRemainder(bigBase)
        hs.add(divRem[1].toByte())
        b2 = divRem[0]
    }
    return hs.size == base.toInt()
}

// parse a string into a BigInteger, using current base
fun to10(s: String?): BigInteger {
    val bigBase = BigInteger.valueOf(base.toLong())
    var res = BigInteger.ZERO
    for (element in s!!) {
        val idx = indexOf(element)
        val bigIdx = BigInteger.valueOf(idx.toLong())
        res = res.multiply(bigBase).add(bigIdx)
    }
    return res
}

// returns the minimum value string, optionally inserting extra digit
fun fixup(n: Int): String {
    var res = ALPHABET.substring(0, base.toInt())
    if (n > 0) {
        val sb = StringBuilder(res)
        sb.insert(n, n)
        res = sb.toString()
    }
    return "10" + res.substring(2)
}

// checks the square against the threshold, advances various limits when needed
fun check(sq: BigInteger) {
    if (sq > threshold) {
        o.remove(indexOf(ms!![blim.toInt()]).toByte())
        blim--
        ic--
        threshold = limits!![bmo - blim - 1]
        bllim = to10(ms!!.substring(0, blim + 1))
    }
}

// performs all the calculations for the current base
fun doOne() {
    limits = ArrayList()
    bmo = (base - 1).toByte()
    var dr: Byte = 0
    if ((base.toInt() and 1) == 1) {
        dr = (base.toInt() shr 1).toByte()
    }
    o.clear()
    blim = 0
    var id: Byte = 0
    var inc = 1
    val st = System.nanoTime()
    val sdr = ByteArray(bmo.toInt())
    var rc: Byte = 0
    for (i in 0 until bmo) {
        sdr[i] = (i * i % bmo).toByte()
        if (sdr[i] == dr) {
            rc = (rc + 1).toByte()
        }
        if (sdr[i] == 0.toByte()) {
            sdr[i] = (sdr[i] + bmo).toByte()
        }
    }
    var i: Long = 0
    if (dr > 0) {
        id = base
        i = 1
        while (i <= dr) {
            if (sdr[i.toInt()] >= dr) {
                if (id > sdr[i.toInt()]) {
                    id = sdr[i.toInt()]
                }
            }
            i++
        }
        id = (id - dr).toByte()
        i = 0
    }
    ms = fixup(id.toInt())
    var sq = to10(ms)
    var rt = BigInteger.valueOf((sqrt(sq.toDouble()) + 1).toLong())
    sq = rt.multiply(rt)
    if (base > 9) {
        for (j in 1 until base) {
            limits!!.add(to10(ms!!.substring(0, j) + chars[bmo.toInt()].toString().repeat(base - j + if (rc > 0) 0 else 1)))
        }
        limits!!.reverse()
        while (sq < limits!![0]) {
            rt = rt.add(BigInteger.ONE)
            sq = rt.multiply(rt)
        }
    }
    var dn = rt.shiftLeft(1).add(BigInteger.ONE)
    var d = BigInteger.ONE
    if (base > 3 && rc > 0) {
        while (sq.remainder(BigInteger.valueOf(bmo.toLong())).compareTo(BigInteger.valueOf(dr.toLong())) != 0) {
            rt = rt.add(BigInteger.ONE)
            sq = sq.add(dn)
            dn = dn.add(BigInteger.TWO)
        } // aligns sq to dr
        inc = bmo / rc
        if (inc > 1) {
            dn = dn.add(rt.multiply(BigInteger.valueOf(inc - 2.toLong())).subtract(BigInteger.ONE))
            d = BigInteger.valueOf(inc * inc.toLong())
        }
        dn = dn.add(dn).add(d)
    }
    d = d.shiftLeft(1)
    if (base > 9) {
        blim = 0
        while (sq < limits!![bmo - blim - 1]) {
            blim++
        }
        ic = (blim + 1).toByte()
        threshold = limits!![bmo - blim - 1]
        if (blim > 0) {
            for (j in 0..blim) {
                o.add(indexOf(ms!![j]).toByte())
            }
        }
        bllim = if (blim > 0) {
            to10(ms!!.substring(0, blim + 1))
        } else {
            BigInteger.ZERO
        }
        if (base > 5 && rc > 0) while (!allInQS(sq)) {
            sq = sq.add(dn)
            dn = dn.add(d)
            i += 1
            check(sq)
        } else {
            while (!allInS(sq)) {
                sq = sq.add(dn)
                dn = dn.add(d)
                i += 1
                check(sq)
            }
        }
    } else {
        if (base > 5 && rc > 0) {
            while (!allInQ(sq)) {
                sq = sq.add(dn)
                dn = dn.add(d)
                i += 1
            }
        } else {
            while (!allIn(sq)) {
                sq = sq.add(dn)
                dn = dn.add(d)
                i += 1
            }
        }
    }
    rt = rt.add(BigInteger.valueOf(i * inc))
    val delta1 = System.nanoTime() - st
    val dur1 = Duration.ofNanos(delta1)
    val delta2 = System.nanoTime() - st0
    val dur2 = Duration.ofNanos(delta2)
    System.out.printf(
        "%3d  %2d  %2s %20s -> %-40s %10d %9s  %9s\n",
        base, inc, if (id > 0) ALPHABET.substring(id.toInt(), id + 1) else " ", toStr(rt), toStr(sq), i, format(dur1), format(dur2)
    )
}

private fun format(d: Duration): String {
    val minP = d.toMinutesPart()
    val secP = d.toSecondsPart()
    val milP = d.toMillisPart()
    return String.format("%02d:%02d.%03d", minP, secP, milP)
}

fun main() {
    println("base inc id                 root    square                                   test count    time        total")
    st0 = System.nanoTime()
    base = 2
    while (base < 28) {
        doOne()
        ++base
    }
}


First power of 2 that has leading decimal digits of 12

Solution:
import kotlin.math.ln
import kotlin.math.pow

fun main() {
    runTest(12, 1)
    runTest(12, 2)
    runTest(123, 45)
    runTest(123, 12345)
    runTest(123, 678910)
}

private fun runTest(l: Int, n: Int) {
//    System.out.printf("p(%d, %d) = %,d%n", l, n, p(l, n))
    println("p($l, $n) = %,d".format(p(l, n)))
}

fun p(l: Int, n: Int): Int {
    var m = n
    var test = 0
    val log = ln(2.0) / ln(10.0)
    var factor = 1
    var loop = l
    while (loop > 10) {
        factor *= 10
        loop /= 10
    }
    while (m > 0) {
        test++
        val value = (factor * 10.0.pow(test * log % 1)).toInt()
        if (value == l) {
            m--
        }
    }
    return test
}


Fivenum

Many big data or scientific programs use boxplots to show distributions of data.   In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM.   It can be useful to save large arrays as arrays with five numbers to save memory.

For example, the   '''R'''   programming language implements Tukey's five-number summary as the '''fivenum''' function.

;Task:
Given an array of numbers, compute the five-number summary.

;Note:
While these five numbers can be used to draw a boxplot,   statistical packages will typically need extra data.

Moreover, while there is a consensus about the "box" of the boxplot,   there are variations among statistical packages for the whiskers.

Solution:
// version 1.2.21

fun median(x: DoubleArray, start: Int, endInclusive: Int): Double {
    val size = endInclusive - start + 1
    require (size > 0) { "Array slice cannot be empty" }
    val m = start + size / 2
    return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0
}

fun fivenum(x: DoubleArray): DoubleArray {
    require(x.none { it.isNaN() }) { "Unable to deal with arrays containing NaN" }
    val result = DoubleArray(5)
    x.sort()
    result[0] = x[0]
    result[2] = median(x, 0, x.size - 1)
    result[4] = x[x.lastIndex]
    val m = x.size / 2
    var lowerEnd = if (x.size % 2 == 1) m else m - 1
    result[1] = median(x, 0, lowerEnd)
    result[3] = median(x, m, x.size - 1)
    return result
}

fun main(args: Array<String>) {
    var xl = listOf(
        doubleArrayOf(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0),
        doubleArrayOf(36.0, 40.0, 7.0, 39.0, 41.0, 15.0),
        doubleArrayOf(
             0.14082834,  0.09748790,  1.73131507,  0.87636009, -1.95059594,  0.73438555,
            -0.03035726,  1.46675970, -0.74621349, -0.72588772,  0.63905160,  0.61501527,
            -0.98983780, -1.00447874, -0.62759469,  0.66206163,  1.04312009, -0.10305385,
             0.75775634,  0.32566578
        )
    )
    xl.forEach { println("${fivenum(it).asList()}\n") }
}


Flatten a list

Write a function to flatten the nesting in an arbitrary list of values.

Your program should work on the equivalent of this list:
   [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]
Where the correct result would be the list:
    [1, 2, 3, 4, 5, 6, 7, 8]

;Related task:
*   [[Tree traversal]]

Solution:
// version 1.0.6

@Suppress("UNCHECKED_CAST")

fun flattenList(nestList: List<Any>, flatList: MutableList<Int>) {
    for (e in nestList)
        if (e is Int)
            flatList.add(e)
        else
            // using unchecked cast here as can't check for instance of 'erased' generic type
            flattenList(e as List<Any>, flatList)
}

fun main(args: Array<String>) {
    val nestList : List<Any> = listOf(
        listOf(1),
        2,
        listOf(listOf(3, 4), 5),
        listOf(listOf(listOf<Int>())),
        listOf(listOf(listOf(6))),
        7,
        8,
        listOf<Int>()
    )
    println("Nested    : " + nestList)
    val flatList = mutableListOf<Int>()
    flattenList(nestList, flatList)
    println("Flattened : " + flatList)
}


Flipping bits game

The game:
Given an   '''NxN'''   square array of zeroes or ones in an initial configuration,   and a target configuration of zeroes and ones.

The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered
columns at once   (as one move).

In an inversion.   any  '''1'''  becomes  '''0''',   and any  '''0'''  becomes  '''1'''  for that whole row or column.

;Task:
Create a program to score for the Flipping bits game.
# The game should create an original random target configuration and a starting configuration.
# Ensure that the starting position is ''never'' the target position.
# The target position must be guaranteed as reachable from the starting position.   (One possible way to do this is to generate the start position by legal flips from a random target position.   The flips will always be reversible back to the target from the given start position).
# The number of moves taken so far should be shown.

Show an example of a short game here, on this page, for a   '''3x3'''   array of bits.

Solution:
// version 1.1.3

import java.util.Random

val rand = Random()
val target = Array(3) { IntArray(3) { rand.nextInt(2) } }
val board  = Array(3) { IntArray(3) }

fun flipRow(r: Int) {
    for (c in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0
}

fun flipCol(c: Int) {
    for (r in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0
}

/** starting from the target we make 9 random row or column flips */
fun initBoard() {
    for (i in 0..2) {
        for (j in 0..2) board[i][j] = target[i][j]
    }
    repeat(9) {
        val rc = rand.nextInt(2)
        if (rc == 0)
            flipRow(rand.nextInt(3))
        else
            flipCol(rand.nextInt(3))
    }
}

fun printBoard(label: String, isTarget: Boolean = false) {
    val a = if (isTarget) target else board
    println("$label:")
    println("  | a b c")
    println("---------")
    for (r in 0..2) {
        print("${r + 1} |")
        for (c in 0..2) print(" ${a[r][c]}")
        println()
    }
    println()
}

fun gameOver(): Boolean {
    for (r in 0..2) {
        for (c in 0..2) if (board[r][c] != target[r][c]) return false
    }
    return true
}

fun main(args: Array<String>) {
     // initialize board and ensure it differs from the target i.e. game not already over!
    do {
        initBoard()
    }
    while(gameOver())

    printBoard("TARGET", true)
    printBoard("OPENING BOARD")
    var flips = 0

    do {
        var isRow = true
        var n = -1
        do {
            print("Enter row number or column letter to be flipped: ")
            val input = readLine()!!
            val ch = if (input.isNotEmpty()) input[0].toLowerCase() else '0'
            if (ch !in "123abc") {
                println("Must be 1, 2, 3, a, b or c")
                continue
            }
            if (ch in '1'..'3') {
                n = ch.toInt() - 49
            }
            else {
                isRow = false
                n = ch.toInt() - 97
            }
        }
        while (n == -1)

        flips++
        if (isRow) flipRow(n) else flipCol(n)
        val plural = if (flips == 1) "" else "S"
        printBoard("\nBOARD AFTER $flips FLIP$plural")
    }
    while (!gameOver())

    val plural = if (flips == 1) "" else "s"
    println("You've succeeded in $flips flip$plural")
}


Floyd's triangle

Floyd's triangle   lists the natural numbers in a right triangle aligned to the left where
* the first row is   '''1'''     (unity)
* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.

The first few lines of a Floyd triangle looks like this:

 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

;Task:
:# Write a program to generate and display here the first   n   lines of a Floyd triangle. (Use   n=5   and   n=14   rows).
:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.

Solution:
fun main(args: Array<String>) = args.forEach { Triangle(it.toInt()) }

internal class Triangle(n: Int) {
    init {
        println("$n rows:")
        var printMe = 1
        var printed = 0
        var row = 1
        while (row <= n) {
            val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).toInt()
            print("%${cols}d ".format(printMe))
            if (++printed == row) { println(); row++; printed = 0 }
            printMe++
        }
    }
}


Four bit adder

"''Simulate''" a four-bit adder.

This design can be realized using four 1-bit full adders.
Each of these 1-bit full adders can be built with two gate. ;

Finally a half adder can be made using an   ''xor''   gate and an   ''and''   gate.

The   ''xor''   gate can be made using two   ''not''s,   two   ''and''s   and one   ''or''.

'''Not''',   '''or'''   and   '''and''',   the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language.

If there is not a ''bit type'' in your language, to be sure that the   ''not''   does not "invert" all the other bits of the basic type   (e.g. a byte)   we are not interested in,   you can use an extra   ''nand''   (''and''   then   ''not'')   with the constant   '''1'''   on one input.

Instead of optimizing and reducing the number of gates used for the final 4-bit adder,   build it in the most straightforward way,   ''connecting'' the other "constructive blocks",   in turn made of "simpler" and "smaller" ones.

{|
|+Schematics of the "constructive blocks"
!(Xor gate with ANDs, ORs and NOTs)
!   (A half adder)
!          (A full adder)
!                (A 4-bit adder)
|-
|Xor gate done with ands, ors and nots
|A half adder
|A full adder
|A 4-bit adder
|}

Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks".

It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.

To test the implementation, show the sum of two four-bit numbers (in binary).

Solution:
// version 1.1.51

val Boolean.I get() = if (this) 1 else 0

val Int.B get() = this != 0

class Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) {
    fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8

    override fun toString() = "${n3.I}${n2.I}${n1.I}${n0.I}"
}

fun Int.toNybble(): Nybble {
    val n = BooleanArray(4)
    for (k in 0..3) n[k] = ((this shr k) and 1).B
    return Nybble(n[3], n[2], n[1], n[0])
}

fun xorGate(a: Boolean, b: Boolean) = (a && !b) || (!a && b)

fun halfAdder(a: Boolean, b: Boolean) = Pair(xorGate(a, b), a && b)

fun fullAdder(a: Boolean, b: Boolean, c: Boolean): Pair<Boolean, Boolean> {
    val (s1, c1) = halfAdder(c, a)
    val (s2, c2) = halfAdder(s1, b)
    return s2 to (c1 || c2)
}

fun fourBitAdder(a: Nybble, b: Nybble): Pair<Nybble, Int> {
    val (s0, c0) = fullAdder(a.n0, b.n0, false)
    val (s1, c1) = fullAdder(a.n1, b.n1, c0)
    val (s2, c2) = fullAdder(a.n2, b.n2, c1)
    val (s3, c3) = fullAdder(a.n3, b.n3, c2)
    return Nybble(s3, s2, s1, s0) to c3.I
}

const val f = "%s + %s = %d %s (%2d + %2d = %2d)"

fun test(i: Int, j: Int) {
    val a = i.toNybble()
    val b = j.toNybble()
    val (r, c) = fourBitAdder(a, b)
    val s = c * 16 + r.toInt()
    println(f.format(a, b, c, r, i, j, s))
}

fun main(args: Array<String>) {
    println(" A      B     C  R     I    J    S")
    for (i in 0..15) {
        for (j in i..minOf(i + 1, 15)) test(i, j)
    }
}


Four is magic

Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.

Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word.

Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.

For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.'''

      '''Three is five, five is four, four is magic.'''

For reference, here are outputs for 0 through 9.

      Zero is four, four is magic.
      One is three, three is five, five is four, four is magic.
      Two is three, three is five, five is four, four is magic.
      Three is five, five is four, four is magic.
      Four is magic.
      Five is four, four is magic.
      Six is three, three is five, five is four, four is magic.
      Seven is five, five is four, four is magic.
      Eight is five, five is four, four is magic.
      Nine is four, four is magic.

;Some task guidelines:
:* You may assume the input will only contain integer numbers.
:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)
:* Cardinal number conversions should follow the  English short scale. (billion is 1e9, trillion is 1e12, etc.)
:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)
:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.
:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.
:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.
:* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.")
:* The output can either be the return value from the function, or be displayed from within the function.
:* You are encouraged, though not mandated to use proper sentence capitalization.
:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.
:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.

You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public.

If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)

Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.

;Related tasks:
:*   [[Four is the number of_letters in the ...]]
:*   [[Look-and-say sequence]]
:*   [[Number names]]
:*   [[Self-describing numbers]]
:*   [[Summarize and say sequence]]
:*   [[Spelling of ordinal numbers]]
:*   [[De Bruijn sequences]]

Solution:
// version 1.1.4-3

val names = mapOf(
    1 to "one",
    2 to "two",
    3 to "three",
    4 to "four",
    5 to "five",
    6 to "six",
    7 to "seven",
    8 to "eight",
    9 to "nine",
    10 to "ten",
    11 to "eleven",
    12 to "twelve",
    13 to "thirteen",
    14 to "fourteen",
    15 to "fifteen",
    16 to "sixteen",
    17 to "seventeen",
    18 to "eighteen",
    19 to "nineteen",
    20 to "twenty",
    30 to "thirty",
    40 to "forty",
    50 to "fifty",
    60 to "sixty",
    70 to "seventy",
    80 to "eighty",
    90 to "ninety"
)
val bigNames = mapOf(
    1_000L to "thousand",
    1_000_000L to "million",
    1_000_000_000L to "billion",
    1_000_000_000_000L to "trillion",
    1_000_000_000_000_000L to "quadrillion",
    1_000_000_000_000_000_000L to "quintillion"
)

fun numToText(n: Long): String {
    if (n == 0L) return "zero"
    val neg = n < 0L
    val maxNeg = n == Long.MIN_VALUE
    var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
    val digits3 = IntArray(7)
    for (i in 0..6) {  // split number into groups of 3 digits from the right
        digits3[i] = (nn % 1000).toInt()
        nn /= 1000
    }

    fun threeDigitsToText(number: Int) : String {
        val sb = StringBuilder()
        if (number == 0) return ""
        val hundreds = number / 100
        val remainder = number % 100
        if (hundreds > 0) {
            sb.append(names[hundreds], " hundred")
            if (remainder > 0) sb.append(" ")
        }
        if (remainder > 0) {
            val tens = remainder / 10
            val units = remainder % 10
            if (tens > 1) {
                sb.append(names[tens * 10])
                if (units > 0) sb.append("-", names[units])
            }
            else sb.append(names[remainder])
        }
        return sb.toString()
    }

    val strings = Array<String>(7) { threeDigitsToText(digits3[it]) }
    var text = strings[0]
    var big = 1000L
    for (i in 1..6) {
        if (digits3[i] > 0) {
            var text2 = strings[i] + " " + bigNames[big]
            if (text.length > 0) text2 += " "
            text = text2 + text
        }
        big *= 1000
    }
    if (maxNeg) text = text.dropLast(5) + "eight"
    if (neg) text = "negative " + text
    return text
}

fun fourIsMagic(n: Long): String {
    if (n == 4L) return "Four is magic."
    var text = numToText(n).capitalize()
    val sb = StringBuilder()
    while (true) {
        val len = text.length.toLong()
        if (len == 4L) return sb.append("$text is four, four is magic.").toString()
        val text2 = numToText(len)
        sb.append("$text is $text2, ")
        text = text2
    }
}

fun main(args: Array<String>) {
    val la = longArrayOf(0, 4, 6, 11, 13, 75, 100, 337, -164, 9_223_372_036_854_775_807L)
    for (i in la) {
        println(fourIsMagic(i))
        println()
    }
}


Four is the number of letters in the ...

The      '''Four is ...'''      sequence is based on the counting of the number of
letters in the words of the (never-ending) sentence:
   Four is the number of letters in the first word of this sentence, two in the second,
   three in the third, six in the fourth, two in the fifth, seven in the sixth, ***

;Definitions and directives:
:*   English is to be used in spelling numbers.
:*   '''Letters'''   are defined as the upper- and lowercase letters in the Latin alphabet   ('''A-->Z'''   and   '''a-->z''').
:*   Commas are not counted,   nor are hyphens (dashes or minus signs).
:*   '''twenty-three'''   has eleven letters.
:*   '''twenty-three'''   is considered one word   (which is hyphenated).
:*   no   ''' ''and'' '''   words are to be used when spelling a (English) word for a number.
:*   The American version of numbers will be used here in this task   (as opposed to the British version).
          '''2,000,000,000'''   is two billion,   ''not''   two milliard.

;Task:
:*   Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first   '''N'''    words in the never-ending sentence.   For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble),   the sequence would be:
          '''4  2  3  6  2  7'''
:*   Only construct as much as is needed for the never-ending sentence.
:*   Write a driver (invoking routine) to show the number of letters in the   Nth   word,   ''as well as''   showing the   Nth   word itself.
:*   After each test case, show the total number of characters   (including blanks, commas, and punctuation)   of the sentence that was constructed.
:*   Show all output here.

;Test cases:
  Display the first  201  numbers in the sequence   (and the total number of characters in the sentence).
  Display the number of letters  (and the word itself)  of the       1,000th  word.
  Display the number of letters  (and the word itself)  of the      10,000th  word.
  Display the number of letters  (and the word itself)  of the     100,000th  word.
  Display the number of letters  (and the word itself)  of the   1,000,000th  word.
  Display the number of letters  (and the word itself)  of the  10,000,000th  word  (optional).

;Related tasks:
:*   [[Four is magic]]
:*   [[Look-and-say sequence]]
:*   [[Number names]]
:*   [[Self-describing numbers]]
:*   [[Self-referential sequence]]
:*   [[Spelling of ordinal numbers]]

;Also see:
:*   See the OEIS sequence  A72425  "Four is the number of letters...".
:*   See the OEIS sequence  A72424  "Five's the number of letters..."

Solution:
// version 1.1.4-3

val names = mapOf(
    1 to "one",
    2 to "two",
    3 to "three",
    4 to "four",
    5 to "five",
    6 to "six",
    7 to "seven",
    8 to "eight",
    9 to "nine",
    10 to "ten",
    11 to "eleven",
    12 to "twelve",
    13 to "thirteen",
    14 to "fourteen",
    15 to "fifteen",
    16 to "sixteen",
    17 to "seventeen",
    18 to "eighteen",
    19 to "nineteen",
    20 to "twenty",
    30 to "thirty",
    40 to "forty",
    50 to "fifty",
    60 to "sixty",
    70 to "seventy",
    80 to "eighty",
    90 to "ninety"
)

val bigNames = mapOf(
    1_000L to "thousand",
    1_000_000L to "million",
    1_000_000_000L to "billion",
    1_000_000_000_000L to "trillion",
    1_000_000_000_000_000L to "quadrillion",
    1_000_000_000_000_000_000L to "quintillion"
)

val irregOrdinals = mapOf(
    "one" to "first",
    "two" to "second",
    "three" to "third",
    "five" to "fifth",
    "eight" to "eighth",
    "nine" to "ninth",
    "twelve" to "twelfth"
)

fun String.toOrdinal(): String {
    if (this == "zero") return "zeroth"  // or alternatively 'zeroeth'
    val splits = this.split(' ', '-')
    val last = splits[splits.lastIndex]
    return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!
           else if (last.endsWith("y")) this.dropLast(1) + "ieth"
           else this + "th"
}

fun numToText(n: Long, uk: Boolean = false): String {
    if (n == 0L) return "zero"
    val neg = n < 0L
    val maxNeg = n == Long.MIN_VALUE
    var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
    val digits3 = IntArray(7)
    for (i in 0..6) {  // split number into groups of 3 digits from the right
        digits3[i] = (nn % 1000).toInt()
        nn /= 1000
    }

    fun threeDigitsToText(number: Int) : String {
        val sb = StringBuilder()
        if (number == 0) return ""
        val hundreds = number / 100
        val remainder = number % 100
        if (hundreds > 0) {
            sb.append(names[hundreds], " hundred")
            if (remainder > 0) sb.append(if (uk) " and " else " ")
        }
        if (remainder > 0) {
            val tens = remainder / 10
            val units = remainder % 10
            if (tens > 1) {
                sb.append(names[tens * 10])
                if (units > 0) sb.append("-", names[units])
            }
            else sb.append(names[remainder])
        }
        return sb.toString()
    }

    val strings = Array(7) { threeDigitsToText(digits3[it]) }
    var text = strings[0]
    var andNeeded = uk && digits3[0] in 1..99
    var big = 1000L
    for (i in 1..6) {
        if (digits3[i] > 0) {
            var text2 = strings[i] + " " + bigNames[big]
            if (text.isNotEmpty()) {
                text2 += if (andNeeded) " and " else " "  // no commas inserted in this version
                andNeeded = false
            }
            else andNeeded = uk && digits3[i] in 1..99
            text = text2 + text
        }
        big *= 1000
    }
    if (maxNeg) text = text.dropLast(5) + "eight"
    if (neg) text = "minus " + text
    return text
}

val opening = "Four is the number of letters in the first word of this sentence,".split(' ')

val String.adjustedLength get() = this.replace(",", "").replace("-", "").length  // no ',' or '-'

fun getWords(n: Int): List<String> {
    val words = mutableListOf<String>()
    words.addAll(opening)
    if (n > opening.size) {
        var k = 2
        while (true) {
            val len = words[k - 1].adjustedLength
            val text = numToText(len.toLong())
            val splits = text.split(' ')
            words.addAll(splits)
            words.add("in")
            words.add("the")
            val text2 = numToText(k.toLong()).toOrdinal() + ","  // add trailing comma
            val splits2 = text2.split(' ')
            words.addAll(splits2)
            if (words.size >= n) break
            k++
        }
    }
    return words
}

fun getLengths(n: Int): Pair<List<Int>, Int> {
    val words = getWords(n)
    val lengths = words.take(n).map { it.adjustedLength }
    val sentenceLength = words.sumBy { it.length } + words.size - 1  // includes hyphens, commas & spaces
    return Pair(lengths, sentenceLength)
}

fun getLastWord(n: Int): Triple<String, Int, Int> {
    val words = getWords(n)
    val nthWord = words[n - 1]
    val nthWordLength = nthWord.adjustedLength
    val sentenceLength = words.sumBy { it.length } + words.size - 1  // includes hyphens, commas & spaces
    return Triple(nthWord, nthWordLength, sentenceLength)
}

fun main(args: Array<String>) {
    var n = 201
    println("The lengths of the first $n words are:\n")
    val (list, sentenceLength) = getLengths(n)
    for (i in 0 until n) {
        if (i % 25 == 0) {
            if (i > 0) println()
            print("${"%3d".format(i + 1)}: ")
        }
        print("%3d".format(list[i]))
    }
    println("\n\nLength of sentence = $sentenceLength\n")
    n = 1_000
    do {
        var (word, wLen, sLen) = getLastWord(n)
        if (word.endsWith(",")) word = word.dropLast(1)  // strip off any trailing comma
        println("The length of word $n [$word] is $wLen")
        println("Length of sentence = $sLen\n")
        n *= 10
    }
    while (n <= 10_000_000)
}


French Republican calendar

Write a program to convert dates between the French Republican calendar.

The year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fete de la vertu / Virtue Day, Fete du genie / Talent Day, Fete du travail / Labour Day, Fete de l'opinion / Opinion Day, and Fete des recompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fete de la Revolution / Revolution Day.

As a minimum, your program should give correct results for dates in the range from 1 Vendemiaire 1 = 22 September 1792 to 10 Nivose 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)

Test your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:

* 1 Vendemiaire 1 = 22 September 1792

* 1 Prairial 3 = 20 May 1795

* 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)

* Fete de la Revolution 11 = 23 September 1803

* 10 Nivose 14 = 31 December 1805

Solution:
// version 1.1.4-3

import java.time.format.DateTimeFormatter
import java.time.LocalDate
import java.time.temporal.ChronoUnit.DAYS

/* year = 1..  month = 1..13  day = 1..30 */
class FrenchRCDate(val year: Int, val month: Int, val day: Int) {

    init {
        require (year > 0 && month in 1..13)
        if (month < 13) require (day in 1..30)
        else {
            val leap = isLeapYear(year)
            require (day in (if (leap) 1..6 else 1..5))
        }
    }

    override fun toString() =
        if (month < 13) "$day ${months[month - 1]} $year"
        else "${intercal[day - 1]} $year"

    fun toLocalDate(): LocalDate {
        var sumDays = 0L
        for (i in 1 until year) sumDays += if (isLeapYear(i)) 366 else 365
        val dayInYear = (month - 1) * 30 + day - 1
        return introductionDate.plusDays(sumDays + dayInYear)
    }

    companion object {
        /* uses the 'continuous method' for years after 1805 */
        fun isLeapYear(y: Int): Boolean {
            val yy = y + 1
            return (yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0)
        }

        fun parse(frcDate: String): FrenchRCDate {
            val splits = frcDate.trim().split(' ')
            if (splits.size == 3) {
                val month = months.indexOf(splits[1]) + 1
                require(month in 1..13)
                val year = splits[2].toIntOrNull() ?: 0
                require(year > 0)
                val monthLength = if (month < 13) 30 else if (isLeapYear(year)) 6 else 5
                val day = splits[0].toIntOrNull() ?: 0
                require(day in 1..monthLength)
                return FrenchRCDate(year, month, day)
            }
            else if (splits.size in 4..5) {
                val yearStr = splits[splits.lastIndex]
                val year = yearStr.toIntOrNull() ?: 0
                require(year > 0)
                val scDay = frcDate.trim().dropLast(yearStr.length + 1)
                val day = intercal.indexOf(scDay) + 1
                val maxDay = if (isLeapYear(year)) 6 else 5
                require (day in 1..maxDay)
                return FrenchRCDate(year, 13, day)
            }
            else throw IllegalArgumentException("Invalid French Republican date")
        }

        /* for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days */
        val months = arrayOf(
            "Vendémiaire", "Brumaire", "Frimaire", "Nivôse", "Pluviôse", "Ventôse", "Germinal",
            "Floréal", "Prairial", "Messidor", "Thermidor", "Fructidor", "Sansculottide"
        )

        val intercal = arrayOf(
            "Fête de la vertu", "Fête du génie", "Fête du travail",
            "Fête de l'opinion", "Fête des récompenses", "Fête de la Révolution"
        )

        val introductionDate = LocalDate.of(1792, 9, 22)
    }
}

fun LocalDate.toFrenchRCDate(): FrenchRCDate {
    val daysDiff  = DAYS.between(FrenchRCDate.introductionDate, this).toInt() + 1
    if (daysDiff <= 0) throw IllegalArgumentException("Date can't be before 22 September 1792")
    var year = 1
    var startDay = 1
    while (true) {
        val endDay = startDay + if (FrenchRCDate.isLeapYear(year)) 365 else 364
        if (daysDiff in startDay..endDay) break
        year++
        startDay = endDay + 1
    }
    val remDays = daysDiff - startDay
    val month  = remDays / 30
    val day = remDays - month * 30
    return FrenchRCDate(year, month + 1, day + 1)
}

fun main(args: Array<String>) {
    val formatter = DateTimeFormatter.ofPattern("d MMMM yyyy")
    val dates = arrayOf("22 September 1792", "20 May 1795", "15 July 1799", "23 September 1803",
                        "31 December 1805", "18 March 1871", "25 August 1944", "19 September 2016",
                        "22 September 2017", "28 September 2017")
    val frcDates = Array<String>(dates.size) { "" }
    for ((i, date) in dates.withIndex()) {
        val thisDate = LocalDate.parse(date, formatter)
        val frcd = thisDate.toFrenchRCDate()
        frcDates[i] = frcd.toString()
        println("${date.padEnd(25)} => $frcd")
    }

    // now process the other way around
    println()
    for (frcDate in frcDates) {
        val thisDate = FrenchRCDate.parse(frcDate)
        val lds = formatter.format(thisDate.toLocalDate())
        println("${frcDate.padEnd(25)} => $lds")
    }
}


Function prototype

Some languages provide the facility to declare functions and subroutines through the use of function prototyping.

;Task:
Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include:

* An explanation of any placement restrictions for prototype declarations
* A prototype declaration for a function that does not require arguments
* A prototype declaration for a function that requires two arguments
* A prototype declaration for a function that utilizes varargs
* A prototype declaration for a function that utilizes optional arguments
* A prototype declaration for a function that utilizes named parameters
* Example of prototype declarations for subroutines or procedures (if these differ from functions)
* An explanation and example of any special forms of prototyping not covered by the above

Languages that do not provide function prototyping facilities should be omitted from this task.

Solution:
// version 1.0.6

interface MyInterface {
    fun foo()                     // no arguments, no return type
    fun goo(i: Int, j: Int)       // two arguments, no return type
    fun voo(vararg v: Int)        // variable number of arguments, no return type
    fun ooo(o: Int = 1): Int      // optional argument with default value and return type Int
    fun roo(): Int                // no arguments with return type Int
    val poo: Int                // read only property of type Int
}

abstract class MyAbstractClass {
    abstract fun afoo()           // abstract member function, no arguments or return type
    abstract var apoo: Int        // abstract read/write member property of type Int
}

class Derived : MyAbstractClass(), MyInterface {
    override fun afoo() {}
    override var apoo: Int = 0

    override fun foo() {}
    override fun goo(i: Int, j: Int) {}
    override fun voo(vararg v: Int) {}
    override fun ooo(o: Int): Int = o  // can't specify default argument again here but same as in interface
    override fun roo(): Int = 2
    override val poo: Int = 3
}

fun main(args: Array<String>) {
    val d = Derived()
    println(d.apoo)
    println(d.ooo())  // default argument of 1 inferred
    println(d.roo())
    println(d.poo)
}


Functional coverage tree

Functional coverage is a measure of how much a particular function of a system
has been verified as correct. It is used heavily in tracking the completeness
of the verification of complex System on Chip (SoC) integrated circuits, where
it can also be used to track how well the functional ''requirements'' of the
system have been verified.

This task uses a sub-set of the calculations sometimes used in tracking
functional coverage but uses a more familiar(?) scenario.

;Task Description:
The head of the clean-up crews for "The Men in a very dark shade of grey when
viewed at night" has been tasked with managing the cleansing of two properties
after an incident involving aliens.

She arranges the task hierarchically with a manager for the crews working on
each house who return with a breakdown of how they will report on progress in
each house.

The overall hierarchy of (sub)tasks is as follows,
cleaning
    house1
        bedrooms
        bathrooms
            bathroom1
            bathroom2
            outside lavatory
        attic
        kitchen
        living rooms
            lounge
            dining room
            conservatory
            playroom
        basement
        garage
        garden
    house2
        upstairs
            bedrooms
                suite 1
                suite 2
                bedroom 3
                bedroom 4
            bathroom
            toilet
            attics
        groundfloor
            kitchen
            living rooms
                lounge
                dining room
                conservatory
                playroom
            wet room & toilet
            garage
            garden
            hot tub suite
        basement
            cellars
            wine cellar
            cinema

The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.

Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.
NAME_HIERARCHY                  |WEIGHT  |COVERAGE  |
cleaning                        |        |          |
    house1                      |40      |          |
        bedrooms                |        |0.25      |
        bathrooms               |        |          |
            bathroom1           |        |0.5       |
            bathroom2           |        |          |
            outside_lavatory    |        |1         |
        attic                   |        |0.75      |
        kitchen                 |        |0.1       |
        living_rooms            |        |          |
            lounge              |        |          |
            dining_room         |        |          |
            conservatory        |        |          |
            playroom            |        |1         |
        basement                |        |          |
        garage                  |        |          |
        garden                  |        |0.8       |
    house2                      |60      |          |
        upstairs                |        |          |
            bedrooms            |        |          |
                suite_1         |        |          |
                suite_2         |        |          |
                bedroom_3       |        |          |
                bedroom_4       |        |          |
            bathroom            |        |          |
            toilet              |        |          |
            attics              |        |0.6       |
        groundfloor             |        |          |
            kitchen             |        |          |
            living_rooms        |        |          |
                lounge          |        |          |
                dining_room     |        |          |
                conservatory    |        |          |
                playroom        |        |          |
            wet_room_&_toilet   |        |          |
            garage              |        |          |
            garden              |        |0.9       |
            hot_tub_suite       |        |1         |
        basement                |        |          |
            cellars             |        |1         |
            wine_cellar         |        |1         |
            cinema              |        |0.75      |

;Calculation:
The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.

'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.

;Extra Credit:
After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.
The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.

The pseudo code would be:

    method delta_calculation(this, power):
        sum_of_weights = sum(node.weight for node in children)
        this.delta  = (1 - this.coverage) * power
        for node in self.children:
            node.delta_calculation(power * node.weight / sum_of_weights)
        return this.delta

Followed by a call to:

    top.delta_calculation(power=1)

'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.

Solution:
// version 1.2.10

class FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {

    var coverage = coverage
        set(value) {
            if (field != value) {
               field = value
               // update any parent's coverage
               if (parent != null) parent!!.updateCoverage()
            }
        }

    val children = mutableListOf<FCNode>()
    var parent: FCNode? = null

    fun addChildren(nodes: List<FCNode>) {
        children.addAll(nodes)
        nodes.forEach { it.parent = this }
        updateCoverage()
    }

    private fun updateCoverage() {
        val v1 = children.sumByDouble { it.weight * it.coverage }
        val v2 = children.sumBy { it.weight }
        coverage = v1 / v2
    }

    fun show(level: Int = 0) {
        val indent = level * 4
        val nl = name.length + indent
        print(name.padStart(nl))
        print("|".padStart(32 - nl))
        print("  %3d   |".format(weight))
        println(" %8.6f |".format(coverage))
        if (children.size == 0) return
        for (child in children) child.show(level + 1)
    }
}

val houses = listOf(
    FCNode("house1", 40),
    FCNode("house2", 60)
)

val house1 = listOf(
    FCNode("bedrooms", 1, 0.25),
    FCNode("bathrooms"),
    FCNode("attic", 1, 0.75),
    FCNode("kitchen", 1, 0.1),
    FCNode("living_rooms"),
    FCNode("basement"),
    FCNode("garage"),
    FCNode("garden", 1, 0.8)
)

val house2 = listOf(
    FCNode("upstairs"),
    FCNode("groundfloor"),
    FCNode("basement")
)

val h1Bathrooms = listOf(
    FCNode("bathroom1", 1, 0.5),
    FCNode("bathroom2"),
    FCNode("outside_lavatory", 1, 1.0)
)

val h1LivingRooms = listOf(
    FCNode("lounge"),
    FCNode("dining_room"),
    FCNode("conservatory"),
    FCNode("playroom", 1, 1.0)
)

val h2Upstairs = listOf(
    FCNode("bedrooms"),
    FCNode("bathroom"),
    FCNode("toilet"),
    FCNode("attics", 1, 0.6)
)

val h2Groundfloor = listOf(
    FCNode("kitchen"),
    FCNode("living_rooms"),
    FCNode("wet_room_&_toilet"),
    FCNode("garage"),
    FCNode("garden", 1, 0.9),
    FCNode("hot_tub_suite", 1, 1.0)
)

val h2Basement = listOf(
    FCNode("cellars", 1, 1.0),
    FCNode("wine_cellar", 1, 1.0),
    FCNode("cinema", 1, 0.75)
)

val h2UpstairsBedrooms = listOf(
    FCNode("suite_1"),
    FCNode("suite_2"),
    FCNode("bedroom_3"),
    FCNode("bedroom_4")
)

val h2GroundfloorLivingRooms = listOf(
    FCNode("lounge"),
    FCNode("dining_room"),
    FCNode("conservatory"),
    FCNode("playroom")
)

fun main(args: Array<String>) {
    val cleaning = FCNode("cleaning")

    house1[1].addChildren(h1Bathrooms)
    house1[4].addChildren(h1LivingRooms)
    houses[0].addChildren(house1)

    h2Upstairs[0].addChildren(h2UpstairsBedrooms)
    house2[0].addChildren(h2Upstairs)
    h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)
    house2[1].addChildren(h2Groundfloor)
    house2[2].addChildren(h2Basement)
    houses[1].addChildren(house2)

    cleaning.addChildren(houses)
    val topCoverage = cleaning.coverage
    println("TOP COVERAGE = ${"%8.6f".format(topCoverage)}\n")
    println("NAME HIERARCHY                 | WEIGHT | COVERAGE |")
    cleaning.show()

    h2Basement[2].coverage = 1.0  // change Cinema node coverage to 1.0
    val diff = cleaning.coverage - topCoverage
    println("\nIf the coverage of the Cinema node were increased from 0.75 to 1.0")
    print("the top level coverage would increase by ")
    println("${"%8.6f".format(diff)} to ${"%8.6f".format(topCoverage + diff)}")
    h2Basement[2].coverage = 0.75  // restore to original value if required
}


Fusc sequence

Definitions:
The   '''fusc'''   integer sequence is defined as:
::*   fusc(0) = 0
::*   fusc(1) = 1
::*   for '''n'''>1,   the   '''n'''th   term is defined as:
::::*   if   '''n'''   is       even;     fusc(n) = fusc(n/2)
::::*   if   '''n'''   is   odd;     fusc(n) = fusc((n-1)/2)   +   fusc((n+1)/2)

Note that MathWorld's definition starts with unity, not zero.   This task will be using the OEIS' version   (above).

;An observation:
:::::*   fusc(A) = fusc(B)

where   '''A'''   is some non-negative integer expressed in binary,   and
where   '''B'''   is the binary value of   '''A'''   reversed.

Fusc numbers are also known as:
::*   fusc function   (named by Dijkstra, 1982)
::*   Stern's Diatomic series   (although it starts with unity, not zero)
::*   Stern-Brocot sequence   (although it starts with unity, not zero)

;Task:
::*   show the first   '''61'''   fusc numbers (starting at zero) in a horizontal format.
::*   show the fusc number (and its index) whose length is greater than any previous fusc number length.
::::*   (the length is the number of decimal digits when the fusc number is expressed in base ten.)
::*   show all numbers with commas   (if appropriate).
::*   show all output here.

;Related task:
::*   RosettaCode Stern-Brocot sequence

;Also see:
::*   the MathWorld entry:   Stern's Diatomic Series.
::*   the OEIS      entry:   A2487.

Solution:
// Version 1.3.21

fun fusc(n: Int): IntArray {
    if (n <= 0) return intArrayOf()
    if (n == 1) return intArrayOf(0)
    val res = IntArray(n)
    res[1] = 1
    for (i in 2 until n) {
        if (i % 2 == 0) {
            res[i] = res[i / 2]
        } else {
            res[i] = res[(i - 1) / 2] + res[(i + 1) / 2]
        }
    }
    return res
}

fun fuscMaxLen(n: Int): List<Pair<Int, Int>> {
    var maxLen = -1
    var maxFusc = -1
    val f = fusc(n)
    val res = mutableListOf<Pair<Int, Int>>()
    for (i in 0 until n) {
        if (f[i] <= maxFusc) continue // avoid string conversion
        maxFusc = f[i]
        val len = f[i].toString().length
        if (len > maxLen) {
            res.add(Pair(i, f[i]))
            maxLen = len
        }
    }
    return res
}

fun main() {
    println("The first 61 fusc numbers are:")
    println(fusc(61).asList())
    println("\nThe fusc numbers whose length > any previous fusc number length are:")
    val res = fuscMaxLen(20_000_000)  // examine first 20 million numbers say
    for (r in res) {
        System.out.printf("%,7d (index %,10d)\n", r.second, r.first)
    }
}


Gapful numbers

Numbers   (positive integers expressed in base ten)   that are (evenly) divisible by the number formed by the
first and last digit are known as   '''gapful numbers'''.

''Evenly divisible''   means divisible with   no   remainder.

All   one-   and two-digit   numbers have this property and are trivially excluded.   Only
numbers    >=  '''100'''   will be considered for this Rosetta Code task.

;Example:
'''187'''   is a   '''gapful'''   number because it is evenly divisible by the
number   '''17'''   which is formed by the first and last decimal digits
of    '''187'''.

About   7.46%   of positive integers are   ''gapful''.

;Task:
:*   Generate and show all sets of numbers (below) on one line (horizontally) with a title,   here on this page
:*   Show the first   '''30'''   gapful numbers
:*   Show the first   '''15'''   gapful numbers    >=           '''1,000,000'''
:*   Show the first   '''10'''   gapful numbers    >=                               '''1,000,000,000'''

;Related tasks:
:*   Harshad or Niven series.
:*   palindromic gapful numbers.
:*   largest number divisible by its digits.

;Also see:
:*   The OEIS entry:   A108343 gapful numbers.
:*   numbersaplenty gapful numbers

Solution:
private fun commatize(n: Long): String {
    val sb = StringBuilder(n.toString())
    val le = sb.length
    var i = le - 3
    while (i >= 1) {
        sb.insert(i, ',')
        i -= 3
    }
    return sb.toString()
}

fun main() {
    val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.toLong())
    val counts = listOf(30, 15, 15, 10, 25)
    for (i in starts.indices) {
        var count = 0
        var j = starts[i]
        var pow: Long = 100
        while (j >= pow * 10) {
            pow *= 10
        }
        System.out.printf(
            "First %d gapful numbers starting at %s:\n",
            counts[i],
            commatize(starts[i])
        )
        while (count < counts[i]) {
            val fl = j / pow * 10 + j % 10
            if (j % fl == 0L) {
                System.out.printf("%d ", j)
                count++
            }
            j++
            if (j >= 10 * pow) {
                pow *= 10
            }
        }
        println('\n')
    }
}


Gauss-Jordan matrix inversion

Invert matrix   '''A'''   using Gauss-Jordan method.

'''A'''   being an   '''n''' x '''n'''   matrix.

Solution:
// version 1.2.21

typealias Matrix = Array<DoubleArray>

fun Matrix.inverse(): Matrix {
    val len = this.size
    require(this.all { it.size == len }) { "Not a square matrix" }
    val aug = Array(len) { DoubleArray(2 * len) }
    for (i in 0 until len) {
        for (j in 0 until len) aug[i][j] = this[i][j]
        // augment by identity matrix to right
        aug[i][i + len] = 1.0
    }
    aug.toReducedRowEchelonForm()
    val inv = Array(len) { DoubleArray(len) }
    // remove identity matrix to left
    for (i in 0 until len) {
        for (j in len until 2 * len) inv[i][j - len] = aug[i][j]
    }
    return inv
}

fun Matrix.toReducedRowEchelonForm() {
    var lead = 0
    val rowCount = this.size
    val colCount = this[0].size
    for (r in 0 until rowCount) {
        if (colCount <= lead) return
        var i = r

        while (this[i][lead] == 0.0) {
            i++
            if (rowCount == i) {
                i = r
                lead++
                if (colCount == lead) return
            }
        }

        val temp = this[i]
        this[i] = this[r]
        this[r] = temp

        if (this[r][lead] != 0.0) {
           val div = this[r][lead]
           for (j in 0 until colCount) this[r][j] /= div
        }

        for (k in 0 until rowCount) {
            if (k != r) {
                val mult = this[k][lead]
                for (j in 0 until colCount) this[k][j] -= this[r][j] * mult
            }
        }

        lead++
    }
}

fun Matrix.printf(title: String) {
    println(title)
    val rowCount = this.size
    val colCount = this[0].size

    for (r in 0 until rowCount) {
        for (c in 0 until colCount) {
            if (this[r][c] == -0.0) this[r][c] = 0.0  // get rid of negative zeros
            print("${"% 10.6f".format(this[r][c])}  ")
        }
        println()
    }

    println()
}

fun main(args: Array<String>) {
    val a = arrayOf(
        doubleArrayOf(1.0, 2.0, 3.0),
        doubleArrayOf(4.0, 1.0, 6.0),
        doubleArrayOf(7.0, 8.0, 9.0)
    )
    a.inverse().printf("Inverse of A is :\n")

    val b = arrayOf(
        doubleArrayOf( 2.0, -1.0,  0.0),
        doubleArrayOf(-1.0,  2.0, -1.0),
        doubleArrayOf( 0.0, -1.0,  2.0)
    )
    b.inverse().printf("Inverse of B is :\n")
}


Gaussian elimination

Solve   '''Ax=b'''   using Gaussian elimination then backwards substitution.

'''A'''   being an   '''n''' by '''n'''   matrix.

Also,   '''x''' and '''b'''   are   '''n''' by '''1'''   vectors.

To improve accuracy, please use partial pivoting and scaling.

;See also:
:*   the Wikipedia entry:   Gaussian elimination

Solution:
// version 1.1.51

val ta = arrayOf(
    doubleArrayOf(1.00, 0.00, 0.00, 0.00, 0.00, 0.00),
    doubleArrayOf(1.00, 0.63, 0.39, 0.25, 0.16, 0.10),
    doubleArrayOf(1.00, 1.26, 1.58, 1.98, 2.49, 3.13),
    doubleArrayOf(1.00, 1.88, 3.55, 6.70, 12.62, 23.80),
    doubleArrayOf(1.00, 2.51, 6.32, 15.88, 39.90, 100.28),
    doubleArrayOf(1.00, 3.14, 9.87, 31.01, 97.41, 306.02)
)

val tb = doubleArrayOf(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02)

val tx = doubleArrayOf(
    -0.01, 1.602790394502114, -1.6132030599055613,
    1.2454941213714368, -0.4909897195846576, 0.065760696175232
)

const val EPSILON = 1e-14  // tolerance required

fun gaussPartial(a0: Array<DoubleArray>, b0: DoubleArray): DoubleArray {
    val m = b0.size
    val a = Array(m) { DoubleArray(m) }
    for ((i, ai) in a0.withIndex()) {
        val row = ai.copyOf(m + 1)
        row[m] = b0[i]
        a[i] = row
    }
    for (k in 0 until a.size) {
        var iMax = 0
        var max = -1.0
        for (i in k until m) {
            val row = a[i]
            // compute scale factor s = max abs in row
            var s = -1.0
            for (j in k until m) {
                val e = Math.abs(row[j])
                if (e > s) s = e
            }
            // scale the abs used to pick the pivot
            val abs = Math.abs(row[k]) / s
            if (abs > max) {
                iMax = i
                max = abs
            }
        }
        if (a[iMax][k] == 0.0) {
            throw RuntimeException("Matrix is singular.")
        }
        val tmp = a[k]
        a[k] = a[iMax]
        a[iMax] = tmp
        for (i in k + 1 until m) {
            for (j in k + 1..m) {
                a[i][j] -= a[k][j] * a[i][k] / a[k][k]
            }
            a[i][k] = 0.0
        }
    }
    val x = DoubleArray(m)
    for (i in m - 1 downTo 0) {
        x[i] = a[i][m]
        for (j in i + 1 until m) {
            x[i] -= a[i][j] * x[j]
        }
        x[i] /= a[i][i]
    }
    return x
}

fun main(args: Array<String>) {
    val x = gaussPartial(ta, tb)
    println(x.asList())
    for ((i, xi) in x.withIndex()) {
        if (Math.abs(tx[i] - xi) > EPSILON) {
            println("Out of tolerance.")
            println("Expected values are ${tx.asList()}")
            return
        }
    }
}


Generate Chess960 starting position

Bobby Fischer.  Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:

* as in the standard chess game, all eight white pawns must be placed on the second rank.
* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:
** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)
** the King must be between two rooks (with any number of other pieces between them all)
* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game.  (That is, their positions are not independently randomized.)

With those constraints there are '''960''' possible starting positions, thus the name of the variant.

;Task:
The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode:  or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.

Solution:
object Chess960 : Iterable<String> {
    override fun iterator() = patterns.iterator()

    private operator fun invoke(b: String, e: String) {
        if (e.length <= 1) {
            val s = b + e
            if (s.is_valid()) patterns += s
        } else {
            for (i in 0 until e.length) {
                invoke(b + e[i], e.substring(0, i) + e.substring(i + 1))
            }
        }
    }

    private fun String.is_valid(): Boolean {
        val k = indexOf('K')
        return indexOf('R') < k && k < lastIndexOf('R') &&
            indexOf('B') % 2 != lastIndexOf('B') % 2
    }

    private val patterns = sortedSetOf<String>()

    init {
        invoke("", "KQRRNNBB")
    }
}

fun main(args: Array<String>) {
    Chess960.forEachIndexed { i, s -> println("$i: $s") }
}


Generate random chess position

Generate a random chess position in FEN format.

The position does not have to be realistic or even balanced,  but it must comply to the following rules:
:* there is one and only one king of each color  (one black king and one white king);
:* the kings must not be placed on adjacent squares;
:* there can not be any pawn in the promotion square  (no white pawn in the eighth rank, and no black pawn in the first rank);
:* including the kings, up to 32 pieces of either color can be placed.
:* There is no requirement for material balance between sides.
:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two.
:* it is white's turn.
:* It's assumed that both sides have lost castling rights and that there is no possibility for   ''en passant''   (the FEN should thus end in w - - 0 1).

No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions.  For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.

Solution:
// version 1.2.0

import java.util.Random
import kotlin.math.abs

val rand = Random()

val grid = List(8) { CharArray(8) }

const val NUL = '\u0000'

fun createFen(): String {
    placeKings()
    placePieces("PPPPPPPP", true)
    placePieces("pppppppp", true)
    placePieces("RNBQBNR", false)
    placePieces("rnbqbnr", false)
    return toFen()
}

fun placeKings() {
    while (true) {
        val r1 = rand.nextInt(8)
        val c1 = rand.nextInt(8)
        val r2 = rand.nextInt(8)
        val c2 = rand.nextInt(8)
        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
            grid[r1][c1] = 'K'
            grid[r2][c2] = 'k'
            return
        }
    }
}

fun placePieces(pieces: String, isPawn: Boolean) {
    val numToPlace = rand.nextInt(pieces.length)
    for (n in 0 until numToPlace) {
        var r: Int
        var c: Int
        do {
            r = rand.nextInt(8)
            c = rand.nextInt(8)
        }
        while (grid[r][c] != NUL || (isPawn && (r == 7 || r == 0)))
        grid[r][c] = pieces[n]
    }
}

fun toFen(): String {
    val fen = StringBuilder()
    var countEmpty = 0
    for (r in 0..7) {
        for (c in 0..7) {
            val ch = grid[r][c]
            print ("%2c ".format(if (ch == NUL) '.' else ch))
            if (ch == NUL) {
                countEmpty++
            }
            else {
                if (countEmpty > 0) {
                    fen.append(countEmpty)
                    countEmpty = 0
                }
                fen.append(ch)
            }
        }
        if (countEmpty > 0) {
            fen.append(countEmpty)
            countEmpty = 0
        }
        fen.append("/")
        println()
    }
    return fen.append(" w - - 0 1").toString()
}

fun main(args: Array<String>) {
    println(createFen())
}


Generator/Exponential

A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.

Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".

Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.

;Task:
* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).
* Use it to create a generator of:
:::*   Squares.
:::*   Cubes.
* Create a new generator that filters all cubes from the generator of squares.
* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.

Note that this task ''requires'' the use of generators in the calculation of the result.

;Also see:
* Generator

Solution:
// version 1.1.0
// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning

import kotlin.coroutines.experimental.buildSequence

fun generatePowers(m: Int) =
    buildSequence {
        var n = 0
        val mm = m.toDouble()
        while (true) yield(Math.pow((n++).toDouble(), mm).toLong())
    }

fun generateNonCubicSquares(squares: Sequence<Long>, cubes: Sequence<Long>) =
    buildSequence {
        val iter2 = squares.iterator()
        val iter3 = cubes.iterator()
        var square = iter2.next()
        var cube = iter3.next()
        while (true) {
            if (square > cube) {
                cube = iter3.next()
                continue
            } else if (square < cube) {
                yield(square)
            }
            square = iter2.next()
        }
    }

fun main(args: Array<String>) {
    val squares = generatePowers(2)
    val cubes = generatePowers(3)
    val ncs = generateNonCubicSquares(squares, cubes)
    print("Non-cubic squares (21st to 30th) : ")
    ncs.drop(20).take(10).forEach { print("$it ") } // print 21st to 30th items
    println()
}


Get system command output

Task
Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.).

;Related task
*  Execute a system command

Solution:
// version 1.0.6

import java.util.Scanner

fun main(args: Array<String>) {
    val command = "cmd /c chcp"
    val p = Runtime.getRuntime().exec(command)
    val sc = Scanner(p.inputStream)
    println(sc.nextLine())
    sc.close()
}


Globally replace text in several files

Replace every occurring instance of a piece of text in a group of text files with another one.

For this task we want to replace the text   "'''Goodbye London!'''"   with   "'''Hello New York!'''"   for a list of files.

Solution:
// version 1.2.0

import java.io.File

fun main(args: Array<String>) {
    val files = arrayOf("file1.txt", "file2.txt")
    for (file in files) {
        val f = File(file)
        var text = f.readText()
        println(text)
        text = text.replace("Goodbye London!", "Hello New York!")
        f.writeText(text)
        println(f.readText())
    }
}


Gray code

Karnaugh maps in order from left to right or top to bottom.
Create functions to encode a number to and decode a number from Gray code.

Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).

There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."

Encoding (MSB is bit 0, b is binary, g is Gray code):

if b[i-1] = 1
   g[i] = not b[i]
else
   g[i] = b[i]

Or:

g = b xor (b logically right shifted 1 time)

Decoding (MSB is bit 0, b is binary, g is Gray code):

b[0] = g[0]

for other bits:
b[i] = g[i] xor b[i-1]

;Reference
* Converting Between Gray and Binary Codes. It includes step-by-step animations.

Solution:
// version 1.0.6

object Gray {
    fun encode(n: Int) = n xor (n shr 1)

    fun decode(n: Int): Int {
        var p  = n
        var nn = n
        while (nn != 0) {
            nn = nn shr 1
            p = p xor nn
        }
        return p
    }
}

fun main(args: Array<String>) {
    println("Number\tBinary\tGray\tDecoded")
    for (i in 0..31) {
        print("$i\t${Integer.toBinaryString(i)}\t")
        val g = Gray.encode(i)
        println("${Integer.toBinaryString(g)}\t${Gray.decode(g)}")
    }
}


Greatest subsequential sum

Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.

An empty subsequence is considered to have the sum of   '''0''';   thus if all elements are negative, the result must be the empty sequence.

Solution:
// version 1.1

fun gss(seq: IntArray): Triple<Int, Int, Int> {
    if (seq.isEmpty()) throw IllegalArgumentException("Array cannot be empty")
    var sum: Int
    var maxSum = seq[0]
    var first = 0
    var last = 0
    for (i in 1 until seq.size) {
        sum = 0
        for (j in i until seq.size) {
            sum += seq[j]
            if (sum > maxSum) {
                maxSum = sum
                first = i
                last = j
            }
        }
    }
    return Triple(maxSum, first, last)
}

fun main(args: Array<String>) {
  val seq = intArrayOf(-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)
  val(maxSum, first, last) = gss(seq)
  if (maxSum > 0) {
      println("Maximum subsequence is from indices $first to $last")
      print("Elements are : ")
      for (i in first .. last) print("${seq[i]} ")
      println("\nSum is $maxSum")
  }
  else
      println("Maximum subsequence is the empty sequence which has a sum of 0")
}


Greedy algorithm for Egyptian fractions

An   Egyptian fraction   is the sum of distinct unit fractions such as:

::::   \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48})

Each fraction in the expression has a numerator equal to   '''1'''   (unity)   and a denominator that is a positive integer,   and all the denominators are distinct   (i.e., no repetitions).

Fibonacci's   Greedy algorithm for Egyptian fractions   expands the fraction     \tfrac{x}{y}     to be represented by repeatedly performing the replacement

::::   \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil}

(simplifying the 2nd term in this replacement as necessary, and where     \lceil x \rceil     is the   ''ceiling''   function).

For this task,   Proper and improper fractions   must be able to be expressed.

Proper  fractions   are of the form    \tfrac{a}{b}    where    a    and    b    are positive integers, such that    a < b,     and

improper fractions are of the form    \tfrac{a}{b}    where    a    and    b    are positive integers, such that    ''a'' >= ''b''.

(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)

For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].

;Task requirements:
*   show the Egyptian fractions for:  \tfrac{43}{48}  and  \tfrac{5}{121}  and  \tfrac{2014}{59}
*   for all proper fractions,    \tfrac{a}{b}    where    a    and    b    are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:
::*   the largest number of terms,
::*   the largest denominator.
*   for all one-, two-, and three-digit integers,   find and show (as above).     {extra credit}

;Also see:
*   Wolfram MathWorld(tm) entry: Egyptian fraction

Solution:
// version 1.2.10

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

val bigZero = BigInteger.ZERO
val bigOne  = BigInteger.ONE
val bdZero  = BigDecimal.ZERO
val context = MathContext.UNLIMITED

fun gcd(a: BigInteger, b: BigInteger): BigInteger
    = if (b == bigZero) a else gcd(b, a % b)

class Frac : Comparable<Frac> {
    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 = gcd(nn, dd).abs()
        if (g > bigOne) {
            nn /= g
            dd /= g
        }
        num = nn
        denom = dd
    }

    constructor(n: Int, d: Int) : this(n.toBigInteger(), d.toBigInteger())

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

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

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

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

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

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

    fun toBigDecimal() = num.toBigDecimal() / denom.toBigDecimal()

    fun toEgyptian(): List<Frac> {
        if (num == bigZero) return listOf(this)
        val fracs = mutableListOf<Frac>()
        if (num.abs() >= denom.abs()) {
            val div = Frac(num / denom, bigOne)
            val rem = this - div
            fracs.add(div)
            toEgyptian(rem.num, rem.denom, fracs)
        }
        else {
            toEgyptian(num, denom, fracs)
        }
        return fracs
    }

    private tailrec fun toEgyptian(
        n: BigInteger,
        d: BigInteger,
        fracs: MutableList<Frac>
    ) {
        if (n == bigZero) return
        val n2 = n.toBigDecimal()
        val d2 = d.toBigDecimal()
        var divRem = d2.divideAndRemainder(n2, context)
        var div = divRem[0].toBigInteger()
        if (divRem[1] > bdZero) div++
        fracs.add(Frac(bigOne, div))
        var n3 = (-d) % n
        if (n3 < bigZero) n3 += n
        val d3 = d * div
        val f = Frac(n3, d3)
        if (f.num == bigOne) {
            fracs.add(f)
            return
        }
        toEgyptian(f.num, f.denom, fracs)
    }
}

fun main(args: Array<String>) {
    val fracs = listOf(Frac(43, 48), Frac(5, 121), Frac(2014,59))
    for (frac in fracs) {
        val list = frac.toEgyptian()
        if (list[0].denom == bigOne) {
            val first = "[${list[0]}]"
            println("$frac -> $first + ${list.drop(1).joinToString(" + ")}")
        }
        else {
            println("$frac -> ${list.joinToString(" + ")}")
        }
    }

    for (r in listOf(98, 998)) {
        if (r == 98)
            println("\nFor proper fractions with 1 or 2 digits:")
        else
            println("\nFor proper fractions with 1, 2 or 3 digits:")
        var maxSize = 0
        var maxSizeFracs = mutableListOf<Frac>()
        var maxDen = bigZero
        var maxDenFracs = mutableListOf<Frac>()
        val sieve = List(r + 1) { BooleanArray(r + 2) }  // to eliminate duplicates
        for (i in 1..r) {
            for (j in (i + 1)..(r + 1)) {
                if (sieve[i][j]) continue
                val f = Frac(i, j)
                val list = f.toEgyptian()
                val listSize = list.size
                if (listSize > maxSize) {
                    maxSize = listSize
                    maxSizeFracs.clear()
                    maxSizeFracs.add(f)
                }
                else if (listSize == maxSize) {
                    maxSizeFracs.add(f)
                }
                val listDen = list[list.lastIndex].denom
                if (listDen > maxDen) {
                    maxDen = listDen
                    maxDenFracs.clear()
                    maxDenFracs.add(f)
                }
                else if (listDen == maxDen) {
                    maxDenFracs.add(f)
                }
                if (i < r / 2) {
                   var k = 2
                   while (true) {
                       if (j * k > r + 1) break
                       sieve[i * k][j * k] = true
                       k++
                   }
                }
            }
        }
        println("  largest number of items = $maxSize")
        println("  fraction(s) with this number : $maxSizeFracs")
        val md = maxDen.toString()
        print("  largest denominator = ${md.length} digits, ")
        println("${md.take(20)}...${md.takeLast(20)}")
        println("  fraction(s) with this denominator : $maxDenFracs")
    }
}


Greyscale bars/Display

The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display.

For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)

For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).

Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.

Solution:
// version 1.1

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

class GreyBars : JFrame("grey bars example!") {
    private val w: Int
    private val h: Int

    init {
        w = 640
        h = 320
        setSize(w, h)
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }

    override fun paint(g: Graphics) {
        var run = 0
        var colorComp: Double  // component of the color
        var columnCount = 8
        while (columnCount < 128) {
            var colorGap = 255.0 / (columnCount - 1) // by this gap we change the background color
            val columnWidth = w / columnCount
            val columnHeight = h / 4
            if (run % 2 == 0)  // switches color directions with each iteration of while loop
                colorComp = 0.0
            else {
                colorComp = 255.0
                colorGap *= -1.0
            }
            val ystart = columnHeight * run
            var xstart = 0
            for (i in 0 until columnCount) {
                val iColor = Math.round(colorComp).toInt()
                val nextColor = Color(iColor, iColor, iColor)
                g.color = nextColor
                g.fillRect(xstart, ystart, columnWidth, columnHeight)
                xstart += columnWidth
	        colorComp += colorGap
	    }
            run++
            columnCount *= 2
        }
    }
}

fun main(args: Array<String>) {
    GreyBars()
}


Hailstone sequence

The Hailstone sequence of numbers can be generated from a starting positive integer,   n   by:
*   If   n   is     '''1'''     then the sequence ends.
*   If   n   is   '''even''' then the next   n   of the sequence    = n/2
*   If   n   is   '''odd'''    then the next   n   of the sequence    = (3 * n) + 1

The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.

This sequence was named by Lothar Collatz in 1937   (or possibly in 1939),   and is also known as (the):
:::*   hailstone sequence,   hailstone numbers
:::*   3x + 2 mapping,   3n + 1 problem
:::*   Collatz sequence
:::*   Hasse's algorithm
:::*   Kakutani's problem
:::*   Syracuse algorithm,   Syracuse problem
:::*   Thwaites conjecture
:::*   Ulam's problem

The hailstone sequence is also known as   ''hailstone numbers''   (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).

;Task:
# Create a routine to generate the hailstone sequence for a number.
# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.    (But don't show the actual sequence!)

;See also:
*   xkcd (humourous).
*   The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).
*   The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).

Solution:
import java.util.ArrayDeque

fun hailstone(n: Int): ArrayDeque<Int> {
    val hails = when {
        n == 1 -> ArrayDeque<Int>()
        n % 2 == 0 -> hailstone(n / 2)
        else -> hailstone(3 * n + 1)
    }
    hails.addFirst(n)
    return hails
}

fun main(args: Array<String>) {
    val hail27 = hailstone(27)
    fun showSeq(s: List<Int>) = s.map { it.toString() }.reduce { a, b -> a + ", " + b }
    println("Hailstone sequence for 27 is " + showSeq(hail27.take(3)) + " ... "
            + showSeq(hail27.drop(hail27.size - 3)) + " with length ${hail27.size}.")

    var longestHail = hailstone(1)
    for (x in 1..99999)
        longestHail = arrayOf(hailstone(x), longestHail).maxBy { it.size } ?: longestHail
    println("${longestHail.first} is the number less than 100000 with " +
            "the longest sequence, having length ${longestHail.size}.")
}


Harshad or Niven series

The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits.

For example,   '''42'''   is a Harshad number as   '''42'''   is divisible by   ('''4''' + '''2''')   without remainder.

Assume that the series is defined as the numbers in increasing order.

;Task:
The task is to create a function/method/procedure to generate successive members of the Harshad sequence.

Use it to:
::*   list the first '''20''' members of the sequence,   and
::*   list the first Harshad number greater than '''1000'''.

Show your output here.

;Related task
:*   Increasing gaps between consecutive Niven numbers

;See also
*    OEIS: A005349

Solution:
// version 1.1

fun sumDigits(n: Int): Int = when {
        n <= 0 -> 0
        else   -> {
            var sum = 0
            var nn = n
            while (nn > 0) {
                sum += nn % 10
                nn /= 10
            }
            sum
        }
    }

fun isHarshad(n: Int): Boolean = (n % sumDigits(n) == 0)

fun main(args: Array<String>) {
    println("The first 20 Harshad numbers are:")
    var count = 0
    var i = 0

    while (true) {
        if (isHarshad(++i)) {
            print("$i ")
            if (++count == 20) break
        }
    }

    println("\n\nThe first Harshad number above 1000 is:")
    i = 1000

    while (true) {
        if (isHarshad(++i)) {
            println(i)
            return
        }
    }
}