Hash join

{| class="wikitable"
|-
! Input
! Output
|-
|

{| style="border:none; border-collapse:collapse;"
|-
| style="border:none" | ''A'' =
| style="border:none" |

{| class="wikitable"
|-
! Age !! Name
|-
| 27 || Jonah
|-
| 18 || Alan
|-
| 28 || Glory
|-
| 18 || Popeye
|-
| 28 || Alan
|}

| style="border:none; padding-left:1.5em;" rowspan="2" |
| style="border:none" | ''B'' =
| style="border:none" |

{| class="wikitable"
|-
! Character !! Nemesis
|-
| Jonah || Whales
|-
| Jonah || Spiders
|-
| Alan || Ghosts
|-
| Alan || Zombies
|-
| Glory || Buffy
|}

|-
| style="border:none" | ''jA'' =
| style="border:none" | Name (i.e. column 1)

| style="border:none" | ''jB'' =
| style="border:none" | Character (i.e. column 0)
|}

|

{| class="wikitable" style="margin-left:1em"
|-
! A.Age !! A.Name !! B.Character !! B.Nemesis
|-
| 27 || Jonah || Jonah || Whales
|-
| 27 || Jonah || Jonah || Spiders
|-
| 18 || Alan || Alan || Ghosts
|-
| 18 || Alan || Alan || Zombies
|-
| 28 || Glory || Glory || Buffy
|-
| 28 || Alan || Alan || Ghosts
|-
| 28 || Alan || Alan || Zombies
|}

|}

The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].

Solution:
data class A(val age: Int, val name: String)

data class B(val character: String, val nemesis: String)

data class C(val rowA: A, val rowB: B)

fun hashJoin(tableA: List<A>, tableB: List<B>): List<C> {
    val mm = tableB.groupBy { it.character }
    val tableC = mutableListOf<C>()
    for (a in tableA) {
        val value = mm[a.name] ?: continue
        for (b in value) tableC.add(C(a, b))
    }
    return tableC.toList()
}

fun main(args: Array<String>) {
    val tableA = listOf(
        A(27, "Jonah"),
        A(18, "Alan"),
        A(28, "Glory"),
        A(18, "Popeye"),
        A(28, "Alan")
    )
    val tableB = listOf(
        B("Jonah", "Whales"),
        B("Jonah", "Spiders"),
        B("Alan", "Ghosts"),
        B("Alan", "Zombies"),
        B("Glory", "Buffy")
    )
    val tableC = hashJoin(tableA, tableB)
    println("A.Age A.Name B.Character B.Nemesis")
    println("----- ------ ----------- ---------")
    for (c in tableC) {
        print("${c.rowA.age}    ${c.rowA.name.padEnd(6)} ")
        println("${c.rowB.character.padEnd(6)}      ${c.rowB.nemesis}")
    }
}


Haversine formula

{{Wikipedia}}

The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.

It is a special case of a more general formula  in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles".

