Kosaraju

{{wikipedia|Graph}}

Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.

For this task consider the directed graph with these connections:
  0 -> 1
  1 -> 2
  2 -> 0
  3 -> 1,  3 -> 2,  3 -> 4
  4 -> 3,  4 -> 5
  5 -> 2,  5 -> 6
  6 -> 5
  7 -> 4, 7  -> 6, 7 -> 7

And report the kosaraju strongly connected component for each node.

;References:
* The article on Wikipedia.

Solution:
// version 1.1.3

/* the list index is the first vertex in the edge(s) */
val g = listOf(
    intArrayOf(1),        // 0
    intArrayOf(2),        // 1
    intArrayOf(0),        // 2
    intArrayOf(1, 2, 4),  // 3
    intArrayOf(3, 5),     // 4
    intArrayOf(2, 6),     // 5
    intArrayOf(5),        // 6
    intArrayOf(4, 6, 7)   // 7
)

fun kosaraju(g: List<IntArray>): List<List<Int>> {
    // 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
    val size = g.size
    val vis = BooleanArray(size)                 // all false by default
    val l = IntArray(size)                       // all zero by default
    var x = size                                 // index for filling l in reverse order
    val t = List(size) { mutableListOf<Int>() }  // transpose graph

    // Recursive subroutine 'visit':
    fun visit(u: Int) {
        if (!vis[u]) {
            vis[u] = true
            for (v in g[u]) {
                visit(v)
                t[v].add(u)  // construct transpose
            }
            l[--x] = u
        }
     }

    // 2. For each vertex u of the graph do visit(u)
    for (u in g.indices) visit(u)
    val c = IntArray(size)  // used for component assignment

    // Recursive subroutine 'assign':
    fun assign(u: Int, root: Int) {
        if (vis[u]) {  // repurpose vis to mean 'unassigned'
            vis[u] = false
            c[u] = root
            for (v in t[u]) assign(v, root)
        }
    }

    // 3: For each element u of l in order, do assign(u, u)
    for (u in l) assign(u, u)

    // Obtain list of SCC's from 'c' and return it
    return c.withIndex()
            .groupBy { it.value }.values
            .map { ivl -> ivl.map { it.index } }
}

fun main(args: Array<String>) {
    println(kosaraju(g).joinToString("\n"))
}


Lah numbers

Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.

Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.

Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.

Lah numbers obey the identities and relations:
   L(n, 0), L(0, k) = 0   # for n, k > 0
   L(n, n) = 1
   L(n, 1) = n!
   L(n, k) =           ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For unsigned Lah numbers
      ''or''
   L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)!      # For   signed Lah numbers

;Task:
:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.

:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).

:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.

;See also:

:* '''Wikipedia - Lah number'''
:* '''OEIS:A105278 - Unsigned Lah numbers'''
:* '''OEIS:A008297 - Signed Lah numbers'''

;Related Tasks:

:* '''Stirling numbers of the first kind'''
:* '''Stirling numbers of the second kind'''
:* '''Bell numbers'''

Solution:
import java.math.BigInteger

fun factorial(n: BigInteger): BigInteger {
    if (n == BigInteger.ZERO) return BigInteger.ONE
    if (n == BigInteger.ONE) return BigInteger.ONE
    var prod = BigInteger.ONE
    var num = n
    while (num > BigInteger.ONE) {
        prod *= num
        num--
    }
    return prod
}

fun lah(n: BigInteger, k: BigInteger): BigInteger {
    if (k == BigInteger.ONE) return factorial(n)
    if (k == n) return BigInteger.ONE
    if (k > n) return BigInteger.ZERO
    if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO
    return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k)
}

fun main() {
    println("Unsigned Lah numbers: L(n, k):")
    print("n/k ")
    for (i in 0..12) {
        print("%10d ".format(i))
    }
    println()
    for (row in 0..12) {
        print("%-3d".format(row))
        for (i in 0..row) {
            val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong()))
            print("%11d".format(l))
        }
        println()
    }
    println("\nMaximum value from the L(100, *) row:")
    println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max())
}


Largest int from concatenated ints

Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.

Use the following two sets of integers as tests   and   show your program output here.

:::::*   {1, 34, 3, 98, 9, 76, 45, 4}
:::::*   {54, 546, 548, 60}

;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.
# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.

;See also:
*   Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
*   Constructing the largest number possible by rearranging a list

Solution:
import kotlin.Comparator

fun main(args: Array<String>) {
    val comparator = Comparator<Int> { x, y -> "$x$y".compareTo("$y$x") }

    fun findLargestSequence(array: IntArray): String {
        return array.sortedWith(comparator.reversed()).joinToString("") { it.toString() }
    }

    for (array in listOf(
        intArrayOf(1, 34, 3, 98, 9, 76, 45, 4),
        intArrayOf(54, 546, 548, 60),
    )) {
        println("%s -> %s".format(array.contentToString(), findLargestSequence(array)))
    }
}


Largest number divisible by its digits

Find the largest base 10 integer whose digits are all different,   and   is evenly divisible by each of its individual digits.

These numbers are also known as   '''Lynch-Bell numbers''',   numbers   '''n'''   such that the
(base ten) digits are all different (and do not include zero)   and   '''n'''   is divisible by each of its individual digits.

;Example:
'''135'''   is evenly divisible by   '''1''',   '''3''',   and   '''5'''.

Note that the digit zero (0) can not be in the number as integer division by zero is undefined.

The digits must all be unique so a base ten number will have at most '''9''' digits.

Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)

;Stretch goal:
Do the same thing for hexadecimal.

;Related tasks:
:*   gapful numbers.
:*   palindromic gapful numbers.

;Also see:
:*   The OEIS sequence:   A115569: Lynch-Bell numbers.

Solution:
// version 1.1.4-3

fun Int.divByAll(digits: List<Char>) = digits.all { this % (it - '0') == 0 }

fun main(args: Array<String>) {
    val magic = 9 * 8 * 7
    val high = 9876432 / magic * magic
    for (i in high downTo magic step magic) {
        if (i % 10 == 0) continue            // can't end in '0'
        val s = i.toString()
        if ('0' in s || '5' in s) continue   // can't contain '0' or '5'
        val sd = s.toCharArray().distinct()
        if (sd.size != s.length) continue    // digits must be unique
        if (i.divByAll(sd)) {
            println("Largest decimal number is $i")
            return
        }
    }
}


Last Friday of each month

Write a program or a script that returns the date of the last Fridays 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_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28

;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday 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 Fridays 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)
        var offset = calendar[Calendar.DAY_OF_WEEK] - Calendar.FRIDAY
        if (offset < 0) offset += 7
        val lastFriday = daysInMonth - offset
        println("$year-" + "%02d-".format(month) + "%02d".format(lastFriday))
        if (month < 12) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
            calendar.add(Calendar.MONTH, 1)
            calendar.add(Calendar.DAY_OF_MONTH, -1)
        }
    }
}


Last letter-first letter

A certain children's game involves starting with a word in a particular category.   Each participant in turn says a word, but that word must begin with the final letter of the previous word.   Once a word has been given, it cannot be repeated.   If an opponent cannot give a word in the category, they fall out of the game.

For example, with   "animals"   as the category,

Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...