;Task:
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
* Nashville International Airport (BNA)   in Nashville, TN, USA,   which is:
    '''N''' 36deg7.2',   '''W''' 86deg40.2'     (36.12,   -86.67)           -and-
* Los Angeles International Airport (LAX)  in Los Angeles, CA, USA,   which is:
    '''N''' 33deg56.4',  '''W''' 118deg24.0'    (33.94,  -118.40)

User Kaimbridge clarified on the Talk page:

 -- 6371.0 km is the authalic radius based on/extracted from surface area;
 -- 6372.8 km is an approximation of the radius of the average circumference
    (i.e., the average great-elliptic or great-circle radius), where the
     boundaries are the meridian (6367.45 km) and the equator (6378.14 km).

Using either of these values results, of course, in differing distances:

 6371.0 km -> 2886.44444283798329974715782394574671655 km;
 6372.8 km -> 2887.25995060711033944886005029688505340 km;
 (results extended for accuracy check:  Given that the radii are only
  approximations anyways, .01'  1.0621333 km and .001"  .00177 km,
  practical precision required is certainly no greater than about
  .0000001----i.e., .1 mm!)

As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).

Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius.  However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased).  When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km.  This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.

Solution:
import java.lang.Math.*

const val R = 6372.8 // in kilometers

fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
    val λ1 = toRadians(lat1)
    val λ2 = toRadians(lat2)
    val Δλ = toRadians(lat2 - lat1)
    val Δφ = toRadians(lon2 - lon1)
    return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2)))
}

fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40))


Hello world/Newbie

Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the [[Hello world/Text]] task.
* Assume the language-newbie is a programmer in another language.
* Assume the language-newbie is competent in installing software for the platform.
* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).
* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).
* Remember to state where to view the output.
* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.

;Note:
* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.
* You may use sub-headings if giving instructions for multiple platforms.

Solution:
fun main(args: Array<String>) {
    println("Hello, World!")
}


Here document

A   ''here document''    (or "heredoc")   is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.

Depending on the language being used, a   ''here document''   is constructed using a command followed by "<<" (or some other symbol) followed by a token string.

The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.

;Task:
Demonstrate the use of   ''here documents''   within the language.

;Related task:
*   [[Documentation]]

Solution:
// version 1.1.0

fun main(args: Array<String>) {
    val ev = "embed variables"

    val here = """
               This is a raw string literal
               which does not treat escaped characters
               (\t, \b, \n, \r, \', \", \\, \$ and \u)
               specially and can contain new lines,
               indentation and other        whitespace
               within the string.

"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.

           It's also possible to $ev
           in a raw string literal using string
           interpolation.

  If you need to include a
  literal ${'$'} sign in a raw string literal then
  don't worry you've just done it!
               """

    println(here)
}


Heronian triangles

Hero's formula for the area of a triangle given the length of its three sides    ''a'',   ''b'',   and   ''c''   is given by:

:::: A = \sqrt{s(s-a)(s-b)(s-c)},

where   ''s''   is half the perimeter of the triangle; that is,

:::: s=\frac{a+b+c}{2}.

'''Heronian triangles'''
are triangles whose sides ''and area'' are all integers.
: An example is the triangle with sides   '''3, 4, 5'''   whose area is   '''6'''   (and whose perimeter is   '''12''').

Note that any triangle whose sides are all an integer multiple of   '''3, 4, 5''';   such as   '''6, 8, 10,'''   will also be a Heronian triangle.

Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor
of all three sides is   '''1'''   (unity).

This will exclude, for example, triangle   '''6, 8, 10.'''

;Task:
# Create a named function/method/procedure/... that implements Hero's formula.
# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.
# Show the count of how many triangles are found.
# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths
# Show the first ten ordered triangles in a table of sides, perimeter, and area.
# Show a similar ordered table for those triangles with area = 210

Show all output here.

'''Note''': when generating triangles it may help to restrict a <= b <= c

Solution:
import java.util.ArrayList

object Heron {
    private val n = 200

    fun run() {
        val l = ArrayList<IntArray>()
        for (c in 1..n)
            for (b in 1..c)
                for (a in 1..b)
                    if (gcd(gcd(a, b), c) == 1) {
                        val p = a + b + c
                        val s = p / 2.0
                        val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
                        if (isHeron(area))
                            l.add(intArrayOf(a, b, c, p, area.toInt()))
                    }
        print("Number of primitive Heronian triangles with sides up to $n: " + l.size)

        sort(l)
        print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
        for (i in 0 until 10) {
            print(format(l[i]))
        }
        val a = 210
        print("\n\nArea = $a" + header)
        l.filter { it[4] == a }.forEach { print(format(it)) }
    }

    private fun gcd(a: Int, b: Int): Int {
        var leftover = 1
        var dividend = if (a > b) a else b
        var divisor = if (a > b) b else a
        while (leftover != 0) {
            leftover = dividend % divisor
            if (leftover > 0) {
                dividend = divisor
                divisor = leftover
            }
        }
        return divisor
    }

    fun sort(l: MutableList<IntArray>) {
        var swapped = true
        while (swapped) {
            swapped = false
            for (i in 1 until l.size)
                if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) {
                    val temp = l[i]
                    l[i] = l[i - 1]
                    l[i - 1] = temp
                    swapped = true
                }
        }
    }

    private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0

    private val header = "\nSides           Perimeter   Area"
    private fun format(a: IntArray) = "\n%3d x %3d x %3d %5d %10d".format(a[0], a[1], a[2], a[3], a[4])
}

fun main(args: Array<String>) = Heron.run()


Hickerson series of almost integers

The following function,   due to D. Hickerson,   is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld,   (December 31 2013).   (See formula numbered   '''51'''.)

The function is:           h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}}

It is said to produce "almost integers" for   '''n'''   between   '''1'''   and   '''17'''.
The purpose of the task is to verify this assertion.

Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation

;Task:
Calculate all values of the function checking and stating which are "almost integers".

Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:
                h(18) = 3385534663256845326.39...

Solution:
// version 1.1.4

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

object Hickerson {
    private const val LN2 = "0.693147180559945309417232121458"

    fun almostInteger(n: Int): Boolean {
        val a = BigDecimal(LN2).pow(n + 1) * BigDecimal(2)
        var nn = n
        var f = n.toLong()
        while (--nn > 1) f *= nn
        val b = BigDecimal(f).divide(a, MathContext.DECIMAL128)
        val c = b.movePointRight(1).toBigInteger() % BigInteger.TEN
        return c.toString().matches(Regex("[09]"))
    }
}

fun main(args: Array<String>) {
    for (n in 1..17) println("${"%2d".format(n)} is almost integer: ${Hickerson.almostInteger(n)}")
}


History variables

''Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''

''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.
''

"History Variables:
The Semantics, Formal Correctness, and Implementation of History Variables
in an Imperative Programming Language" by Mallon and Takaoka

Concept also discussed on LtU and Patents.com.

;Task:
Demonstrate History variable support:
* enable history variable support (if needed)
* define a history variable
* assign three values
* non-destructively display the history
* recall the three values.

For extra points, if the language of choice does not support history variables,
demonstrate how this might be implemented.

Solution:
// version 1.1.4

class HistoryVariable<T>(initialValue: T) {
    private val history = mutableListOf<T>()

    var currentValue: T
        get() = history[history.size - 1]
        set(value) {
           history.add(value)
        }

    init {
        currentValue = initialValue
    }

    fun showHistory() {
        println("The variable's history, oldest values first, is:")
        for (item in history) println(item)
    }
}

fun main(args: Array<String>) {
    val v = HistoryVariable(1)
    v.currentValue = 2
    v.currentValue = 3
    v.showHistory()
    println("\nCurrentvalue is ${v.currentValue}")
}


Hofstadter-Conway $10,000 sequence

The definition of the sequence is colloquially described as:
*   Starting with the list [1,1],
*   Take the last number in the list so far: 1, I'll call it x.
*   Count forward x places from the beginning of the list to find the first number to add (1)
*   Count backward x places from the end of the list to find the second number to add (1)
*   Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)
*   This would then produce [1,1,2] where 2 is the third element of the sequence.

Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.

A less wordy description of the sequence is:
    a(1)=a(2)=1
    a(n)=a(a(n-1))+a(n-a(n-1))

The sequence begins:
    1, 1, 2, 2, 3, 4, 4, 4, 5, ...

Interesting features of the sequence are that:
*   a(n)/n   tends to   0.5   as   n   grows towards infinity.
*   a(n)/n   where   n   is a power of   2   is   0.5
*   For   n>4   the maximal value of   a(n)/n   between successive powers of 2 decreases.

a(n) / n   for   n   in   1..256

The sequence is so named because John Conway offered a prize of $10,000 to the first person who could
find the first position,   p   in the sequence where
    |a(n)/n| < 0.55  for all  n > p
It was later found that Hofstadter had also done prior work on the sequence.

The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of   n   (which is much smaller than the 3,173,375,556 quoted in the NYT article).

;Task:
#   Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.
#   Use it to show the maxima of   a(n)/n   between successive powers of two up to   2**20
#   As a stretch goal:   compute the value of   n   that would have won the prize and confirm it is true for   n   up to 2**20

;Also see:
*   Conways Challenge Sequence, Mallows' own account.
*   Mathworld Article.

Solution:
// version 1.1.2

fun main(args: Array<String>) {
    val limit = (1 shl 20) + 1
    val a = IntArray(limit)
    a[1] = 1
    a[2] = 1
    for (n in 3 until limit) {
        val p = a[n - 1]
        a[n] = a[p] + a[n - p]
    }

    println("     Range          Maximum")
    println("----------------   --------")
    var pow2 = 1
    var p = 1
    var max = a[1].toDouble()
    for (n in 2 until limit) {
        val r = a[n].toDouble() / n
        if (r > max) max = r
        if (n == pow2 * 2) {
            println("2 ^ ${"%2d".format(p - 1)} to 2 ^ ${"%2d".format(p)}   ${"%f".format(max)}")
            pow2 *= 2
            p++
            max = r
        }
    }

    var prize = 0
    for (n in limit - 1 downTo 1) {
        if (a[n].toDouble() / n >= 0.55) {
            prize = n
            break
        }
    }
    println("\nMallows' number = $prize")
}


Hofstadter Figure-Figure sequences

These two sequences of positive integers are defined as:
:::: \begin{align}
R(1)&=1\ ;\ S(1)=2 \\
R(n)&=R(n-1)+S(n-1), \quad n>1.
\end{align}

The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).

Sequence R starts:
    1, 3, 7, 12, 18, ...
Sequence S starts:
    2, 4, 5, 6, 8, ...

;Task:
# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
# No maximum value for '''n''' should be assumed.
# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.

;References:
* Sloane's A005228 and A030124.
* Wolfram MathWorld
* Wikipedia: Hofstadter Figure-Figure sequences.

Solution:
fun ffr(n: Int) = get(n, 0)[n - 1]

fun ffs(n: Int) = get(0, n)[n - 1]

internal fun get(rSize: Int, sSize: Int): List<Int> {
    val rlist = arrayListOf(1, 3, 7)
    val slist = arrayListOf(2, 4, 5, 6)
    val list = if (rSize > 0) rlist else slist
    val targetSize = if (rSize > 0) rSize else sSize

    while (list.size > targetSize)
        list.removeAt(list.size - 1)
    while (list.size < targetSize) {
        val lastIndex = rlist.lastIndex
        val lastr = rlist[lastIndex]
        val r = lastr + slist[lastIndex]
        rlist += r
        var s = lastr + 1
        while (s < r && list.size < targetSize)
            slist += s++
    }
    return list
}

fun main(args: Array<String>) {
    print("R():")
    (1..10).forEach { print(" " + ffr(it)) }
    println()

    val first40R = (1..40).map { ffr(it) }
    val first960S = (1..960).map { ffs(it) }
    val indices = (1..1000).filter  { it in first40R == it in first960S }
    indices.forEach { println("Integer $it either in both or neither set") }
    println("Done")
}


Hofstadter Q sequence

The Hofstadter Q sequence is defined as:
:: \begin{align}
Q(1)&=Q(2)=1, \\
Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2.
\end{align}

It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.

;Task:
* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6
* Confirm and display that the 1000th term is:   502

;Optional extra credit
* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.
* Ensure that the extra credit solution   ''safely''   handles being initially asked for an '''n'''th term where   '''n'''   is large.
(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).

Solution:
// version 1.1.4

fun main(args: Array<String>) {
    val q = IntArray(100_001)
    q[1] = 1
    q[2] = 1
    for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]]
    print("The first 10 terms are : ")
    for (i in 1..10) print("${q[i]}  ")
    println("\n\nThe 1000th term is : ${q[1000]}")
    val flips = (2..100_000).count { q[it] < q[it - 1] }
    println("\nThe number of flips for the first 100,000 terms is : $flips")
}


Honeycombs

The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should
display a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen.

Optionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.)

[[image:honeycomb.gif]]

Solution:
// version 1.1.4

import java.awt.BasicStroke
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Polygon
import java.awt.RenderingHints
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowEvent
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities

class Honeycombs : JPanel() {
    private val comb: Array<Hexagon?> = arrayOfNulls(20)

    init {
        preferredSize = Dimension(600, 500)
        background = Color.white
        isFocusable = true

        addMouseListener(object : MouseAdapter() {
            override fun mousePressed(e: MouseEvent) {
                for (hex in comb)
                    if (hex!!.contains(e.x, e.y)) {
                        hex.setSelected()
                        checkForClosure()
                        break
                    }
                repaint()
            }
        })

        addKeyListener(object : KeyAdapter() {
            override fun keyPressed(e: KeyEvent) {
                for (hex in comb)
                    if (hex!!.letter == e.keyChar.toUpperCase()) {
                        hex.setSelected()
                        checkForClosure()
                        break
                    }
                repaint()
            }
        })

        val letters = "LRDGITPFBVOKANUYCESM".toCharArray()
        val x1 = 150
        val y1 = 100
        val x2 = 225
        val y2 = 143
        val w = 150
        val h = 87

        for (i in 0 until comb.size) {
            var x: Int
            var y: Int
            if (i < 12) {
                x = x1 + (i % 3) * w
                y = y1 + (i / 3) * h
            }
            else {
                x = x2 + (i % 2) * w
                y = y2 + ((i - 12) / 2) * h
            }
            comb[i] = Hexagon(x, y, w / 3, letters[i])
        }

        requestFocus()
    }

    override fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON)
        g.font = Font("SansSerif", Font.BOLD, 30)
        g.stroke = BasicStroke(3.0f)
        for (hex in comb) hex!!.draw(g)
    }

    private fun checkForClosure() {
        if (comb.all { it!!.hasBeenSelected } ) {
            val f = SwingUtilities.getWindowAncestor(this) as JFrame
            f.dispatchEvent(WindowEvent(f, WindowEvent.WINDOW_CLOSING))
        }
    }
}

class Hexagon(x: Int, y: Int, halfWidth: Int, c: Char) : Polygon() {
    private val baseColor = Color.yellow
    private val selectedColor = Color.magenta
    var hasBeenSelected = false
    val letter = c

    init {
        for (i in 0..5)
            addPoint((x + halfWidth * Math.cos(i * Math.PI / 3.0)).toInt(),
                     (y + halfWidth * Math.sin(i * Math.PI / 3.0)).toInt())
        getBounds()
    }

    fun setSelected() {
        hasBeenSelected = true
    }

    fun draw(g: Graphics2D) {
        with(g) {
            color = if (hasBeenSelected) selectedColor else baseColor
            fillPolygon(this@Hexagon)
            color = Color.black
            drawPolygon(this@Hexagon)
            color = if (hasBeenSelected) Color.black else Color.red
            drawCenteredString(g, letter.toString())
        }
    }

    private fun drawCenteredString(g: Graphics2D, s: String) {
        val fm = g.fontMetrics
        val asc = fm.ascent
        val dec = fm.descent
        val x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2
        val y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2)
        g.drawString(s, x, y)
    }
}

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


Horner's rule for polynomial evaluation

A fast scheme for evaluating a polynomial such as:
: -19+7x-4x^2+6x^3\,
when
: x=3\;.
is to arrange the computation as follows:
: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\;
And compute the result from the innermost brackets outwards as in this pseudocode:
 coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''
 x ''':=''' 3
 accumulator ''':=''' 0
 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''
     ''# Assumes 1-based indexing for arrays''
     accumulator ''':=''' ( accumulator * x ) + coefficients[i]
 '''done'''
 ''# accumulator now has the answer''

'''Task Description'''
:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.

Cf. [[Formal power series]]

Solution:
// version 1.1.2

fun horner(coeffs: DoubleArray, x: Double): Double {
    var sum = 0.0
    for (i in coeffs.size - 1 downTo 0) sum = sum * x + coeffs[i]
    return sum
}

fun main(args: Array<String>) {
    val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0)
    println(horner(coeffs, 3.0))
}


ISBN13 check digit

Validate the check digit of an ISBN-13 code:
::*   Multiply every other digit by  '''3'''.
::*   Add these numbers and the other digits.
::*   Take the remainder of this number after division by  '''10'''.
::*   If it is  '''0''',   the ISBN-13 check digit is correct.

You might use the following codes for testing:
::::*   978-0596528126              (good)
::::*   978-0596528120          (bad)
::::*   978-1788399081              (good)
::::*   978-1788399083          (bad)

Show output here, on this page

;See also:
:*   for details:   13-digit ISBN method of validation.       (installs cookies.)

Solution:
describe("ISBN Utilities") {
    mapOf(
        "978-1734314502" to true,
        "978-1734314509" to false,
        "978-1788399081" to true,
        "978-1788399083" to false
    ).forEach { (input, expected) ->
        it("returns $expected for $input") {
            println("$input: ${when(isValidISBN13(input)) {
                true -> "good"
                else -> "bad"
            }}")
            assert(isValidISBN13(input) == expected)
        }
    }
}


I before E except after C

The phrase      "I before E, except after C"     is a
widely known mnemonic which is supposed to help when spelling English words.

;Task:
Using the word list from   http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
:::#   ''"I before E when not preceded by C"''
:::#   ''"E before I when preceded by C"''

If both sub-phrases are plausible then the original phrase can be said to be plausible.

Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).

;Stretch goal:
As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.

''Show your output here as well as your program.''

;cf.:
* Schools to rethink 'i before e' - BBC news, 20 June 2009
* I Before E Except After C - QI Series 8 Ep 14, (humorous)
* Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".

Solution:
// version 1.0.6

import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader

fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2

fun printResults(source: String, counts: IntArray) {
    println("Results for $source")
    println("  i before e except after c")
    println("    for     ${counts[0]}")
    println("    against ${counts[1]}")
    val plausible1 = isPlausible(counts[0], counts[1])
    println("  sub-rule is${if (plausible1) "" else " not"} plausible\n")
    println("  e before i when preceded by c")
    println("    for     ${counts[2]}")
    println("    against ${counts[3]}")
    val plausible2 = isPlausible(counts[2], counts[3])
    println("  sub-rule is${if (plausible2) "" else " not"} plausible\n")
    val plausible = plausible1 && plausible2
    println("  rule is${if (plausible) "" else " not"} plausible")
}

fun main(args: Array<String>) {
    val url = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
    val isr = InputStreamReader(url.openStream())
    val reader = BufferedReader(isr)
    val regexes = arrayOf(
        Regex("(^|[^c])ie"),     // i before e when not preceded by c (includes words starting with ie)
        Regex("(^|[^c])ei"),     // e before i when not preceded by c (includes words starting with ei)
        Regex("cei"),            // e before i when preceded by c
        Regex("cie")             // i before e when preceded by c
    )
    val counts = IntArray(4) // corresponding counts of occurrences
    var word = reader.readLine()
    while (word != null) {
        for (i in 0..3) counts[i] += regexes[i].findAll(word).toList().size
        word = reader.readLine()
    }
    reader.close()
    printResults("unixdict.txt", counts)

    val url2 = URL("http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt")
    val isr2 = InputStreamReader(url2.openStream())
    val reader2 = BufferedReader(isr2)
    val counts2 = IntArray(4)
    reader2.readLine() // read header line
    var line = reader2.readLine() // read first line and store it
    var words: List<String>
    val splitter = Regex("""(\t+|\s+)""")
    while (line != null) {
        words = line.split(splitter)
        if (words.size == 4)  // first element is empty
            for (i in 0..3) counts2[i] += regexes[i].findAll(words[1]).toList().size * words[3].toInt()
        line = reader2.readLine()
    }
    reader2.close()
    println()
    printResults("British National Corpus", counts2)
}


Identity matrix

Build an   identity matrix   of a size known at run-time.

An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''',
where the diagonal elements are all '''1'''s (ones),
and all the other elements are all '''0'''s (zeroes).

I_n = \begin{bmatrix}
  1      & 0      & 0      & \cdots & 0      \\
  0      & 1      & 0      & \cdots & 0      \\
  0      & 0      & 1      & \cdots & 0      \\
  \vdots & \vdots & \vdots & \ddots & \vdots \\
  0      & 0      & 0      & \cdots & 1      \\
\end{bmatrix}

;Related tasks:
*   [[Spiral matrix]]
*   [[Zig-zag matrix]]
*   [[Ulam_spiral_(for_primes)]]

Solution:
// version 1.0.6

fun main(args: Array<String>) {
    print("Enter size of matrix : ")
    val n = readLine()!!.toInt()
    println()
    val identity = Array(n) { IntArray(n) } // create n x n matrix of integers

    // enter 1s in diagonal elements
    for(i in 0 until n) identity[i][i] = 1

    // print identity matrix if n <= 40
    if (n <= 40)
        for (i in 0 until n) println(identity[i].joinToString(" "))
    else
        println("Matrix is too big to display on 80 column console")
}


Idiomatically determine all the characters that can be used for symbols

Idiomatically determine all the characters that can be used for ''symbols''.
The word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.

The method should find the characters regardless of the hardware architecture that is being used  (ASCII, EBCDIC, or other).

;Task requirements

Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.

Note that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance.  These type of restrictions needn't be addressed here (but can be mentioned).

;See also
* Idiomatically determine all the lowercase and uppercase letters.

Solution:
// version 1.1.4-3

typealias CharPredicate = (Char) -> Boolean

fun printChars(msg: String, start: Int, end: Int, limit: Int, p: CharPredicate, asInt: Boolean) {
    print(msg)
    (start until end).map { it.toChar() }
                     .filter { p(it) }
                     .take(limit)
                     .forEach { print(if (asInt) "[${it.toInt()}]" else it) }
    println("...")
}

fun main(args: Array<String>) {
    printChars("Kotlin Identifier start:     ", 0, 0x10FFFF, 72,
                Char::isJavaIdentifierStart, false)

    printChars("Kotlin Identifier part:      ", 0, 0x10FFFF, 25,
                Character::isJavaIdentifierPart, true)

    printChars("Kotlin Identifier ignorable: ", 0, 0x10FFFF, 25,
                Character::isIdentifierIgnorable, true)
}


Idiomatically determine all the lowercase and uppercase letters   (of the Latin [English] alphabet)   being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).

;Task requirements

Display the set of all:
::::::*   lowercase letters
::::::*   uppercase letters

that can be used (allowed) by the computer program,

where   ''letter''   is a member of the Latin (English) alphabet:     '''a''' --> '''z'''     and     '''A''' --> '''Z'''.

You may want to mention what hardware architecture is being used, and if applicable, the operating system.

;See also
* Idiomatically determine all the characters that can be used for symbols.

Solution:
// version 1.0.6

fun main(args: Array<String>) {
    print("Lower case : ")
    for (ch in 'a'..'z') print(ch)
    print("\nUpper case : ")
    for (ch in 'A'..'Z') print(ch)
    println()
}


Imaginary base numbers

Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.

''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search.  [Ref.]''

Other imaginary bases are possible too but are not as widely discussed and aren't specifically named.

'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back.

At a minimum, support quater-imaginary (base 2i).

For extra kudos, support positive or negative bases 2i through 6i (or higher).

As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.

See Wikipedia: Quater-imaginary_base for more details.

For reference, here are some some decimal and complex numbers converted to quater-imaginary.

Base 10
Base 2i

1
 1

2
 2

3
 3

4
 10300

5
 10301

6
 10302

7
 10303

8
 10200

9
 10201

10
 10202

11
 10203

12
 10100

13
 10101

14
 10102

15
 10103

16
 10000

Base 10
Base 2i

-1
 103

-2
 102

-3
 101

-4
 100

-5
 203

-6
 202

-7
 201

-8
 200

-9
 303

-10
 302

-11
 301

-12
 300