;Task:
Take the following selection of 70 English Pokemon names   (extracted from   Wikipedia's list of Pokemon)   and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.

No Pokemon name is to be repeated.

audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask

Extra brownie points for dealing with the full list of   646   names.

Solution:
// version 1.1.2

var maxPathLength = 0
var maxPathLengthCount = 0
val maxPathExample = StringBuilder(500)

val names = arrayOf(
    "audino", "bagon", "baltoy", "banette", "bidoof",
    "braviary", "bronzor", "carracosta", "charmeleon", "cresselia",
    "croagunk", "darmanitan", "deino", "emboar", "emolga",
    "exeggcute", "gabite", "girafarig", "gulpin", "haxorus",
    "heatmor", "heatran", "ivysaur", "jellicent", "jumpluff",
    "kangaskhan", "kricketune", "landorus", "ledyba", "loudred",
    "lumineon", "lunatone", "machamp", "magnezone", "mamoswine",
    "nosepass", "petilil", "pidgeotto", "pikachu", "pinsir",
    "poliwrath", "poochyena", "porygon2", "porygonz", "registeel",
    "relicanth", "remoraid", "rufflet", "sableye", "scolipede",
    "scrafty", "seaking", "sealeo", "silcoon", "simisear",
    "snivy", "snorlax", "spoink", "starly", "tirtouga",
    "trapinch", "treecko", "tyrogue", "vigoroth", "vulpix",
    "wailord", "wartortle", "whismur", "wingull", "yamask"
)

fun search(part: Array<String>, offset: Int) {
    if (offset > maxPathLength) {
        maxPathLength = offset
        maxPathLengthCount = 1
    }
    else if (offset == maxPathLength) {
        maxPathLengthCount++
        maxPathExample.setLength(0)
        for (i in 0 until offset) {
            maxPathExample.append(if (i % 5 == 0) "\n  " else " ")
            maxPathExample.append(part[i])
        }
    }
    val lastChar = part[offset - 1].last()
    for (i in offset until part.size) {
        if (part[i][0] == lastChar) {
            val tmp = names[offset]
            names[offset] = names[i]
            names[i] = tmp
            search(names, offset + 1)
            names[i] = names[offset]
            names[offset] = tmp
        }
    }
}

fun main(args: Array<String>) {
    for (i in 0 until names.size) {
        val tmp = names[0]
        names[0] = names[i]
        names[i] = tmp
        search(names, 1)
        names[i] = names[0]
        names[0] = tmp
    }
    println("Maximum path length         : $maxPathLength")
    println("Paths of that length        : $maxPathLengthCount")
    println("Example path of that length : $maxPathExample")
}


Latin Squares in reduced form

A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.

For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.

Demonstrate by:
* displaying the four reduced Latin Squares of order 4.
* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.

Solution:
typealias Matrix = MutableList<MutableList<Int>>

fun dList(n: Int, sp: Int): Matrix {
    val start = sp - 1 // use 0 basing

    val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
    a[start] = a[0].also { a[0] = a[start] }
    a.subList(1, a.size).sort()

    val first = a[1]
    // recursive closure permutes a[1:]
    val r = mutableListOf<MutableList<Int>>()
    fun recurse(last: Int) {
        if (last == first) {
            // bottom of recursion. you get here once for each permutation.
            // test if permutation is deranged
            for (jv in a.subList(1, a.size).withIndex()) {
                if (jv.index + 1 == jv.value) {
                    return  // no, ignore it
                }
            }
            // yes, save a copy with 1 based indexing
            val b = a.map { it + 1 }
            r.add(b.toMutableList())
            return
        }
        for (i in last.downTo(1)) {
            a[i] = a[last].also { a[last] = a[i] }
            recurse(last - 1)
            a[i] = a[last].also { a[last] = a[i] }
        }
    }
    recurse(n - 1)
    return r
}

fun reducedLatinSquares(n: Int, echo: Boolean): Long {
    if (n <= 0) {
        if (echo) {
            println("[]\n")
        }
        return 0
    } else if (n == 1) {
        if (echo) {
            println("[1]\n")
        }
        return 1
    }

    val rlatin = MutableList(n) { MutableList(n) { it } }
    // first row
    for (j in 0 until n) {
        rlatin[0][j] = j + 1
    }

    var count = 0L
    fun recurse(i: Int) {
        val rows = dList(n, i)

        outer@
        for (r in 0 until rows.size) {
            rlatin[i - 1] = rows[r].toMutableList()
            for (k in 0 until i - 1) {
                for (j in 1 until n) {
                    if (rlatin[k][j] == rlatin[i - 1][j]) {
                        if (r < rows.size - 1) {
                            continue@outer
                        }
                        if (i > 2) {
                            return
                        }
                    }
                }
            }
            if (i < n) {
                recurse(i + 1)
            } else {
                count++
                if (echo) {
                    printSquare(rlatin)
                }
            }
        }
    }

    // remaining rows
    recurse(2)
    return count
}

fun printSquare(latin: Matrix) {
    for (row in latin) {
        println(row)
    }
    println()
}

fun factorial(n: Long): Long {
    if (n == 0L) {
        return 1
    }
    var prod = 1L
    for (i in 2..n) {
        prod *= i
    }
    return prod
}

fun main() {
    println("The four reduced latin squares of order 4 are:\n")
    reducedLatinSquares(4, true)

    println("The size of the set of reduced latin squares for the following orders")
    println("and hence the total number of latin squares of these orders are:\n")
    for (n in 1 until 7) {
        val size = reducedLatinSquares(n, false)
        var f = factorial(n - 1.toLong())
        f *= f * n * size
        println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size))
    }
}


Law of cosines - triples

The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
           A2 + B2 - 2ABcos(g) = C2

;Specific angles:
For an angle of of   '''90o'''   this becomes the more familiar "Pythagoras equation":
           A2 + B2  =  C2

For an angle of   '''60o'''   this becomes the less familiar  equation:
           A2 + B2 - AB  =  C2

And finally for an angle of   '''120o'''   this becomes the equation:
           A2 + B2 + AB  =  C2

;Task:
*   Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
*   Restrain all sides to the integers   '''1..13'''   inclusive.
*   Show how many results there are for each of the three angles mentioned above.
*   Display results on this page.

Note: Triangles with the same length sides but different order are to be treated as the same.

;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.

;Related Task
* [[Pythagorean triples]]

;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video

Solution:
// Version 1.2.70

val squares13 = mutableMapOf<Int, Int>()
val squares10000 = mutableMapOf<Int, Int>()

class Trio(val a: Int, val b: Int, val c: Int) {
    override fun toString() = "($a $b $c)"
}

fun init() {
    for (i in 1..13) squares13.put(i * i, i)
    for (i in 1..10000) squares10000.put(i * i, i)
}

fun solve(angle :Int, maxLen: Int, allowSame: Boolean): List<Trio> {
    val solutions = mutableListOf<Trio>()
    for (a in 1..maxLen) {
        inner@ for (b in a..maxLen) {
            var lhs = a * a + b * b
            if (angle != 90) {
                when (angle) {
                    60   -> lhs -= a * b
                    120  -> lhs += a * b
                    else -> throw RuntimeException("Angle must be 60, 90 or 120 degrees")
                }
            }
            when (maxLen) {
                13 -> {
                    val c = squares13[lhs]
                    if (c != null) {
                        if (!allowSame && a == b && b == c) continue@inner
                        solutions.add(Trio(a, b, c))
                    }
                }

                10000 -> {
                    val c = squares10000[lhs]
                    if (c != null) {
                        if (!allowSame && a == b && b == c) continue@inner
                        solutions.add(Trio(a, b, c))
                    }
                }

                else -> throw RuntimeException("Maximum length must be either 13 or 10000")
            }
        }
    }
    return solutions
}

fun main(args: Array<String>) {
    init()
    print("For sides in the range [1, 13] ")
    println("where they can all be of the same length:-\n")
    val angles = intArrayOf(90, 60, 120)
    lateinit var solutions: List<Trio>
    for (angle in angles) {
        solutions = solve(angle, 13, true)
        print("  For an angle of ${angle} degrees")
        println(" there are ${solutions.size} solutions, namely:")
        println("  ${solutions.joinToString(" ", "[", "]")}\n")
    }
    print("For sides in the range [1, 10000] ")
    println("where they cannot ALL be of the same length:-\n")
    solutions = solve(60, 10000, false)
    print("  For an angle of 60 degrees")
    println(" there are ${solutions.size} solutions.")
}


Least common multiple

Compute the   least common multiple   (LCM)   of two integers.

Given   ''m''   and   ''n'',   the least common multiple is the smallest positive integer that has both   ''m''   and   ''n''   as factors.

;Example:
The least common multiple of   '''12'''   and   '''18'''   is   '''36''',       because:
:*   '''12'''   is a factor     ('''12''' x '''3''' = '''36'''),     and
:*   '''18'''   is a factor     ('''18''' x '''2''' = '''36'''),     and
:*   there is no positive integer less than   '''36'''   that has both factors.

As a special case,   if either   ''m''   or   ''n''   is zero,   then the least common multiple is zero.

One way to calculate the least common multiple is to iterate all the multiples of   ''m'',   until you find one that is also a multiple of   ''n''.

If you already have   ''gcd''   for [[greatest common divisor]],   then this formula calculates   ''lcm''.

:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}

One can also find   ''lcm''   by merging the [[prime decomposition]]s of both   ''m''   and   ''n''.

;Related task
:*   greatest common divisor.

;See also:
*   MathWorld entry:   Least Common Multiple.
*   Wikipedia entry:   Least common multiple.

Solution:
fun main(args: Array<String>) {
    fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
    fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
    println(lcm(15, 9))
}


Left factorials

'''Left factorials''',   !n,   may refer to either   ''subfactorials''   or to   ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.