-13
 1030003

-14
 1030002

-15
 1030001

-16
 1030000

Base 10
Base 2i

1i
10.2

2i
10.0

3i
20.2

4i
20.0

5i
30.2

6i
30.0

7i
103000.2

8i
103000.0

9i
103010.2

10i
103010.0

11i
103020.2

12i
103020.0

13i
103030.2

14i
103030.0

15i
102000.2

16i
102000.0

Base 10
Base 2i

-1i
0.2

-2i
1030.0

-3i
1030.2

-4i
1020.0

-5i
1020.2

-6i
1010.0

-7i
1010.2

-8i
1000.0

-9i
1000.2

-10i
2030.0

-11i
2030.2

-12i
2020.0

-13i
2020.2

-14i
2010.0

-15i
2010.2

-16i
2000.0

Solution:
// version 1.2.10

import kotlin.math.ceil

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

    constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())

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

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

    operator fun times(other: Double) = Complex(real * other, imag * other)

    fun inv(): Complex {
        val denom = real * real + imag * imag
        return Complex(real / denom, -imag / denom)
    }

    operator fun unaryMinus() = Complex(-real, -imag)

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

    operator fun div(other: Complex) = this * other.inv()

    // only works properly if 'real' and 'imag' are both integral
    fun toQuaterImaginary(): QuaterImaginary {
        if (real == 0.0 && imag == 0.0) return QuaterImaginary("0")
        var re = real.toInt()
        var im = imag.toInt()
        var fi = -1
        val sb = StringBuilder()
        while (re != 0) {
            var rem = re % -4
            re /= -4
            if (rem < 0) {
                rem = 4 + rem
                re++
            }
            sb.append(rem)
            sb.append(0)
        }
        if (im != 0) {
            var f = (Complex(0.0, imag) / Complex(0.0, 2.0)).real
            im = ceil(f).toInt()
            f = -4.0 * (f - im.toDouble())
            var index = 1
            while (im != 0) {
                var rem = im % -4
                im /= -4
                if (rem < 0) {
                    rem = 4 + rem
                    im++
                }
                if (index < sb.length) {
                    sb[index] = (rem + 48).toChar()
                }
                else {
                    sb.append(0)
                    sb.append(rem)
                }
                index += 2
            }
            fi = f.toInt()
        }
        sb.reverse()
        if (fi != -1) sb.append(".$fi")
        var s = sb.toString().trimStart('0')
        if (s.startsWith(".")) s = "0$s"
        return QuaterImaginary(s)
    }

    override fun toString(): String {
        val real2 = if (real == -0.0) 0.0 else real  // get rid of negative zero
        val imag2 = if (imag == -0.0) 0.0 else imag  // ditto
        var result = if (imag2 >= 0.0) "$real2 + ${imag2}i" else "$real2 - ${-imag2}i"
        result = result.replace(".0 ", " ").replace(".0i", "i").replace(" + 0i", "")
        if (result.startsWith("0 + ")) result = result.drop(4)
        if (result.startsWith("0 - ")) result = "-" + result.drop(4)
        return result
    }
}

class QuaterImaginary(val b2i: String) {

    init {
        if (b2i == "" || !b2i.all { it in "0123." } || b2i.count { it == '.'} > 1 )
            throw RuntimeException("Invalid Base 2i number")
    }

    fun toComplex(): Complex {
        val pointPos = b2i.indexOf(".")
        var posLen = if (pointPos != -1) pointPos else b2i.length
        var sum = Complex(0.0, 0.0)
        var prod = Complex(1.0, 0.0)
        for (j in 0 until posLen) {
            val k = (b2i[posLen - 1 - j] - '0').toDouble()
            if (k > 0.0) sum += prod * k
            prod *= twoI
        }
        if (pointPos != -1) {
            prod = invTwoI
            for (j in posLen + 1 until b2i.length) {
                val k = (b2i[j] - '0').toDouble()
                if (k > 0.0) sum += prod * k
                prod *= invTwoI
            }
        }
        return sum
    }

    override fun toString() = b2i

    companion object {
        val twoI = Complex(0.0, 2.0)
        val invTwoI = twoI.inv()
    }
}

fun main(args: Array<String>) {
    val fmt = "%4s -> %8s -> %4s"
    for (i in 1..16) {
        var c1 = Complex(i, 0)
        var qi = c1.toQuaterImaginary()
        var c2 = qi.toComplex()
        print("$fmt     ".format(c1, qi, c2))
        c1 = -c1
        qi = c1.toQuaterImaginary()
        c2 = qi.toComplex()
        println(fmt.format(c1, qi, c2))
    }
    println()
    for (i in 1..16) {
        var c1 = Complex(0, i)
        var qi = c1.toQuaterImaginary()
        var c2 = qi.toComplex()
        print("$fmt     ".format(c1, qi, c2))
        c1 = -c1
        qi = c1.toQuaterImaginary()
        c2 = qi.toComplex()
        println(fmt.format(c1, qi, c2))
    }
}


Include a file

Demonstrate the language's ability to include source code from other files.

;See Also

* [[Compiler/Simple file inclusion pre processor]]

Solution:
// version 1.1.2

import package1.f // import f from package `package1`

fun main(args: Array<String>) {
    f()  // invoke f without qualification
}


Index finite lists of positive integers

It is known that the set of finite lists of positive integers is    countable.

This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.

;Task:
Implement such a mapping:
:*   write a function     ''rank''     which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.
:*   write a function          ''unrank''        which is the   ''rank''    inverse function.

Demonstrate your solution by:
:*   picking a random-length list of random positive integers
:*   turn it into an integer,   and
:*   get the list back.

There are many ways to do this.   Feel free to choose any one you like.

;Extra credit:
Make the   ''rank''   function as a    bijection   and show   ''unrank(n)''   for   '''n'''   varying from   '''0'''   to   '''10'''.

Solution:
// version 1.1.2

import java.math.BigInteger

/* Separates each integer in the list with an 'a' then encodes in base 11. Empty list mapped to '-1' */
fun rank(li: List<Int>) = when (li.size) {
    0    -> -BigInteger.ONE
    else ->  BigInteger(li.joinToString("a"), 11)
}

fun unrank(r: BigInteger) = when (r) {
    -BigInteger.ONE -> emptyList<Int>()
    else            -> r.toString(11).split('a').map { if (it != "") it.toInt() else 0 }
}

/* Each integer n in the list mapped to '1' plus n '0's. Empty list mapped to '0' */
fun rank2(li:List<Int>): BigInteger {
    if (li.isEmpty()) return BigInteger.ZERO
    val sb = StringBuilder()
    for (i in li) sb.append("1" + "0".repeat(i))
    return BigInteger(sb.toString(), 2)
}

fun unrank2(r: BigInteger) = when (r) {
    BigInteger.ZERO -> emptyList<Int>()
    else            -> r.toString(2).drop(1).split('1').map { it.length }
}

fun main(args: Array<String>) {
    var li: List<Int>
    var r: BigInteger
    li = listOf(0, 1, 2, 3, 10, 100, 987654321)
    println("Before ranking   : $li")
    r = rank(li)
    println("Rank = $r")
    li = unrank(r)
    println("After unranking  : $li")

    println("\nAlternative approach (not suitable for large numbers)...\n")
    li = li.dropLast(1)
    println("Before ranking   : $li")
    r = rank2(li)
    println("Rank = $r")
    li = unrank2(r)
    println("After unranking  : $li")

    println()
    for (i in 0..10) {
        val bi = BigInteger.valueOf(i.toLong())
        li = unrank2(bi)
        println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
    }
}


Integer overflow

Some languages support one or more integer types of the underlying processor.

This integer types have fixed size;   usually   '''8'''-bit,   '''16'''-bit,   '''32'''-bit,   or   '''64'''-bit.
The integers supported by such a type can be   ''signed''   or   ''unsigned''.

Arithmetic for machine level integers can often be done by single CPU instructions.
This allows high performance and is the main reason to support machine level integers.

;Definition:
An integer overflow happens when the result of a computation does not fit into the fixed size integer.
The result can be too small or too big to be representable in the fixed size integer.

;Task:
When a language has fixed size integer types, create a program that
does arithmetic computations for the fixed size integers of the language.

These computations must be done such that the result would overflow.

The program should demonstrate what the following expressions do.

For 32-bit signed integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit signed integer
|-
| -(-2147483647-1)
| 2147483648
|-
| 2000000000 + 2000000000
| 4000000000
|-
| -2147483647 - 2147483647
| -4294967294
|-
| 46341 * 46341
| 2147488281
|-
| (-2147483647-1) / -1
| 2147483648
|}

For 64-bit signed integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit signed integer
|-
| -(-9223372036854775807-1)
| 9223372036854775808
|-
| 5000000000000000000+5000000000000000000
| 10000000000000000000
|-
| -9223372036854775807 - 9223372036854775807
| -18446744073709551614
|-
| 3037000500 * 3037000500
| 9223372037000250000
|-
| (-9223372036854775807-1) / -1
| 9223372036854775808
|}

For 32-bit unsigned integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit unsigned integer
|-
| -4294967295
| -4294967295
|-
| 3000000000 + 3000000000
| 6000000000
|-
| 2147483647 - 4294967295
| -2147483648
|-
| 65537 * 65537
| 4295098369
|}