Sometimes,   ''subfactorials''   (also known as ''derangements'')   may use any of the notations:
:::::::*     !''n''`
:::::::*     !''n''
:::::::*     ''n''!

(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)

This Rosetta Code task will be using this formula   (''factorial sums'')   for   '''left factorial''':

:::::    !n = \sum_{k=0}^{n-1} k!

:::: where

:::::   !0 = 0

;Task
Display the left factorials for:
*   zero      through        ten     (inclusive)
*   20   through   110          (inclusive)   by tens

Display the length (in decimal digits) of the left factorials for:
*   1,000   through   10,000   (inclusive), by thousands.

;Also see:
*   The OEIS entry: A003422 left factorials
*   The MathWorld entry: left factorial
*   The MathWorld entry: factorial sums
*   The MathWorld entry: subfactorial

;Related task:
*   permutations/derangements (subfactorials)

Solution:
// version 1.0.6

import java.math.BigInteger

fun leftFactorial(n: Int): BigInteger {
    if (n == 0) return BigInteger.ZERO
    var fact = BigInteger.ONE
    var sum = fact
    for (i in 1 until n) {
        fact *= BigInteger.valueOf(i.toLong())
        sum += fact
    }
    return sum
}

fun main(args: Array<String>) {
    for (i in 0..110)
        if (i <= 10 || (i % 10) == 0)
            println("!${i.toString().padEnd(3)} = ${leftFactorial(i)}")
    println("\nLength of the following left factorials:")
    for (i in 1000..10000 step 1000)
        println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits")
}


Levenshtein distance

{{Wikipedia}}

In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.

;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::#   '''k'''itten    '''s'''itten       (substitution of 'k' with 's')
::#   sitt'''e'''n    sitt'''i'''n       (substitution of 'e' with 'i')
::#   sittin          sittin'''g'''      (insert 'g' at the end).

''The Levenshtein distance between   "'''rosettacode'''",   "'''raisethysword'''"   is   '''8'''.

''The distance between two strings is same as that when both strings are reversed.''

;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between   "kitten"   and   "sitting".

;Related task:
*   [[Longest common subsequence]]

Solution:
// version 1.0.6

// Uses the "iterative with two matrix rows" algorithm referred to in the Wikipedia article.

fun levenshtein(s: String, t: String): Int {
    // degenerate cases
    if (s == t)  return 0
    if (s == "") return t.length
    if (t == "") return s.length

    // create two integer arrays of distances and initialize the first one
    val v0 = IntArray(t.length + 1) { it }  // previous
    val v1 = IntArray(t.length + 1)         // current

    var cost: Int
    for (i in 0 until s.length) {
        // calculate v1 from v0
        v1[0] = i + 1
        for (j in 0 until t.length) {
            cost = if (s[i] == t[j]) 0 else 1
            v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost))
        }
        // copy v1 to v0 for next iteration
        for (j in 0 .. t.length) v0[j] = v1[j]
    }
    return v1[t.length]
}

fun main(args: Array<String>) {
    println("'kitten' to 'sitting'            => ${levenshtein("kitten", "sitting")}")
    println("'rosettacode' to 'raisethysword' => ${levenshtein("rosettacode", "raisethysword")}")
    println("'sleep' to 'fleeting'            => ${levenshtein("sleep", "fleeting")}")
}


Levenshtein distance/Alignment

The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.

An alignment is a notation used to describe the operations used to turn a string into an other.  At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place.  For instance, an alignment between the words 'place' and 'palace' is:

P-LACE
PALACE

;Task:
Write a function that shows the alignment of two strings for the corresponding levenshtein distance.

As an example, use the words "rosettacode" and "raisethysword".

You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).

Solution:
// version 1.1.3

fun levenshteinAlign(a: String, b: String): Array<String> {
    val aa = a.toLowerCase()
    val bb = b.toLowerCase()
    val costs = Array(a.length + 1) { IntArray(b.length + 1) }
    for (j in 0..b.length) costs[0][j] = j
    for (i in 1..a.length) {
        costs[i][0] = i
        for (j in 1..b.length) {
            val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1)
            costs[i][j] = minOf(1 + minOf(costs[i - 1][j], costs[i][j - 1]), temp)
        }
    }

    // walk back through matrix to figure out path
    val aPathRev = StringBuilder()
    val bPathRev = StringBuilder()
    var i = a.length
    var j = b.length
    while (i != 0 && j != 0) {
        val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1)
        when (costs[i][j]) {
            temp -> {
                aPathRev.append(aa[--i])
                bPathRev.append(bb[--j])
            }

            1 + costs[i-1][j] -> {
                aPathRev.append(aa[--i])
                bPathRev.append('-')
            }

            1 + costs[i][j-1] -> {
                aPathRev.append('-')
                bPathRev.append(bb[--j])
            }
        }
    }
    return arrayOf(aPathRev.reverse().toString(), bPathRev.reverse().toString())
}

fun main(args: Array<String>) {
    var result = levenshteinAlign("place", "palace")
    println(result[0])
    println(result[1])
    println()
    result = levenshteinAlign("rosettacode","raisethysword")
    println(result[0])
    println(result[1])
}


List rooted trees

You came back from grocery shopping.    After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink.   In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.

If we use a matching pair of parentheses to represent a bag, the ways are:

For 1 bag, there's one way:
  ()	<- a bag

for 2 bags, there's one way:
  (())	<- one bag in another

for 3 bags, there are two:
  ((())) <- 3 bags nested Russian doll style
  (()()) <- 2 bags side by side, inside the third

for 4 bags, four:
  (()()())
  ((())())
  ((()()))
  (((())))

Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.

It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree.  The outermost bag is the tree root.  Number of configurations for given ''n'' is given by OEIS A81.

;Task:
Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags.   You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.

This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.

As an example output, run 5 bags.   There should be 9 ways.

Solution:
// version 1.1.3

typealias Tree = Long

val treeList = mutableListOf<Tree>()
val offset = IntArray(32) { if (it == 1) 1 else 0 }

fun append(t: Tree) {
    treeList.add(1L or (t shl 1))
}

fun show(t: Tree, l: Int) {
    var tt = t
    var ll = l
    while (ll-- > 0) {
        print(if (tt % 2L == 1L) "(" else ")")
        tt = tt ushr 1
    }
}

fun listTrees(n: Int) {
    for (i in offset[n] until offset[n + 1]) {
        show(treeList[i], n * 2)
        println()
    }
}

/* assemble tree from subtrees
	n:   length of tree we want to make
	t:   assembled parts so far
	sl:  length of subtree we are looking at
	pos: offset of subtree we are looking at
	rem: remaining length to be put together
*/

fun assemble(n: Int, t: Tree, sl: Int, pos: Int, rem: Int) {
    if (rem == 0) {
        append(t)
        return
    }

    var pp = pos
    var ss = sl

    if (sl > rem) { // need smaller subtrees
        ss = rem
        pp = offset[ss]
    }
    else if (pp >= offset[ss + 1]) {
        // used up sl-trees, try smaller ones
        ss--
        if(ss == 0) return
        pp = offset[ss]
    }

    assemble(n, (t shl (2 * ss)) or treeList[pp], ss, pp, rem - ss)
    assemble(n, t, ss, pp + 1, rem)
}

fun makeTrees(n: Int) {
    if (offset[n + 1] != 0) return
    if (n > 0) makeTrees(n - 1)
    assemble(n, 0, n - 1, offset[n - 1], n - 1)
    offset[n + 1] = treeList.size
}

fun main(args: Array<String>) {
    if (args.size != 1) {
        throw IllegalArgumentException("There must be exactly 1 command line argument")
    }
    val n = args[0].toIntOrNull()
    if (n == null) throw IllegalArgumentException("Argument is not a valid number")
    // n limited to 12 to avoid overflowing default stack
    if (n !in 1..12) throw IllegalArgumentException("Argument must be between 1 and 12")

    // init 1-tree
    append(0)

    makeTrees(n)
    println("Number of $n-trees: ${offset[n + 1] - offset[n]}")
    listTrees(n)
}


Long literals, with continuations

This task is about writing a computer program that has long literals   (character
literals that may require specifying the words/tokens on more than one (source)
line,   either with continuations or some other method, such as abutments or
concatenations   (or some other mechanisms).

The literal is to be in the form of a "list",    a literal that contains many
words (tokens) separated by a blank (space),   in this case   (so as to have a
common list),   the (English) names of the chemical elements of the periodic table.

The list is to be in (ascending) order of the (chemical) element's atomic number:

 ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''

... up to the last known (named) chemical element   (at this time).

Do not include any of the   "unnamed"   chemical element names such as:

 ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''

To make computer programming languages comparable,   the statement widths should be
restricted to less than   '''81'''   bytes (characters),   or less
if a computer programming language has more restrictive limitations or standards.

Also mention what column the programming statements can start in if   ''not''
in column one.

The list   ''may''   have leading/embedded/trailing blanks during the
declaration   (the actual program statements),   this is allow the list to be
more readable.   The "final" list shouldn't have any leading/trailing or superfluous
blanks   (when stored in the program's "memory").

This list should be written with the idea in mind that the
program   ''will''   be updated,   most likely someone other than the
original author,   as there will be newer (discovered) elements of the periodic
table being added   (possibly in the near future).   These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list   (within the computer
program).

Attention should be paid so as to not exceed the   ''clause length''   of
continued or specified statements,   if there is such a restriction.   If the
limit is greater than (say) 4,000 bytes or so,   it needn't be mentioned here.

;Task:
:*   Write a computer program (by whatever name) to contain a list of the known elements.
:*   The program should eventually contain a long literal of words   (the elements).
:*   The literal should show how one could create a long list of blank-delineated words.
:*   The "final" (stored) list should only have a single blank between elements.
:*   Try to use the most idiomatic approach(es) in creating the final list.
:*   Use continuation if possible, and/or show alternatives   (possibly using concatenation).
:*   Use a program comment to explain what the continuation character is if it isn't obvious.
:*   The program should contain a variable that has the date of the last update/revision.
:*   The program, when run, should display with verbiage:
:::*   The last update/revision date   (and should be unambiguous).
:::*   The number of chemical elements in the list.
:::*   The name of the highest (last) element name.

Show all output here, on this page.

Solution:
import java.time.Instant

const val elementsChunk = """
hydrogen     helium        lithium      beryllium
boron        carbon        nitrogen     oxygen
fluorine     neon          sodium       magnesium
aluminum     silicon       phosphorous  sulfur
chlorine     argon         potassium    calcium
scandium     titanium      vanadium     chromium
manganese    iron          cobalt       nickel
copper       zinc          gallium      germanium
arsenic      selenium      bromine      krypton
rubidium     strontium     yttrium      zirconium
niobium      molybdenum    technetium   ruthenium
rhodium      palladium     silver       cadmium
indium       tin           antimony     tellurium
iodine       xenon         cesium       barium
lanthanum    cerium        praseodymium neodymium
promethium   samarium      europium     gadolinium
terbium      dysprosium    holmium      erbium
thulium      ytterbium     lutetium     hafnium
tantalum     tungsten      rhenium      osmium
iridium      platinum      gold         mercury
thallium     lead          bismuth      polonium
astatine     radon         francium     radium
actinium     thorium       protactinium uranium
neptunium    plutonium     americium    curium
berkelium    californium   einsteinium  fermium
mendelevium  nobelium      lawrencium   rutherfordium
dubnium      seaborgium    bohrium      hassium
meitnerium   darmstadtium  roentgenium  copernicium
nihonium     flerovium     moscovium    livermorium
tennessine   oganesson
"""

const val unamedElementsChunk = """
ununennium unquadnilium triunhexium penthextrium
penthexpentium septhexunium octenntrium ennennbium
"""

fun main() {
    fun String.splitToList() = trim().split("\\s+".toRegex());
    val elementsList =
        elementsChunk.splitToList()
            .filterNot(unamedElementsChunk.splitToList().toSet()::contains)
    println("Last revision Date:  ${Instant.now()}")
    println("Number of elements:  ${elementsList.size}")
    println("Last element      :  ${elementsList.last()}")
    println("The elements are  :  ${elementsList.joinToString(" ", limit = 5)}")
}


Long year

Most years have 52 weeks, some have 53, according to ISO8601.

;Task:
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.

Solution:
fun main() {
    val has53Weeks = { year: Int -> LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53 }
    println("Long years this century:")
    (2000..2100).filter(has53Weeks)
        .forEach { year -> print("$year ")}
}


Longest common subsequence

'''Introduction'''

Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.

The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.

Let ''A''  ''A''[0]... ''A''[m - 1] and ''B''  ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.

An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.

The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j)  '''M'''.

Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2.  We define (>=) similarly.

We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds.  If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.

Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2.  We define (>) similarly.

A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2.  An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.

A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].

Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''.  Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.

According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed.  Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.

'''Background'''

Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth.  This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.

The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n'').  However, this approach requires O(''m*n'') time even in the best case.

This quadratic time dependency may become prohibitive, given very long input strings.  Thus, heuristics are often favored over optimal Dynamic Programming solutions.

In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS.  In this case the number of matches reduces to linear, O(''n'') growth.

A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m'').  Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').

'''Note'''

[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').

'''Legend'''

 A, B are input strings of lengths m, n respectively
 p is the length of the LCS
 M is the set of matches (i, j) such that A[i] = B[j]
 r is the magnitude of M
 s is the magnitude of the alphabet S of distinct symbols in A + B

'''References'''

[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]

[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]

[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]

[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41

[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]

[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]

'''Examples'''

The sequences "1234" and "1224533324" have an LCS of "1234":
 '''1234'''
 '''12'''245'''3'''332'''4'''

For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
 '''t'''hi'''si'''sa'''test'''
 '''t'''e'''s'''t'''i'''ng123'''test'''ing

In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.

For more information on this problem please see Wikipedia.

Solution:
// version 1.1.2

fun lcs(x: String, y: String): String {
    if (x.length == 0 || y.length == 0) return ""
    val x1 = x.dropLast(1)
    val y1 = y.dropLast(1)
    if (x.last() == y.last()) return lcs(x1, y1) + x.last()
    val x2 = lcs(x, y1)
    val y2 = lcs(x1, y)
    return if (x2.length > y2.length) x2 else y2
}

fun main(args: Array<String>) {
    val x = "thisisatest"
    val y = "testing123testing"
    println(lcs(x, y))
}


Longest common substring

Write a function that returns the longest common substring of two strings.

Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".

Note that substrings are consecutive characters within a string.   This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.

Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test".

;References:
*Generalize Suffix Tree
*[[Ukkonen's Suffix Tree Construction]]

Solution:
// version 1.1.2

fun lcs(a: String, b: String): String {
    if (a.length > b.length) return lcs(b, a)
    var res = ""
    for (ai in 0 until a.length) {
        for (len in a.length - ai downTo 1) {
            for (bi in 0 until b.length - len) {
                if (a.regionMatches(ai, b, bi,len) && len > res.length) {
                    res = a.substring(ai, ai + len)
                }
            }
        }
    }
    return res
}

fun main(args: Array<String>) = println(lcs("testing123testing", "thisisatest"))


Longest increasing subsequence

Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}

Note that a list may have more than one subsequence that is of the maximum length.

;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.

Solution:
// version 1.1.0

fun longestIncreasingSubsequence(x: IntArray): IntArray =
    when (x.size) {
        0    -> IntArray(0)
        1    -> x
        else -> {
            val n = x.size
            val p = IntArray(n)
            val m = IntArray(n + 1)
            var len = 0
            for (i in 0 until n) {
                var lo = 1
                var hi = len
                while (lo <= hi) {
                    val mid = Math.ceil((lo + hi) / 2.0).toInt()
                    if (x[m[mid]] < x[i]) lo = mid + 1
                    else hi = mid - 1
                }
                val newLen = lo
                p[i] = m[newLen - 1]
                m[newLen] = i
                if (newLen > len) len = newLen
            }
            val s = IntArray(len)
            var k = m[len]
            for (i in len - 1 downTo 0) {
                s[i] = x[k]
                k = p[k]
            }
            s
        }
    }

fun main(args: Array<String>) {
    val lists = listOf(
        intArrayOf(3, 2, 6, 4, 5, 1),
        intArrayOf(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)
    )
    lists.forEach { println(longestIncreasingSubsequence(it).asList()) }
}


Lucky and even lucky numbers

Note that in the following explanation list indices are assumed to start at ''one''.

;Definition of lucky numbers
''Lucky numbers'' are positive integers that are formed by:

# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...
# Return the first number from the list (which is '''1''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''3''').
#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''7''').
#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...
#* Note then return the 4th number from the list (which is '''9''').
#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...
#* Take the 5th, i.e. '''13'''.  Remove every 13th.
#* Take the 6th, i.e. '''15'''.  Remove every 15th.
#* Take the 7th, i.e. '''21'''.  Remove every 21th.
#* Take the 8th, i.e. '''25'''.  Remove every 25th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.

;Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above ''except for the very first step'':
# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...
# Return the first number from the list (which is '''2''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''4''').
#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''6''').
#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...
#* Take the 4th, i.e. '''10'''.  Remove every 10th.
#* Take the 5th, i.e. '''12'''.  Remove every 12th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.

;Task requirements
* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers''
* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
** missing arguments
** too many arguments
** number (or numbers) aren't legal
** misspelled argument ('''lucky''' or '''evenLucky''')
* The command line handling should:
** support mixed case handling of the (non-numeric) arguments
** support printing a particular number
** support printing a range of numbers by their index
** support printing a range of numbers by their values
* The resulting list of numbers should be printed on a single line.

The program should support the arguments:

                             what is displayed  (on a single line)
       argument(s)              (optional verbiage is encouraged)
  +-------------------+----------------------------------------------------+
  |  j                |  Jth       lucky number                            |
  |  j  ,      lucky  |  Jth       lucky number                            |
  |  j  ,  evenLucky  |  Jth  even lucky number                            |
  |                   |                                                    |
  |  j  k             |  Jth  through  Kth (inclusive)       lucky numbers |
  |  j  k      lucky  |  Jth  through  Kth (inclusive)       lucky numbers |
  |  j  k  evenLucky  |  Jth  through  Kth (inclusive)  even lucky numbers |
  |                   |                                                    |
  |  j -k             |  all       lucky numbers in the range  j --> |k|   |
  |  j -k      lucky  |  all       lucky numbers in the range  j --> |k|   |
  |  j -k  evenLucky  |  all  even lucky numbers in the range  j --> |k|   |
  +-------------------+----------------------------------------------------+
                           where    |k|    is the absolute value of   k

Demonstrate the program by:
* showing the first twenty ''lucky'' numbers
* showing the first twenty ''even lucky'' numbers
* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)
* showing all ''even lucky'' numbers in the same range as above
* showing the 10,000th ''lucky'' number (extra credit)
* showing the 10,000th ''even lucky'' number (extra credit)

;See also:
* This task is related to the [[Sieve of Eratosthenes]] task.
* OEIS Wiki Lucky numbers.
* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
* Entry lucky numbers on The Eric Weisstein's World of Mathematics.

Solution:
// version 1.1.51

typealias IAE = IllegalArgumentException

val luckyOdd  = MutableList(100000) { it * 2 + 1 }
val luckyEven = MutableList(100000) { it * 2 + 2 }

fun filterLuckyOdd() {
    var n = 2
    while (n < luckyOdd.size) {
        val m = luckyOdd[n - 1]
        val end = (luckyOdd.size / m) * m - 1
        for (j in end downTo m - 1 step m) luckyOdd.removeAt(j)
        n++
    }
}

fun filterLuckyEven() {
    var n = 2
    while (n < luckyEven.size) {
        val m = luckyEven[n - 1]
        val end = (luckyEven.size / m) * m - 1
        for (j in end downTo m - 1 step m) luckyEven.removeAt(j)
        n++
    }
}

fun printSingle(j: Int, odd: Boolean) {
    if (odd) {
        if (j >= luckyOdd.size) throw IAE("Argument is too big")
        println("Lucky number $j = ${luckyOdd[j - 1]}")
    }
    else {
        if (j >= luckyEven.size) throw IAE("Argument is too big")
        println("Lucky even number $j = ${luckyEven[j - 1]}")
    }
}

fun printRange(j: Int, k: Int, odd: Boolean) {
    if (odd) {
        if (k >= luckyOdd.size) throw IAE("Argument is too big")
        println("Lucky numbers $j to $k are:\n${luckyOdd.drop(j - 1).take(k - j + 1)}")
    }
    else {
        if (k >= luckyEven.size) throw IAE("Argument is too big")
        println("Lucky even numbers $j to $k are:\n${luckyEven.drop(j - 1).take(k - j + 1)}")
    }
}

fun printBetween(j: Int, k: Int, odd: Boolean) {
    val range = mutableListOf<Int>()
    if (odd) {
        val max = luckyOdd[luckyOdd.lastIndex]
        if (j > max || k > max) {
            throw IAE("At least one argument is too big")
        }
        for (num in luckyOdd) {
            if (num < j) continue
            if (num > k) break
            range.add(num)
        }
        println("Lucky numbers between $j and $k are:\n$range")
    }
    else {
        val max = luckyEven[luckyEven.lastIndex]
        if (j > max || k > max) {
            throw IAE("At least one argument is too big")
        }
        for (num in luckyEven) {
            if (num < j) continue
            if (num > k) break
            range.add(num)
        }
        println("Lucky even numbers between $j and $k are:\n$range")
    }
}

fun main(args: Array<String>) {
    if (args.size !in 1..3) throw IAE("There must be between 1 and 3 command line arguments")
    filterLuckyOdd()
    filterLuckyEven()
    val j = args[0].toIntOrNull()
    if (j == null || j < 1) throw IAE("First argument must be a positive integer")
    if (args.size == 1) { printSingle(j, true); return }

    if (args.size == 2) {
        val k = args[1].toIntOrNull()
        if (k == null) throw IAE("Second argument must be an integer")
        if (k >= 0) {
            if (j > k) throw IAE("Second argument can't be less than first")
            printRange(j, k, true)
        }
        else {
           val l = -k
            if (j > l) throw IAE("The second argument can't be less in absolute value than first")
            printBetween(j, l, true)
        }
        return
    }

    var odd =
        if (args[2].toLowerCase() == "lucky") true
        else if (args[2].toLowerCase() == "evenlucky") false
        else throw IAE("Third argument is invalid")

    if (args[1] == ",") {
        printSingle(j, odd)
        return
    }

    val k = args[1].toIntOrNull()
    if (k == null) throw IAE("Second argument must be an integer or a comma")

    if (k >= 0) {
        if (j > k) throw IAE("Second argument can't be less than first")
        printRange(j, k, odd)
    }
    else {
        val l = -k
        if (j > l) throw IAE("The second argument can't be less in absolute value than first")
        printBetween(j, l, odd)
    }
}


Lychrel numbers

::#   Take an integer n, greater than zero.
::#   Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
::#   Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.

The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.

;Example:
If n0 = 12 we get

       12
       12 +  21 =  33,   a palindrome!

And if n0 = 55 we get

       55
       55 +  55 = 110
      110 + 011 = 121,   a palindrome!

Notice that the check for a palindrome happens   ''after''   an addition.

Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.

These numbers that do not end in a palindrome are called '''Lychrel numbers'''.

For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.

;Seed and related Lychrel numbers:
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.

In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:

        196
        196 +    691 =   887
        887 +    788 =  1675
       1675 +   5761 =  7436
       7436 +   6347 = 13783
      13783 +  38731 = 52514
      52514 +  41525 = 94039
       ...

        689
        689 +    986 =  1675
       1675 +   5761 =  7436
       ...

So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.

Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.

;Task:
*   Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
*    Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.
*    Print any seed Lychrel or related number that is itself a palindrome.

Show all output here.

;References:
*   What's special about 196? Numberphile video.
*   A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
*   Status of the 196 conjecture? Mathoverflow.

Solution:
// version 1.0.6

import java.math.BigInteger

const val ITERATIONS = 500
const val LIMIT = 10000

val bigLimit = BigInteger.valueOf(LIMIT.toLong())

// In the sieve,  0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel
val lychrelSieve    = IntArray(LIMIT + 1)  // all zero by default
val seedLychrels    = mutableListOf<Int>()
val relatedLychrels = mutableSetOf<BigInteger>()

fun isPalindrome(bi: BigInteger): Boolean {
    val s = bi.toString()
    return s == s.reversed()
}

fun lychrelTest(i: Int, seq: MutableList<BigInteger>){
    if (i < 1) return
    var bi = BigInteger.valueOf(i.toLong())
    (1 .. ITERATIONS).forEach {
        bi += BigInteger(bi.toString().reversed())
        seq.add(bi)
        if (isPalindrome(bi)) return
    }
    for (j in 0 until seq.size) {
        if (seq[j] <= bigLimit) lychrelSieve[seq[j].toInt()] = 2
        else break
    }
    val sizeBefore = relatedLychrels.size
    relatedLychrels.addAll(seq)  // if all of these can be added 'i' must be a seed Lychrel
    if (relatedLychrels.size - sizeBefore == seq.size) {
        seedLychrels.add(i)
        lychrelSieve[i] = 1
    }
    else {
        relatedLychrels.add(BigInteger.valueOf(i.toLong()))
        lychrelSieve[i] = 2
    }
}

fun main(args: Array<String>) {
    val seq  = mutableListOf<BigInteger>()
    for (i in 1 .. LIMIT)
        if (lychrelSieve[i] == 0) {
           seq.clear()
           lychrelTest(i, seq)
        }
    var related = lychrelSieve.count { it == 2 }
    println("Lychrel numbers in the range [1, $LIMIT]")
    println("Maximum iterations = $ITERATIONS")
    println("\nThere are ${seedLychrels.size} seed Lychrel numbers, namely")
    println(seedLychrels)
    println("\nThere are also $related related Lychrel numbers in this range")
    val palindromes = mutableListOf<Int>()
    for (i in 1 .. LIMIT)
        if (lychrelSieve[i] > 0 && isPalindrome(BigInteger.valueOf(i.toLong()))) palindromes.add(i)
    println("\nThere are ${palindromes.size} palindromic Lychrel numbers, namely")
    println(palindromes)
}


MAC vendor lookup

Every connected device around the world comes with a unique Media Access Control address, or a   MAC address.

A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.

;Task:
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.

A MAC address that does not return a valid result should return the String "N/A".   An error related to the network connectivity or the API should return a null result.

Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.

'''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''

Solution:
// version 1.1.2

import java.net.URL

fun lookupVendor(mac: String) = URL("http://api.macvendors.com/" + mac).readText()

fun main(args: Array<String>) {
    val macs = arrayOf("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D")
    for (mac in macs) println(lookupVendor(mac))
}


MD4

Find the MD4 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code" (without quotes).
You may either call an MD4 library, or implement MD4 in your language.

'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.

RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.

Solution:
// version 1.0.6

import java.security.MessageDigest

class MD4() : MessageDigest("MD4"), Cloneable {
    private val blockLength = 64
    private var context = IntArray(4)
    private var count = 0L
    private var buffer = ByteArray(blockLength)
    private var x = IntArray(16)

    init {
        engineReset()
    }

    private constructor(md: MD4): this() {
        context = md.context.clone()
        buffer = md.buffer.clone()
        count = md.count
    }

    override fun clone(): Any = MD4(this)

    override fun engineReset() {
        context[0] = 0x67452301
        context[1] = 0xefcdab89.toInt()
        context[2] = 0x98badcfe.toInt()
        context[3] = 0x10325476
        count = 0L
        for (i in 0 until blockLength) buffer[i] = 0
    }

    override fun engineUpdate(b: Byte) {
        val i = (count % blockLength).toInt()
        count++
        buffer[i] = b
        if (i == blockLength - 1) transform(buffer, 0)
    }

    override fun engineUpdate(input: ByteArray, offset: Int, len: Int) {
        if (offset < 0 || len < 0 || offset.toLong() + len > input.size.toLong())
            throw ArrayIndexOutOfBoundsException()
        var bufferNdx = (count % blockLength).toInt()
        count += len
        val partLen = blockLength - bufferNdx
        var i = 0
        if (len >= partLen) {
            System.arraycopy(input, offset, buffer, bufferNdx, partLen)
            transform(buffer, 0)
            i = partLen
            while (i + blockLength - 1 < len) {
                transform(input, offset + i)
                i += blockLength
            }
            bufferNdx = 0
        }
        if (i < len) System.arraycopy(input, offset + i, buffer, bufferNdx, len - i)
    }

    override fun engineDigest(): ByteArray {
        val bufferNdx = (count % blockLength).toInt()
        val padLen = if (bufferNdx < 56) 56 - bufferNdx else 120 - bufferNdx
        val tail = ByteArray(padLen + 8)
        tail[0] = 0x80.toByte()
        for (i in 0..7) tail[padLen + i] = ((count * 8) ushr (8 * i)).toByte()
        engineUpdate(tail, 0, tail.size)
        val result = ByteArray(16)
        for (i in 0..3)
            for (j in 0..3)
                result[i * 4 + j] = (context[i] ushr (8 * j)).toByte()
        engineReset()
        return result
    }

    private fun transform (block: ByteArray, offset: Int) {
        var offset2 = offset
        for (i in 0..15)
            x[i] = ((block[offset2++].toInt() and 0xff)       ) or
                   ((block[offset2++].toInt() and 0xff) shl 8 ) or
                   ((block[offset2++].toInt() and 0xff) shl 16) or
                   ((block[offset2++].toInt() and 0xff) shl 24)

        var a = context[0]
        var b = context[1]
        var c = context[2]
        var d = context[3]

        a = ff(a, b, c, d, x[ 0],  3)
        d = ff(d, a, b, c, x[ 1],  7)
        c = ff(c, d, a, b, x[ 2], 11)
        b = ff(b, c, d, a, x[ 3], 19)
        a = ff(a, b, c, d, x[ 4],  3)
        d = ff(d, a, b, c, x[ 5],  7)
        c = ff(c, d, a, b, x[ 6], 11)
        b = ff(b, c, d, a, x[ 7], 19)
        a = ff(a, b, c, d, x[ 8],  3)
        d = ff(d, a, b, c, x[ 9],  7)
        c = ff(c, d, a, b, x[10], 11)
        b = ff(b, c, d, a, x[11], 19)
        a = ff(a, b, c, d, x[12],  3)
        d = ff(d, a, b, c, x[13],  7)
        c = ff(c, d, a, b, x[14], 11)
        b = ff(b, c, d, a, x[15], 19)

        a = gg(a, b, c, d, x[ 0],  3)
        d = gg(d, a, b, c, x[ 4],  5)
        c = gg(c, d, a, b, x[ 8],  9)
        b = gg(b, c, d, a, x[12], 13)
        a = gg(a, b, c, d, x[ 1],  3)
        d = gg(d, a, b, c, x[ 5],  5)
        c = gg(c, d, a, b, x[ 9],  9)
        b = gg(b, c, d, a, x[13], 13)
        a = gg(a, b, c, d, x[ 2],  3)
        d = gg(d, a, b, c, x[ 6],  5)
        c = gg(c, d, a, b, x[10],  9)
        b = gg(b, c, d, a, x[14], 13)
        a = gg(a, b, c, d, x[ 3],  3)
        d = gg(d, a, b, c, x[ 7],  5)
        c = gg(c, d, a, b, x[11],  9)
        b = gg(b, c, d, a, x[15], 13)

        a = hh(a, b, c, d, x[ 0],  3)
        d = hh(d, a, b, c, x[ 8],  9)
        c = hh(c, d, a, b, x[ 4], 11)
        b = hh(b, c, d, a, x[12], 15)
        a = hh(a, b, c, d, x[ 2],  3)
        d = hh(d, a, b, c, x[10],  9)
        c = hh(c, d, a, b, x[ 6], 11)
        b = hh(b, c, d, a, x[14], 15)
        a = hh(a, b, c, d, x[ 1],  3)
        d = hh(d, a, b, c, x[ 9],  9)
        c = hh(c, d, a, b, x[ 5], 11)
        b = hh(b, c, d, a, x[13], 15)
        a = hh(a, b, c, d, x[ 3],  3)
        d = hh(d, a, b, c, x[11],  9)
        c = hh(c, d, a, b, x[ 7], 11)
        b = hh(b, c, d, a, x[15], 15)

        context[0] += a
        context[1] += b
        context[2] += c
        context[3] += d
    }

    private fun ff(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
        val t = a + ((b and c) or (b.inv() and d)) + x
        return (t shl s) or (t ushr (32 - s))
    }

    private fun gg(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
        val t = a + ((b and (c or d)) or (c and d)) + x + 0x5a827999
        return (t shl s) or (t ushr (32 - s))
    }

    private fun hh(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
        val t = a + (b xor c xor d) + x + 0x6ed9eba1
        return (t shl s) or (t ushr (32 - s))
    }
}

fun main(args: Array<String>) {
    val text  = "Rosetta Code"
    val bytes = text.toByteArray(Charsets.US_ASCII)
    val md: MessageDigest = MD4()
    val digest = md.digest(bytes)
    for (byte in digest) print("%02x".format(byte))
    println()
}


Machine code

The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.

For example, the following assembly language program is given for x86 (32 bit) architectures:

mov EAX, [ESP+4]
add EAX, [ESP+8]
ret

This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195

Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3

;Task:
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:

* Poke the necessary opcodes into a memory location.
* Provide a means to pass two values to the machine code.
* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)

Solution:
// Kotlin Native version 0.3

import kotlinx.cinterop.*
import string.*
import mman.*
import mcode.*

fun main(args: Array<String>) {
    memScoped {
        val bytes = byteArrayOf(
            144 - 256,                            // Align
            144 - 256,
            106, 12,                              // Prepare stack
            184 - 256, 7, 0, 0, 0,
            72, 193 - 256, 224 - 256, 32,
            80,
            139 - 256, 68, 36, 4, 3, 68, 36, 8,   // Rosetta task code
            76, 137 - 256, 227 - 256,             // Get result
            137 - 256, 195 - 256,
            72, 193 - 256, 227 - 256, 4,
            128 - 256, 203 - 256, 2,
            72, 131 - 256, 196 - 256, 16,         // Clean up stack
            195 - 256                             // Return
        )
        val len = bytes.size
        val code = allocArray<ByteVar>(len)
        for (i in 0 until len) code[i] = bytes[i]
        val buf = mmap(null, len.toLong(), PROT_READ or PROT_WRITE or PROT_EXEC,
                       MAP_PRIVATE or MAP_ANON, -1, 0)
        memcpy(buf, code, len.toLong())
        val a: Byte = 7
        val b: Byte = 12
        val c = runMachineCode(buf, a, b)
        munmap(buf, len.toLong())
        println("$a + $b = ${if(c >= 0) c.toInt() else c + 256}")
    }
}


Mad Libs

{{wikipedia}}

Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.

;Task;
Write a program to create a Mad Libs like story.

The program should read an arbitrary multiline story from input.

The story will be terminated with a blank line.

Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.

Stop when there are none left and print the final story.

The input should be an arbitrary story in the form:

 went for a walk in the park.
found a .  decided to take it home.

Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).

Solution:
// version 1.1.2

fun main(args: Array<String>) {
    println("Please enter a multi-line story template terminated by a blank line\n")
    val sb  = StringBuilder()
    while (true) {
        val line = readLine()!!
        if (line.isEmpty()) break
        sb.append("$line\n") // preserve line breaks
    }
    var story = sb.toString()
    // identify blanks
    val r = Regex("<.*?>")
    val blanks = r.findAll(story).map { it.value }.distinct()
    println("Please enter your replacements for the following 'blanks' in the story:")
    for (blank in blanks) {
        print("${blank.drop(1).dropLast(1)} : ")
        val repl = readLine()!!
        story = story.replace(blank, repl)
    }
    println("\n$story")
}


Magic 8-ball

Create Magic 8-Ball.

See details at:   Magic 8-Ball.

Solution:
// Version 1.2.40

import java.util.Random

fun main(args: Array<String>) {
    val answers = listOf(
        "It is certain", "It is decidedly so", "Without a doubt",
        "Yes, definitely", "You may rely on it", "As I see it, yes",
        "Most likely", "Outlook good", "Signs point to yes", "Yes",
        "Reply hazy, try again", "Ask again later",
        "Better not tell you now", "Cannot predict now",
        "Concentrate and ask again", "Don't bet on it",
        "My reply is no", "My sources say no", "Outlook not so good",
        "Very doubtful"
    )
    val rand = Random()
    println("Please enter your question or a blank line to quit.")
    while (true) {
        print("\n? : ")
        val question = readLine()!!
        if (question.trim() == "") return
        val answer = answers[rand.nextInt(20)]
        println("\n$answer")
    }
}


Magic squares of doubly even order

Solution:
// version 1.1.0

fun magicSquareDoublyEven(n: Int): Array<IntArray> {
    if ( n < 4 || n % 4 != 0)
        throw IllegalArgumentException("Base must be a positive multiple of 4")

    // pattern of count-up vs count-down zones
    val bits = 0b1001_0110_0110_1001
    val size = n * n
    val mult = n / 4  // how many multiples of 4
    val result = Array(n) { IntArray(n) }
    var i = 0
    for (r in 0 until n)
        for (c in 0 until n) {
            val bitPos = c / mult + r / mult * 4
            result[r][c] =  if (bits and (1 shl bitPos) != 0) i + 1 else size - i
            i++
        }
    return result
}

fun main(args: Array<String>) {
    val n = 8
    for (ia in magicSquareDoublyEven(n)) {
        for (i in ia) print("%2d  ".format(i))
        println()
    }
    println("\nMagic constant ${(n * n + 1) * n / 2}")
}


Magic squares of odd order

A magic square is an   '''NxN'''   square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column,   ''and''   both long (main) diagonals are equal to the same sum (which is called the   ''magic number''   or   ''magic constant'').

The numbers are usually (but not always) the first   '''N'''2   positive integers.

A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.

{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}

;Task
For any odd   '''N''',   generate a magic square with the integers   ''' 1''' --> '''N''',   and show the results here.

Optionally, show the ''magic number''.

You should demonstrate the generator by showing at least a magic square for   '''N''' = '''5'''.

; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]

; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)

Solution:
// version 1.0.6

fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n

fun main(args: Array<String>) {
    var n: Int
    while (true) {
        print("Enter the order of the magic square : ")
        n = readLine()!!.toInt()
        if (n < 1 || n % 2 == 0) println("Must be odd and >= 1, try again")
        else break
    }
    println()
    for (i in 0 until n) {
        for (j in 0 until n) print("%4d".format(f(n, n - j - 1, i) * n + f(n, j, i) + 1))
        println()
    }
    println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
}


Magic squares of singly even order

A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').

A  magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.

;Task
Create a magic square of 6 x 6.

; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]

; See also
* Singly Even Magic Squares (1728.org)

Solution:
// version 1.0.6

fun magicSquareOdd(n: Int): Array<IntArray> {
    if (n < 3 || n % 2 == 0)
         throw IllegalArgumentException("Base must be odd and > 2")

    var value = 0
    val gridSize = n * n
    var c = n / 2
    var r = 0
    val result = Array(n) { IntArray(n) }
    while (++value <= gridSize) {
        result[r][c] = value
        if (r == 0) {
            if (c == n - 1) r++
            else {
                r = n - 1
                c++
            }
        }
        else if (c == n - 1) {
            r--
            c = 0
        }
        else if (result[r - 1][c + 1] == 0) {
            r--
            c++
        }
        else r++
    }
    return result
}

fun magicSquareSinglyEven(n: Int): Array<IntArray> {
    if (n < 6 || (n - 2) % 4 != 0)
        throw IllegalArgumentException("Base must be a positive multiple of 4 plus 2")

    val size = n * n
    val halfN = n / 2
    val subSquareSize = size / 4
    val subSquare = magicSquareOdd(halfN)
    val quadrantFactors = intArrayOf(0, 2, 3, 1)
    val result = Array(n) { IntArray(n) }
    for (r in 0 until n)
        for (c in 0 until n) {
            val quadrant = r / halfN * 2  + c / halfN
            result[r][c] = subSquare[r % halfN][c % halfN]
            result[r][c] += quadrantFactors[quadrant] * subSquareSize
        }
    val nColsLeft = halfN / 2
    val nColsRight = nColsLeft - 1
    for (r in 0 until halfN)
        for (c in 0 until n)
            if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) {
                if (c == 0 && r == nColsLeft) continue
                val tmp = result[r][c]
                result[r][c] = result[r + halfN][c]
                result[r + halfN][c] = tmp
            }
    return result
}

fun main(args: Array<String>) {
    val n = 6
    for (ia in magicSquareSinglyEven(n)) {
        for (i in ia) print("%2d  ".format(i))
        println()
    }
    println("\nMagic constant ${(n * n + 1) * n / 2}")
}


Map range

Given two ranges:
:::*   [a_1,a_2]   and
:::*   [b_1,b_2];
:::*   then a value   s   in range   [a_1,a_2]
:::*   is linearly mapped to a value   t   in range   [b_1,b_2]
   where:

:::*   t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}

;Task:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.

Use this function to map values from the range    [0, 10]    to the range    [-1, 0].

;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.

Solution:
// version 1.0.6

class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange<Float>

fun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float {
    if (value !in range1) throw IllegalArgumentException("value is not within the first range")
    if (range1.endInclusive == range1.start) throw IllegalArgumentException("first range cannot be single-valued")
    return range2.start + (value - range1.start) * (range2.endInclusive - range2.start) / (range1.endInclusive - range1.start)
}

fun main(args: Array<String>) {
    for (i in 0..10) {
        val mappedValue = mapRange(FloatRange(0.0f, 10.0f), FloatRange(-1.0f, 0.0f), i.toFloat())
        println(String.format("%2d  maps to %+4.2f", i, mappedValue))
    }
}


Maximum triangle path sum

Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:

                          55
                        94 48
                       95 30 96
                     77 71 26 67

One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.

Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.

;Task:
Find the maximum total in the triangle below:

                          55
                        94 48
                       95 30 96
                     77 71 26 67
                    97 13 76 38 45
                  07 36 79 16 37 68
                 48 07 09 18 70 26 06
               18 72 79 46 59 79 29 90
              20 76 87 11 32 07 07 49 18
            27 83 58 35 71 11 25 57 29 85
           14 64 36 96 27 11 58 56 92 18 55
         02 90 03 60 48 49 41 46 33 36 47 23
        92 50 48 02 36 59 42 79 72 20 82 77 42
      56 78 38 80 39 75 02 71 66 66 01 03 55 72
     44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
   85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
  06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93

Such numbers can be included in the solution code, or read from a "triangle.txt" file.

This task is derived from the Euler Problem #18.

Solution:
// version 1.1.2

val tri = intArrayOf(
    55,
    94, 48,
    95, 30, 96,
    77, 71, 26, 67,
    97, 13, 76, 38, 45,
     7, 36, 79, 16, 37, 68,
    48,  7,  9, 18, 70, 26,  6,
    18, 72, 79, 46, 59, 79, 29, 90,
    20, 76, 87, 11, 32,  7,  7, 49, 18,
    27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
    14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
     2, 90,  3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
    92, 50, 48,  2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
    56, 78, 38, 80, 39, 75,  2, 71, 66, 66,  1,  3, 55, 72,
    44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
    85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17,  1,  1, 99, 89, 52,
     6, 71, 28, 75, 94, 48, 37, 10, 23, 51,  6, 48, 53, 18, 74, 98, 15,
    27,  2, 92, 23,  8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
)

fun main(args: Array<String>) {
    val triangles = arrayOf(tri.sliceArray(0..9), tri)
    for (triangle in triangles) {
        val size  = triangle.size
        val base  = ((Math.sqrt(8.0 * size + 1.0) - 1.0)/ 2.0).toInt()
        var step  = base - 1
        var stepc = 0
        for (i in (size - base - 1) downTo 0) {
            triangle[i] += maxOf(triangle[i + step], triangle[i + step + 1])
            if (++stepc == step) {
                step--
                stepc = 0
            }
        }
        println("Maximum total  = ${triangle[0]}")
    }
}


McNuggets problem

From Wikipedia:
 The McNuggets version of the coin problem was introduced by Henri Picciotto,
 who included it in his algebra textbook co-authored with Anita Wah. Picciotto
 thought of the application in the 1980s while dining with his son at
 McDonald's, working the problem out on a napkin. A McNugget number is
 the total number of McDonald's Chicken McNuggets in any number of boxes.
 In the United Kingdom, the original boxes (prior to the introduction of
 the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.

;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).

Solution:
// Version 1.2.71

fun mcnugget(limit: Int) {
    val sv = BooleanArray(limit + 1)  // all false by default
    for (s in 0..limit step 6)
        for (n in s..limit step 9)
            for (t in n..limit step 20) sv[t] = true

    for (i in limit downTo 0) {
        if (!sv[i]) {
            println("Maximum non-McNuggets number is $i")
            return
        }
    }
}

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


Memory layout of a data structure

It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
 Pin Settings for Plug
 (Reverse order for socket.)
 __________________________________________
 1  2  3  4  5  6  7  8  9  10 11 12 13
  14 15 16 17 18 19 20 21 22 23 24 25
 _________________
 1  2  3  4  5
 6  7  8  9
 25 pin                        9 pin
 1 - PG   Protective ground
 2 - TD   Transmitted data     3
 3 - RD   Received data        2
 4 - RTS  Request to send      7
 5 - CTS  Clear to send        8
 6 - DSR  Data set ready       6
 7 - SG   Signal ground        5
 8 - CD   Carrier detect       1
 9 - + voltage (testing)
 10 - - voltage (testing)
 11 -
 12 - SCD  Secondary CD
 13 - SCS  Secondary CTS
 14 - STD  Secondary TD
 15 - TC   Transmit clock
 16 - SRD  Secondary RD
 17 - RC   Receiver clock
 18 -
 19 - SRS  Secondary RTS
 20 - DTR  Data terminal ready      4
 21 - SQD  Signal quality detector
 22 - RI   Ring indicator           9
 23 - DRS  Data rate select
 24 - XTC  External clock
 25 -

Solution:
// version 1.0.6

const val OFF = false
const val ON  = true

fun toOnOff(b: Boolean) = if (b) "ON" else "OFF"

data class Rs232Pins9(
    var carrierDetect     : Boolean = OFF,
    var receivedData      : Boolean = OFF,
    var transmittedData   : Boolean = OFF,
    var dataTerminalReady : Boolean = OFF,
    var signalGround      : Boolean = OFF,
    var dataSetReady      : Boolean = OFF,
    var requestToSend     : Boolean = OFF,
    var clearToSend       : Boolean = OFF,
    var ringIndicator     : Boolean = OFF
) {
    fun setPin(n: Int, v: Boolean) {
        when (n) {
            1 -> carrierDetect     = v
            2 -> receivedData      = v
            3 -> transmittedData   = v
            4 -> dataTerminalReady = v
            5 -> signalGround      = v
            6 -> dataSetReady      = v
            7 -> requestToSend     = v
            8 -> clearToSend       = v
            9 -> ringIndicator     = v
        }
    }
}

fun main(args: Array<String>) {
    val plug = Rs232Pins9(carrierDetect = ON, receivedData = ON) // set first two pins, say
    println(toOnOff(plug.component2()))                          // print value of pin 2 by number
    plug.transmittedData = ON                                    // set pin 3 by name
    plug.setPin(4, ON)                                           // set pin 4 by number
    println(toOnOff(plug.component3()))                          // print value of pin 3 by number
    println(toOnOff(plug.dataTerminalReady))                     // print value of pin 4 by name
    println(toOnOff(plug.ringIndicator))                         // print value of pin 9 by name
}


Metallic ratios

Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series
of related ratios that are referred to as the "'''Metallic ratios'''".

The '''Golden ratio''' was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was
also known to the early Greeks, though was not named so until later as a nod to
the '''Golden ratio''' to which it is closely related. The series has been extended to
encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').
''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".''

'''Metallic ratios''' are the real roots of the general form equation:

          x2 - bx - 1 = 0

where the integer '''b''' determines which specific one it is.

Using the quadratic equation:

          ( -b +- (b2 - 4ac) ) / 2a = x

Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:

          ( b +- (b2 + 4) ) ) / 2 = x

We only want the real root:

          ( b + (b2 + 4) ) ) / 2 = x

When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.

          ( 1 + (12 + 4) ) / 2  =  (1 + 5) / 2 = ~1.618033989...

With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.

          ( 2 + (22 + 4) ) / 2  =  (2 + 8) / 2 = ~2.414213562...

When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''
are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as
standard. After that there isn't really any attempt at standardized names. They
are given names here on this page, but consider the names fanciful rather than
canonical.

Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''.
We will refer to it here as the '''Platinum ratio''', though it is kind-of a
degenerate case.

'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:

          [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...]

So, The first ten '''Metallic ratios''' are:

:::::: {| class="wikitable" style="text-align: center;"
|+ Metallic ratios
!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link
|-
|Platinum||0||(0 + 4) / 2|| 1||-||-
|-
|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]
|-
|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]
|-
|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]
|-
|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]
|-
|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]
|-
|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]
|-
|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]
|-
|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]
|-
|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]
|}

There are other ways to find the '''Metallic ratios'''; one, (the focus of this task)
is through '''successive approximations of Lucas sequences'''.

A traditional '''Lucas sequence''' is of the form:

    x''n'' = P * x''n-1'' - Q * x''n-2''

and starts with the first 2 values '''0, 1'''.

For our purposes in this task, to find the metallic ratios we'll use the form:

    x''n'' = b * x''n-1'' + x''n-2''

( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.''

At any rate, when '''b = 1''' we get:

    x''n'' = x''n-1'' + x''n-2''

    1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...

more commonly known as the Fibonacci sequence.

When '''b = 2''':

    x''n'' = 2 * x''n-1'' + x''n-2''

    1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...

And so on.

To find the ratio by successive approximations, divide the ('''n+1''')th term by the
'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.

For '''b = 1''' (Fibonacci sequence):

    1/1   = 1
    2/1   = 2
    3/2   = 1.5
    5/3   = 1.666667
    8/5   = 1.6
    13/8  = 1.625
    21/13 = 1.615385
    34/21 = 1.619048
    55/34 = 1.617647
    89/55 = 1.618182
    etc.

It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest
possible convergence for any irrational number.

;Task

For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':

* Generate the corresponding "Lucas" sequence.
* Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence.
* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.
* Show the '''value''' of the '''approximation''' at the required accuracy.
* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).

Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.

You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.

;See also
* Wikipedia: Metallic mean
* Wikipedia: Lucas sequence

Solution:
import java.math.BigDecimal
import java.math.BigInteger

val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")

fun lucas(b: Long) {
    println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
    print("First 15 elements: ")
    var x0 = 1L
    var x1 = 1L
    print("$x0, $x1")
    for (i in 1..13) {
        val x2 = b * x1 + x0
        print(", $x2")
        x0 = x1
        x1 = x2
    }
    println()
}

fun metallic(b: Long, dp:Int) {
    var x0 = BigInteger.ONE
    var x1 = BigInteger.ONE
    var x2: BigInteger
    val bb = BigInteger.valueOf(b)
    val ratio = BigDecimal.ONE.setScale(dp)
    var iters = 0
    var prev = ratio.toString()
    while (true) {
        iters++
        x2 = bb * x1 + x0
        val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()
        if (prev == thiz) {
            var plural = "s"
            if (iters == 1) {
                plural = ""
            }
            println("Value after $iters iteration$plural: $thiz\n")
            return
        }
        prev = thiz
        x0 = x1
        x1 = x2
    }
}

fun main() {
    for (b in 0L until 10L) {
        lucas(b)
        metallic(b, 32)
    }
    println("Golden ration, where b = 1:")
    metallic(1, 256)
}


Metaprogramming

{{omit from|BBC BASIC}}
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.

For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.

Solution:
// version 1.0.6

infix fun Double.pwr(exp: Double) = Math.pow(this, exp)

fun main(args: Array<String>) {
   val d = 2.0 pwr 8.0
   println(d)
}


Metronome

The task is to implement a   metronome.

The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.

For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.

However, the playing of the sounds should not interfere with the timing of the metronome.

The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.

If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.

Solution:
// version 1.1.2

fun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) {
    val delay = 60_000L / bpm
    var beats = 0
    do {
        Thread.sleep(delay)
        if (beats % bpb == 0) print("\nTICK ")
        else print("tick ")
        beats++
    }
    while (beats < maxBeats)
    println()
}

fun main(args: Array<String>) = metronome(120, 4, 20) // limit to 20 beats


Mian-Chowla sequence

The Mian-Chowla sequence is an integer sequence defined recursively.

Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.

The sequence starts with:

::a1 = 1

then for n > 1, an is the smallest positive integer such that every pairwise sum

::ai + aj

is distinct, for all i and j less than or equal to n.

;The Task:

:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.
:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.

Demonstrating working through the first few terms longhand:

::a1 = 1

::1 + 1 = 2

Speculatively try a2 = 2

::1 + 1 = 2
::1 + 2 = 3
::2 + 2 = 4

There are no repeated sums so '''2''' is the next number in the sequence.

Speculatively try a3 = 3

::1 + 1 = 2
::1 + 2 = 3
::1 + 3 = 4
::2 + 2 = 4
::2 + 3 = 5
::3 + 3 = 6

Sum of '''4''' is repeated so '''3''' is rejected.

Speculatively try a3 = 4

::1 + 1 = 2
::1 + 2 = 3
::1 + 4 = 5
::2 + 2 = 4
::2 + 4 = 6
::4 + 4 = 8

There are no repeated sums so '''4''' is the next number in the sequence.

And so on...

;See also:

:* OEIS:A005282 Mian-Chowla sequence

Solution:
// Version 1.3.21

fun mianChowla(n: Int): List<Int> {
    val mc = MutableList(n) { 0 }
    mc[0] = 1
    val hs = HashSet<Int>(n * (n + 1) / 2)
    hs.add(2)
    val hsx = mutableListOf<Int>()
    for (i in 1 until n) {
        hsx.clear()
        var j = mc[i - 1]
        outer@ while (true) {
            j++
            mc[i] = j
            for (k in 0..i) {
                val sum = mc[k] + j
                if (hs.contains(sum)) {
                    hsx.clear()
                    continue@outer
                }
                hsx.add(sum)
            }
            hs.addAll(hsx)
            break
        }
    }
    return mc
}

fun main() {
    val mc = mianChowla(100)
    println("The first 30 terms of the Mian-Chowla sequence are:")
    println(mc.subList(0, 30))
    println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
    println(mc.subList(90, 100))
}