For 64-bit unsigned integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit unsigned integer
|-
| -18446744073709551615
| -18446744073709551615
|-
| 10000000000000000000 + 10000000000000000000
| 20000000000000000000
|-
| 9223372036854775807 - 18446744073709551615
| -9223372036854775808
|-
| 4294967296 * 4294967296
| 18446744073709551616
|}

;Notes:
:*   When the integer overflow does trigger an exception show how the exception is caught.
:*   When the integer overflow produces some value,   print it.
:*   It should be explicitly noted when an integer overflow is not recognized,   the program continues with wrong results.
:*   This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
:*   When a language has no fixed size integer type,   or when no integer overflow can occur for other reasons,   this should be noted.
:*   It is okay to mention,   when a language supports unlimited precision integers,   but this task is NOT the place to demonstrate the   capabilities of unlimited precision integers.

Solution:
// The Kotlin compiler can detect expressions of signed constant integers that will overflow.
// It cannot detect unsigned integer overflow, however.
@Suppress("INTEGER_OVERFLOW")
fun main() {
    println("*** Signed 32 bit integers ***\n")
    println(-(-2147483647 - 1))
    println(2000000000 + 2000000000)
    println(-2147483647 - 2147483647)
    println(46341 * 46341)
    println((-2147483647 - 1) / -1)
    println("\n*** Signed 64 bit integers ***\n")
    println(-(-9223372036854775807 - 1))
    println(5000000000000000000 + 5000000000000000000)
    println(-9223372036854775807 - 9223372036854775807)
    println(3037000500 * 3037000500)
    println((-9223372036854775807 - 1) / -1)
    println("\n*** Unsigned 32 bit integers ***\n")
//    println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator
//    println(0U - 4294967295U) // this works
    println((-4294967295).toUInt()) // converting from the signed Int type also produces the overflow; this is intended behavior of toUInt()
    println(3000000000U + 3000000000U)
    println(2147483647U - 4294967295U)
    println(65537U * 65537U)
    println("\n*** Unsigned 64 bit integers ***\n")
    println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction
    println(10000000000000000000U + 10000000000000000000U)
    println(9223372036854775807U - 18446744073709551615U)
    println(4294967296U * 4294967296U)
}


Integer sequence

Create a program that, when run, would display all integers from   '''1'''   to    '''    '''    (or any relevant implementation limit),   in sequence   (i.e.   1, 2, 3, 4, etc)   if given enough time.

An example may not be able to reach arbitrarily-large numbers based on implementations limits.   For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295.   Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.

If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.

Solution:
import java.math.BigInteger

// version 1.0.5-2

fun main(args: Array<String>) {
    // print until 2147483647
    (0..Int.MAX_VALUE).forEach { println(it) }

    // print forever
    var n = BigInteger.ZERO
    while (true) {
        println(n)
        n += BigInteger.ONE
    }
}


Intersecting number wheels

A number wheel has:
* A ''name'' which is an uppercase letter.
* A set of ordered ''values'' which are either ''numbers'' or ''names''.

A ''number'' is generated/yielded from a named wheel by:
:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":
::1.a If the value is a number, yield it.
::1.b If the value is a name, yield the next value from the named wheel
::1.c Advance the position of this wheel.

Given the wheel
: A: 1 2 3
the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...

'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.

;Examples:
Given the wheels:
    A: 1 B 2
    B: 3 4
The series of numbers generated starts:
    1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...

The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.

'''Note:''' If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.

E.g.
  A:  1 D D
  D:  6 7 8
  Generates:
    1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...

;Task:
Generate and show the first twenty terms of the sequence of numbers generated
from these groups:

    Intersecting Number Wheel group:
      A:  1 2 3

    Intersecting Number Wheel group:
      A:  1 B 2
      B:  3 4

    Intersecting Number Wheel group:
      A:  1 D D
      D:  6 7 8

    Intersecting Number Wheel group:
      A:  1 B C
      B:  3 4
      C:  5 B

Show your output here, on this page.

Solution:
import java.util.Collections
import java.util.stream.IntStream

object WheelController {
    private val IS_NUMBER = "[0-9]".toRegex()
    private const val TWENTY = 20
    private var wheelMap = mutableMapOf<String, WheelModel>()

    private fun advance(wheel: String) {
        val w = wheelMap[wheel]
        if (w!!.list[w.position].matches(IS_NUMBER)) {
            w.printThePosition()
        } else {
            val wheelName = w.list[w.position]
            advance(wheelName)
        }
        w.advanceThePosition()
    }

    private fun run() {
        println(wheelMap)
        IntStream.rangeClosed(1, TWENTY)
            .forEach { advance("A") }
        println()
        wheelMap.clear()
    }

    @JvmStatic
    fun main(args: Array<String>) {
        wheelMap["A"] = WheelModel("1", "2", "3")
        run()
        wheelMap["A"] = WheelModel("1", "B", "2")
        wheelMap["B"] = WheelModel("3", "4")
        run()
        wheelMap["A"] = WheelModel("1", "D", "D")
        wheelMap["D"] = WheelModel("6", "7", "8")
        run()
        wheelMap["A"] = WheelModel("1", "B", "C")
        wheelMap["B"] = WheelModel("3", "4")
        wheelMap["C"] = WheelModel("5", "B")
        run()
    }
}

internal class WheelModel(vararg values: String?) {
    var list = mutableListOf<String>()
    var position: Int
    private var endPosition: Int

    override fun toString(): String {
        return list.toString()
    }

    fun advanceThePosition() {
        if (position == endPosition) {
            position = INITIAL // new beginning
        } else {
            position++ // advance position
        }
    }

    fun printThePosition() {
        print(" ${list[position]}")
    }

    companion object {
        private const val INITIAL = 0
    }

    init {
        Collections.addAll<String>(list, *values)
        position = INITIAL
        endPosition = list.size - 1
    }
}


Inverted syntax

'''Inverted syntax with conditional expressions'''

In traditional syntax conditional expressions are usually shown before the action within a statement or code block:

 IF raining=true THEN needumbrella=true

In inverted syntax, the action is listed before the conditional expression in the statement or code block:

 needumbrella=true IF raining=true

'''Inverted syntax with assignment'''

In traditional syntax, assignments are usually expressed with the variable appearing before the expression:

 a = 6

In inverted syntax, the expression appears before the variable:
 6 = a

'''Task'''

The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.

Solution:
// version 1.0.6

infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this

fun main(args: Array<String>) {
    val raining = true
    val needUmbrella = true iif (raining)
    println("Do I need an umbrella?  ${if(needUmbrella) "Yes" else "No"}")
}


Isqrt (integer square root) of X

Sometimes a function is needed to find the integer square root of   '''X''',   where   '''X'''   can be a
real non-negative number.

Often   '''X'''   is actually a non-negative integer.

For the purposes of this task,   '''X'''   can be an integer or a real number,   but if it
simplifies things in your computer programming language,   assume it's an integer.

One of the most common uses of   '''Isqrt'''   is in the division of an integer by all factors   (or
primes)   up to the
 X     of that
integer,   either to find the factors of that integer,   or to determine primality.

An alternative method for finding the   '''Isqrt'''   of a number is to
calculate:        floor( sqrt(X) )
::*   where    '''sqrt'''    is the   square root   function for non-negative real numbers,   and
::*   where   '''floor'''         is the   floor         function for real numbers.

If the hardware supports the computation of (real) square roots,   the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.

However, floating point arithmetic is limited in the number of   (binary or decimal)   digits that it can support.

;Pseudo-code using quadratic residue:
For this task, the integer square root of a non-negative number will be computed using a version
of   ''quadratic residue'',   which has the advantage that no   ''floating point''   calculations are
used,   only integer arithmetic.

Furthermore, the two divisions can be performed by bit shifting,   and the one multiplication can also be be performed by bit shifting or additions.

The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.

Pseudo-code of a procedure for finding the integer square root of   '''X'''       (all variables are integers):
          q <-- 1                                /*initialize  Q  to unity.  */
                                   /*find a power of 4 that's greater than X.*/
                   perform  while q <= x         /*perform while  Q <= X.    */
                   q <-- q * 4                   /*multiply  Q  by  four.    */
                   end  /*perform*/
                                                 /*Q  is now greater than  X.*/
          z <-- x                                /*set  Z  to the value of X.*/
          r <-- 0                                /*initialize  R  to zero.   */
                   perform  while q > 1          /*perform while  Q > unity. */
                   q <-- q / 4                   /*integer divide by  four.  */
                   t <-- z - r - q               /*compute value of  T.      */
                   r <-- r / 2                   /*integer divide by  two.   */
                   if t >= 0  then do
                                   z <-- t       /*set  Z  to value of  T.   */
                                   r <-- r + q   /*compute new value of  R.  */
                                   end
                   end  /*perform*/
                                                 /*R  is now the  Isqrt(X).  */

          /* Sidenote: Also, Z is now the remainder after square root (i.e.  */
          /*           R^2 + Z = X, so if Z = 0 then X is a perfect square). */

Another version for the (above)   1st   '''perform'''   is:
                   perform  until q > X          /*perform until  Q > X.     */
                   q <-- q * 4                   /*multiply  Q  by  four.    */
                   end  /*perform*/

Integer square roots of some values:
 Isqrt( 0)  is   0               Isqrt(60)  is  7                Isqrt( 99)  is   9
 Isqrt( 1)  is   1               Isqrt(61)  is  7                Isqrt(100)  is  10
 Isqrt( 2)  is   1               Isqrt(62)  is  7                Isqrt(102)  is  10
 Isqrt( 3)  is   1               Isqrt(63)  is  7
 Isqrt( 4)  is   2               Isqrt(64)  is  8                Isqet(120)  is  10
 Isqrt( 5)  is   2               Isqrt(65)  is  8                Isqrt(121)  is  11
 Isqrt( 6)  is   2               Isqrt(66)  is  8                Isqrt(122)  is  11
 Isqrt( 7)  is   2               Isqrt(67)  is  8
 Isqrt( 8)  is   2               Isqrt(68)  is  8                Isqrt(143)  is  11
 Isqrt( 9)  is   3               Isqrt(69)  is  8                Isqrt(144)  is  12
 Isqrt(10)  is   3               Isqrt(70)  is  8                Isqrt(145)  is  12

;Task:
Compute and show all output here   (on this page)   for:
::*   the Isqrt of the     integers     from     '''0''' ---> '''65'''                (inclusive), shown in a       horizontal       format.
::*   the Isqrt of the   odd powers               from          '''71''' ---> '''773'''   (inclusive), shown in a   vertical   format.
::*   use commas in the displaying of larger numbers.

You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.
If your computer programming language only supports smaller integers,   show what you can.

;Related tasks:
:*   sequence of non-squares
:*   integer roots
:*   square root by hand

Solution:
import java.math.BigInteger

fun isqrt(x: BigInteger): BigInteger {
    if (x < BigInteger.ZERO) {
        throw IllegalArgumentException("Argument cannot be negative")
    }
    var q = BigInteger.ONE
    while (q <= x) {
        q = q.shiftLeft(2)
    }
    var z = x
    var r = BigInteger.ZERO
    while (q > BigInteger.ONE) {
        q = q.shiftRight(2)
        var t = z
        t -= r
        t -= q
        r = r.shiftRight(1)
        if (t >= BigInteger.ZERO) {
            z = t
            r += q
        }
    }
    return r
}

fun main() {
    println("The integer square root of integers from 0 to 65 are:")
    for (i in 0..65) {
        print("${isqrt(BigInteger.valueOf(i.toLong()))} ")
    }
    println()

    println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:")
    println("power                                    7 ^ power                                                 integer square root")
    println("----- --------------------------------------------------------------------------------- -----------------------------------------")
    var pow7 = BigInteger.valueOf(7)
    val bi49 = BigInteger.valueOf(49)
    for (i in (1..73).step(2)) {
        println("%2d %,84d %,41d".format(i, pow7, isqrt(pow7)))
        pow7 *= bi49
    }
}


Iterated digits squaring

If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1

An example in Python:

>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]

;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.

This problem derives from the Project Euler problem 92.

For a quick algorithm for this task see the talk page

;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]

Solution:
// version 1.0.6

fun endsWith89(n: Int): Boolean {
    var digit: Int
    var sum = 0
    var nn = n
    while (true) {
        while (nn > 0) {
            digit = nn % 10
            sum += digit * digit
            nn /= 10
        }
        if (sum == 89) return true
        if (sum == 1) return false
        nn = sum
        sum  = 0
    }
}

fun main(args: Array<String>) {
    val sums = IntArray(8 * 81 + 1)
    sums[0] = 1
    sums[1] = 0
    var s: Int
    for (n in 1 .. 8)
        for (i in n * 81 downTo 1)
            for (j in 1 .. 9) {
                s = j * j
                if (s > i) break
                sums[i] += sums[i - s]
            }
    var count89 = 0
    for (i in 1 .. 8 * 81)
        if (endsWith89(i)) count89 += sums[i]
    println("There are $count89 numbers from 1 to 100 million ending with 89")
}


JSON

Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.

Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).

Solution:
// version 1.2.21

data class JsonObject(val foo: Int, val bar: Array<String>)

data class JsonObject2(val ocean: String, val blue: Array<Int>)

fun main(args: Array<String>) {
    // JSON to object
    val data: JsonObject = JSON.parse("""{ "foo": 1, "bar": ["10", "apples"] }""")
    println(JSON.stringify(data))

    // object to JSON
    val data2 = JsonObject2("water", arrayOf(1, 2))
    println(JSON.stringify(data2))
}


Jacobi symbol

The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of  a ^ ((p-1)/2) (mod p)
* (a | p)     1      if a is a square (mod p)
* (a | p)         -1      if a is not a square (mod p)
* (a | p)     0      if a  0

If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).

;Task:
Calculate the Jacobi symbol (a | n).

;Reference:
* Wikipedia article on Jacobi symbol.

Solution:
fun jacobi(A: Int, N: Int): Int {
    assert(N > 0 && N and 1 == 1)
    var a = A % N
    var n = N
    var result = 1
    while (a != 0) {
        var aMod4 = a and 3
        while (aMod4 == 0) {    // remove factors of four
            a = a shr 2
            aMod4 = a and 3
        }
        if (aMod4 == 2) {       // if even
            a = a shr 1         // remove factor 2 and possibly change sign
            if ((n and 7).let { it == 3 || it == 5 })
                result = -result
            aMod4 = a and 3
        }
        if (aMod4 == 3 && n and 3 == 3)
            result = -result
        a = (n % a).also { n = a }
    }
    return if (n == 1) result else 0
}


Jaro similarity

The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that   '''0'''   equates to no similarities and   '''1'''   is an exact match.

;;Definition

The Jaro similarity   d_j   of two given strings   s_1   and   s_2   is

: d_j = \left\{

\begin{array}{l l}
  0 & \text{if }m = 0\\
  \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right.

Where:

* m   is the number of ''matching characters'';
* t   is half the number of ''transpositions''.

Two characters from   s_1   and   s_2   respectively, are considered ''matching'' only if they are the same and not farther apart than   \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters.

Each character of   s_1   is compared with all its matching characters in   s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.

;;Example

Given the strings   s_1   ''DWAYNE''   and   s_2   ''DUANE''   we find:

* m = 4
* |s_1| = 6
* |s_2| = 5
* t = 0

We find a Jaro score of:

: d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822

;Task

Implement the Jaro algorithm and show the similarity scores for each of the following pairs:

* ("MARTHA", "MARHTA")
* ("DIXON", "DICKSONX")
* ("JELLYFISH", "SMELLYFISH")

; See also
* Jaro-Winkler distance on Wikipedia.

Solution:
object Jaro {
    fun distance(s1: String, s2: String): Double {
        val s1_len = s1.length
        val s2_len = s2.length
        if (s1_len == 0 && s2_len == 0) return 1.0
        val match_distance = Math.max(s1_len, s2_len) / 2 - 1
        val s1_matches = BooleanArray(s1_len)
        val s2_matches = BooleanArray(s2_len)
        var matches = 0
        for (i in 0..s1_len - 1) {
            val start = Math.max(0, i - match_distance)
            val end = Math.min(i + match_distance + 1, s2_len)
            (start..end - 1).find { j -> !s2_matches[j] && s1[i] == s2[j] } ?. let {
                s1_matches[i] = true
                s2_matches[it] = true
                matches++
            }
        }
        if (matches == 0) return 0.0
        var t = 0.0
        var k = 0
        (0..s1_len - 1).filter { s1_matches[it] }.forEach { i ->
            while (!s2_matches[k]) k++
            if (s1[i] != s2[k]) t += 0.5
            k++
        }

        val m = matches.toDouble()
        return (m / s1_len + m / s2_len + (m - t) / m) / 3.0
    }
}

fun main(args: Array<String>) {
    println(Jaro.distance("MARTHA", "MARHTA"))
    println(Jaro.distance("DIXON", "DICKSONX"))
    println(Jaro.distance("JELLYFISH", "SMELLYFISH"))
}


Jewels and stones

Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.

Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.

The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.

Note that:
:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
:# The parameters do not need to have exactly the same names.
:# Validating the arguments is unnecessary.

So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.

This task was inspired by this problem.

Solution:
// Version 1.2.40

fun countJewels(s: String, j: String) = s.count { it in j }

fun main(args: Array<String>) {
    println(countJewels("aAAbbbb", "aA"))
    println(countJewels("ZZ", "z"))
}


Julia set

Task
Generate and draw a Julia set.

;Related tasks
*   Mandelbrot Set

Solution:
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.JFrame
import javax.swing.JPanel

class JuliaPanel : JPanel() {
    init {
        preferredSize = Dimension(800, 600)
        background = Color.white
    }

    private val maxIterations = 300
    private val zoom = 1
    private val moveX = 0.0
    private val moveY = 0.0
    private val cX = -0.7
    private val cY = 0.27015

    public override fun paintComponent(graphics: Graphics) {
        super.paintComponent(graphics)
        with(graphics as Graphics2D) {
            setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
            val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
            (0 until width).forEach { x ->
                (0 until height).forEach { y ->
                    var zx = 1.5 * (x - width / 2) / (0.5 * zoom * width) + moveX
                    var zy = (y - height / 2) / (0.5 * zoom * height) + moveY
                    var i = maxIterations.toFloat()
                    while (zx * zx + zy * zy < 4 && i > 0) {
                        val tmp = zx * zx - zy * zy + cX
                        zy = 2.0 * zx * zy + cY
                        zx = tmp
                        i--
                    }
                    image.setRGB(x, y, Color.HSBtoRGB(maxIterations / i % 1, 1f, (if (i > 0) 1 else 0).toFloat()))
                }
            }
            drawImage(image, 0, 0, null)
        }
    }
}

fun main() {
    with(JFrame()) {
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        title = "Julia Set"
        isResizable = false
        add(JuliaPanel(), BorderLayout.CENTER)
        pack()
        setLocationRelativeTo(null)
        isVisible = true
    }
}


Jump anywhere

Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.

This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!

* Some languages can ''go to'' any global label in a program.
* Some languages can break multiple function calls, also known as ''unwinding the call stack''.
* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).

These jumps are not all alike.
A simple ''goto'' never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.

;Task:
Use your language to demonstrate the various types of jumps that it supports.

Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].

Solution:
// version 1.0.6

fun main(args: Array<String>) {
    intArrayOf(4, 5, 6).forEach lambda@ {
        if (it == 5) return@lambda
        println(it)
    }
    println()
    loop@ for (i in 0 .. 3) {
        for (j in 0 .. 3) {
            if (i + j == 4) continue@loop
            if (i + j == 5) break@loop
            println(i + j)
        }
    }
}


K-d tree

{{wikipedia|K-d tree}}

A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches).
k-d trees are a special case of binary space partitioning trees.

k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N''  2''k''.
Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.

'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:

# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].
# 1000 3-d points uniformly distributed in a 3-d cube.

For the Wikipedia example, find the nearest neighbor to point (9, 2)
For the random data, pick a random location and find the nearest neighbor.

In addition, instrument your code to count the number of nodes visited in the nearest neighbor search.  Count a node as visited if any field of it is accessed.

Output should show the point searched for, the point found,
the distance to the point, and the number of nodes visited.

There are variant algorithms for constructing the tree.
You can use a simple median strategy or implement something more efficient.
Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches.
You do not have to implement these.
The requirement for this task is specifically the nearest single neighbor.
Also there are algorithms for inserting, deleting, and balancing k-d trees.
These are also not required for the task.

Solution:
// version 1.1.51

import java.util.Random

typealias Point = DoubleArray

fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()

class HyperRect (val min: Point, val max: Point) {
    fun copy() = HyperRect(min.copyOf(), max.copyOf())
}

data class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodesVisited: Int)

class KdNode(
    val domElt: Point,
    val split: Int,
    var left:  KdNode?,
    var right: KdNode?
)

class KdTree {
    val n: KdNode?
    val bounds: HyperRect

    constructor(pts: MutableList<Point>, bounds: HyperRect) {
        fun nk2(exset: MutableList<Point>, split: Int): KdNode? {
            if (exset.size == 0) return null
            val exset2 = exset.sortedBy { it[split] }
            for (i in 0 until exset.size) exset[i] = exset2[i]
            var m = exset.size / 2
            val d = exset[m]
            while (m + 1 < exset.size && exset[m + 1][split] == d[split]) m++
            var s2 = split + 1
            if (s2 == d.size) s2 = 0
            return KdNode(
                d,
                split,
                nk2(exset.subList(0, m), s2),
                nk2(exset.subList(m + 1, exset.size), s2)
            )
        }
        this.n = nk2(pts, 0)
        this.bounds = bounds
    }

    fun nearest(p: Point) = nn(n, p, bounds, Double.POSITIVE_INFINITY)

    private fun nn(
        kd: KdNode?,
        target: Point,
        hr: HyperRect,
        maxDistSqd: Double
    ): NearestNeighbor {
        if (kd == null) return NearestNeighbor(null, Double.POSITIVE_INFINITY, 0)
        var nodesVisited = 1
        val s = kd.split
        val pivot = kd.domElt
        val leftHr = hr.copy()
        val rightHr = hr.copy()
        leftHr.max[s] = pivot[s]
        rightHr.min[s] = pivot[s]
        val targetInLeft = target[s] <= pivot[s]
        val nearerKd = if (targetInLeft) kd.left else kd.right
        val nearerHr = if (targetInLeft) leftHr else rightHr
        val furtherKd = if (targetInLeft) kd.right else kd.left
        val furtherHr = if (targetInLeft) rightHr else leftHr
        var (nearest, distSqd, nv) = nn(nearerKd, target, nearerHr, maxDistSqd)
        nodesVisited += nv
        var maxDistSqd2 = if (distSqd < maxDistSqd) distSqd else maxDistSqd
        var d = pivot[s] - target[s]
        d *= d
        if (d > maxDistSqd2) return NearestNeighbor(nearest, distSqd, nodesVisited)
        d = pivot.sqd(target)
        if (d < distSqd) {
            nearest = pivot
            distSqd = d
            maxDistSqd2 = distSqd
        }
        val temp = nn(furtherKd, target, furtherHr, maxDistSqd2)
        nodesVisited += temp.nodesVisited
        if (temp.distSqd < distSqd) {
            nearest = temp.nearest
            distSqd = temp.distSqd
        }
        return NearestNeighbor(nearest, distSqd, nodesVisited)
    }
}

val rand = Random()

fun randomPt(dim: Int) = Point(dim) { rand.nextDouble() }

fun randomPts(dim: Int, n: Int) = MutableList<Point>(n) { randomPt(dim) }

fun showNearest(heading: String, kd: KdTree, p: Point) {
    println("$heading:")
    println("Point            : ${p.asList()}")
    val (nn, ssq, nv) = kd.nearest(p)
    println("Nearest neighbor : ${nn?.asList()}")
    println("Distance         : ${Math.sqrt(ssq)}")
    println("Nodes visited    : $nv")
    println()
}

fun main(args: Array<String>) {
    val points = mutableListOf(
        doubleArrayOf(2.0, 3.0),
        doubleArrayOf(5.0, 4.0),
        doubleArrayOf(9.0, 6.0),
        doubleArrayOf(4.0, 7.0),
        doubleArrayOf(8.0, 1.0),
        doubleArrayOf(7.0, 2.0)
    )
    var hr = HyperRect(doubleArrayOf(0.0, 0.0), doubleArrayOf(10.0, 10.0))
    var kd = KdTree(points, hr)
    showNearest("WP example data", kd, doubleArrayOf(9.0, 2.0))

    hr = HyperRect(doubleArrayOf(0.0, 0.0, 0.0), doubleArrayOf(1.0, 1.0, 1.0))
    kd = KdTree(randomPts(3, 1000), hr)
    showNearest("1000 random 3D points", kd, randomPt(3))

    hr = hr.copy()
    kd = KdTree(randomPts(3, 400_000), hr)
    showNearest("400,000 random 3D points", kd, randomPt(3))
}


Kaprekar numbers

A positive integer is a Kaprekar number if:
* It is   '''1'''     (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.

;Example Kaprekar numbers:
* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.
* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....

;Example process:
10000 (1002) splitting from left to right:
* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.
* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.

;Task:
Generate and show all Kaprekar numbers less than 10,000.

;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.

;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.

For this purpose, do the following:
* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);
* Display each of them in base 10 representation;
* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square.

For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225   d4  a52g  a5 + 2g

;Reference:
* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version

;Related task:
*   [[Casting out nines]]

Solution:
import java.lang.Long.parseLong
import java.lang.Long.toString

fun String.splitAt(idx: Int): Array<String> {
    val ans = arrayOf(substring(0, idx), substring(idx))
    if (ans.first() == "") ans[0] = "0" // parsing "" throws an exception
    return ans
}

fun Long.getKaprekarParts(sqrStr:  String, base: Int): Array<String>? {
    for (j in 0..sqrStr.length / 2) {
        val parts = sqrStr.splitAt(j)
        val (first, second) = parts.map { parseLong(it, base) }

        // if the right part is all zeroes, then it will be forever, so break
        if (second == 0L) return null
        if (first + second == this) return parts
    }
    return null
}

fun main(args: Array<String>) {
    val base = if (args.isNotEmpty()) args[0].toInt() else 10
    var count = 0
    val max = 1000000L
    for (i in 1..max) {
        val s = toString(i * i, base)
        val p = i.getKaprekarParts(s, base)
        if (p != null) {
            println("%6d\t%6s\t%12s\t%7s + %7s".format(i, toString(i, base), s, p[0], p[1]))
            count++
        }
    }
    println("$count Kaprekar numbers < $max (base 10) in base $base")
}


Kernighans large earthquake problem

Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.

;Problem:
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.

Example lines from the file would be lines like:
8/27/1883    Krakatoa            8.8
5/18/1980    MountStHelens       7.6
3/13/2009    CostaRica           5.1

;Task:
* Create a program or script invocation to find all the events with magnitude greater than 6
* Assuming an appropriate name e.g. "data.txt" for the file:
:# Either: Show how your program is invoked to process a data file of that name.
:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).

Solution:
// Version 1.2.40

import java.io.File

fun main(args: Array<String>) {
    val r = Regex("""\s+""")
    println("Those earthquakes with a magnitude > 6.0 are:\n")
    File("data.txt").forEachLine {
        if (it.split(r)[2].toDouble() > 6.0) println(it)
    }
}


Keyboard input/Obtain a Y or N response

Obtain a valid   '''Y'''   or   '''N'''   response from the [[input device::keyboard]].

The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   '''Y'''   or   '''N'''   key-press from being evaluated.

The response should be obtained as soon as   '''Y'''   or   '''N'''   are pressed, and there should be no need to press an   enter   key.

Solution:
// version 1.0.6

import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities

class Test: JFrame() {
    init {
        while (System.`in`.available() > 0) System.`in`.read()
        println("Do you want to quit Y/N")
        addKeyListener(object: KeyAdapter() {
            override fun keyPressed(e: KeyEvent) {
                if (e.keyCode == KeyEvent.VK_Y) {
                    println("OK, quitting")
                    quit()
                } else if (e.keyCode == KeyEvent.VK_N) {
                    println("N was pressed but the program is about to end anyway")
                    quit()
                } else {
                    println("Only Y/N are acceptable, please try again")
                }
            }
        })
    }

    private fun quit() {
        isVisible = false
        dispose()
        System.exit(0)
    }
}

fun main(args: Array<String>) {
    SwingUtilities.invokeLater {
        val f = Test()
        f.isFocusable = true
        f.isVisible = true
    }
}


Knight's tour

Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square.   Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.

Input and output may be textual or graphical, according to the conventions of the programming environment.  If textual, squares should be indicated in algebraic notation.  The output should indicate the order in which the knight visits the squares, starting with the initial position.  The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.

Input: starting square

Output: move sequence

;Related tasks
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]

Solution:
data class Square(val x : Int, val y : Int)

val board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) })
val axisMoves = arrayOf(1, 2, -1, -2)

fun <T> allPairs(a: Array<T>) = a.flatMap { i -> a.map { j -> Pair(i, j) } }

fun knightMoves(s : Square) : List<Square> {
    val moves = allPairs(axisMoves).filter{ Math.abs(it.first) != Math.abs(it.second) }
    fun onBoard(s : Square) = board.any {it == s}
    return moves.map { Square(s.x + it.first, s.y + it.second) }.filter(::onBoard)
}

fun knightTour(moves : List<Square>) : List<Square> {
    fun findMoves(s: Square) = knightMoves(s).filterNot { m -> moves.any { it == m } }
    val newSquare = findMoves(moves.last()).minBy { findMoves(it).size }
    return if (newSquare == null) moves else knightTour(moves + newSquare)
}

fun knightTourFrom(start : Square) = knightTour(listOf(start))

fun main(args : Array<String>) {
    var col = 0
    for ((x, y) in knightTourFrom(Square(1, 1))) {
        System.out.print("$x,$y")
        System.out.print(if (col == 7) "\n" else " ")
        col = (col + 1) % 8
    }
}


Knuth's algorithm S

This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained  for all successive items > n as they become available (although the content of successive samples can change).

;The algorithm:
:* Select the first n items as the sample as they become available;
:* For the i-th item where i > n, have a random chance of n/i of keeping it.  If failing this chance, the sample remains the same.  If not, have it randomly (1/n) replace one of the previously selected n items of the sample.
:* Repeat   2nd step   for any subsequent items.

;The Task:
:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.
:* Function  s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.
:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:
:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.
:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.

Note: A class taking n and generating a callable instance/function might also be used.

;Reference:
* The Art of Computer Programming, Vol 2, 3.4.2 p.142

;Related tasks:
* [[One of n lines in a file]]
* [[Accumulator factory]]

Solution:
// version 1.2.51

import java.util.Random

val rand = Random()

class SOfN<T>(val n: Int) {
    private val sample = ArrayList<T>(n)
    private var i = 0

    fun process(item: T): List<T> {
        if (++i <= n)
            sample.add(item)
        else if (rand.nextInt(i) < n)
            sample[rand.nextInt(n)] = item
        return sample
    }
}

fun main(args: Array<String>) {
    val bin = IntArray(10)
    (1..100_000).forEach {
        val sOfn = SOfN<Int>(3)
        for (d in 0..8) sOfn.process(d)
        for (s in sOfn.process(9)) bin[s]++
    }
    println(bin.contentToString())
}


Koch curve

Draw a Koch curve. See details: Koch curve

Solution:
// Version 1.2.41

import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import kotlin.math.*
import java.io.File
import javax.imageio.ImageIO

val Double.asI get() = this.toInt()

class Point(var x: Int, var y: Int)

class BasicBitmapStorage(width: Int, height: Int) {
    val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)

    fun fill(c: Color) {
        val g = image.graphics
        g.color = c
        g.fillRect(0, 0, image.width, image.height)
    }

    fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())

    fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))

    fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) {
        val dx = abs(x1 - x0)
        val dy = abs(y1 - y0)
        val sx = if (x0 < x1) 1 else -1
        val sy = if (y0 < y1) 1 else -1
        var xx = x0
        var yy = y0
        var e1 = (if (dx > dy) dx else -dy) / 2
        var e2: Int
        while (true) {
            setPixel(xx, yy, c)
            if (xx == x1 && yy == y1) break
            e2 = e1
            if (e2 > -dx) { e1 -= dy; xx += sx }
            if (e2 <  dy) { e1 += dx; yy += sy }
        }
    }

    fun koch(x1: Double, y1: Double, x2: Double, y2: Double, it: Int) {
        val angle = PI / 3.0  // 60 degrees
        val clr = Color.blue
        var iter = it
        val x3 = (x1 * 2.0 + x2) / 3.0
        val y3 = (y1 * 2.0 + y2) / 3.0
        val x4 = (x1 + x2 * 2.0) / 3.0
        val y4 = (y1 + y2 * 2.0) / 3.0
        val x5 = x3 + (x4 - x3) * cos(angle) + (y4 - y3) * sin(angle)
        val y5 = y3 - (x4 - x3) * sin(angle) + (y4 - y3) * cos(angle)

        if (iter > 0) {
            iter--
            koch(x1, y1, x3, y3, iter)
            koch(x3, y3, x5, y5, iter)
            koch(x5, y5, x4, y4, iter)
            koch(x4, y4, x2, y2, iter)
         }
         else {
            drawLine(x1.asI, y1.asI, x3.asI, y3.asI, clr)
            drawLine(x3.asI, y3.asI, x5.asI, y5.asI, clr)
            drawLine(x5.asI, y5.asI, x4.asI, y4.asI, clr)
            drawLine(x4.asI, y4.asI, x2.asI, y2.asI, clr)
         }
    }
}

fun main(args: Array<String>) {
    val width = 512
    val height = 512
    val bbs = BasicBitmapStorage(width, height)
    with (bbs) {
        fill(Color.white)
        koch(100.0, 100.0, 400.0, 400.0, 4)
        val kFile = File("koch_curve.jpg")
        ImageIO.write(image, "jpg", kFile)
    }
}


Kolakoski sequence

The natural numbers, (excluding zero); with the property that:
: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.

;Example:
This is ''not'' a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2,...
Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:

: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...

The above gives the RLE of:
2, 3, 1, 2, 1, ...

The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.

;Creating a Kolakoski sequence:

Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....

# We start the sequence s with the first item from the cycle c: 1
# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate.
We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.

We started s with 1 and therefore s[k] states that it should appear only the 1 time.

Increment k
Get the next item from c and append it to the end of sequence s. s will then become: 1, 2
k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2
Increment k
Append the next item from the cycle to the list: 1, 2,2, 1
k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1
increment k

...

'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.

;Task:
# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.
# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence  to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.
# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).
# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 20 members of the sequence generated from (2, 1)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)
# Check the sequence againt its RLE.
(There are rules on generating Kolakoski sequences from this method that are broken by the last example)

Solution:
// Version 1.2.41

fun IntArray.nextInCycle(index: Int) = this[index % this.size]

fun IntArray.kolakoski(len: Int): IntArray {
    val s = IntArray(len)
    var i = 0
    var k = 0
    while (true) {
        s[i] = this.nextInCycle(k)
        if (s[k] > 1) {
            repeat(s[k] - 1) {
                if (++i == len) return s
                s[i] = s[i - 1]
            }
        }
        if (++i == len) return s
        k++
    }
}

fun IntArray.possibleKolakoski(): Boolean {
    val len = this.size
    val rle = mutableListOf<Int>()
    var prev = this[0]
    var count = 1
    for (i in 1 until len) {
        if (this[i] == prev) {
            count++
        }
        else {
            rle.add(count)
            count = 1
            prev = this[i]
        }
    }
    // no point adding final 'count' to rle as we're not going to compare it anyway
    for (i in 0 until rle.size) {
        if (rle[i] != this[i]) return false
    }
    return true
}

fun main(args: Array<String>) {
    val ias = listOf(
        intArrayOf(1, 2), intArrayOf(2, 1),
        intArrayOf(1, 3, 1, 2), intArrayOf(1, 3, 2, 1)
    )
    val lens = intArrayOf(20, 20, 30, 30)
    for ((i, ia) in ias.withIndex()) {
        val len = lens[i]
        val kol = ia.kolakoski(len)
        println("First $len members of the sequence generated by ${ia.asList()}:")
        println(kol.asList())
        val p = kol.possibleKolakoski()
        println("Possible Kolakoski sequence? ${if (p) "Yes" else "No"}\n")
    }
}