Dice game probabilities

Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.

They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?

Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?

This task was adapted from the Project Euler Problem n.205:
https://projecteuler.net/problem=205

Solution:
// version 1.1.2

fun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {
    if (nDice == 0) {
        counts[s]++
        return
    }
    for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts)
}

fun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double {
    val len1 = (nSides1 + 1) * nDice1
    val c1 = IntArray(len1)  // all elements zero by default
    throwDie(nSides1, nDice1, 0, c1)

    val len2 = (nSides2 + 1) * nDice2
    val c2 = IntArray(len2)
    throwDie(nSides2, nDice2, 0, c2)

    val p12 = Math.pow(nSides1.toDouble(), nDice1.toDouble()) *
              Math.pow(nSides2.toDouble(), nDice2.toDouble())

    var tot = 0.0
    for (i in 0 until len1) {
        for (j in 0 until minOf(i, len2)) {
            tot += c1[i] * c2[j] / p12
        }
    }
    return tot
}

fun main(args: Array<String>) {
    println(beatingProbability(4, 9, 6, 6))
    println(beatingProbability(10, 5, 7, 6))
}


Digital root

The digital root, X, of a number, n, is calculated:
: find X as the sum of the digits of n
: find a new X by summing the digits of X, repeating until X has only one digit.

The additive persistence is the number of summations required to obtain the single digit.

The task is to calculate the additive persistence and the digital root of a number, e.g.:
:627615 has additive persistence 2 and digital root of 9;
:39390 has additive persistence 2 and digital root of 6;
:588225 has additive persistence 2 and digital root of 3;
:393900588225 has additive persistence 2 and digital root of 9;

The digital root may be calculated in bases other than 10.

;See:
* [[Casting out nines]] for this wiki's use of this procedure.
* [[Digital root/Multiplicative digital root]]
* [[Sum digits of an integer]]
* Digital root sequence on OEIS
* Additive persistence sequence on OEIS
* [[Iterated digits squaring]]

Solution:
// version 1.0.6

fun sumDigits(n: Long): Int = when {
        n < 0L -> throw IllegalArgumentException("Negative numbers not allowed")
        else   -> {
            var sum = 0
            var nn  = n
            while (nn > 0L) {
                sum += (nn % 10).toInt()
                nn /= 10
            }
            sum
        }
    }

fun digitalRoot(n: Long): Pair<Int, Int> = when {
        n < 0L  -> throw IllegalArgumentException("Negative numbers not allowed")
        n < 10L -> Pair(n.toInt(), 0)
        else    -> {
            var dr = n
            var ap = 0
            while (dr > 9L) {
                dr = sumDigits(dr).toLong()
                ap++
            }
            Pair(dr.toInt(), ap)
        }
    }

fun main(args: Array<String>) {
    val a = longArrayOf(1, 14, 267, 8128, 627615, 39390, 588225, 393900588225)
    for (n in a) {
        val(dr, ap) = digitalRoot(n)
        println("${n.toString().padEnd(12)} has additive persistence $ap and digital root of $dr")
    }
}


Disarium numbers

A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.

;E.G.

'''135''' is a '''Disarium number''':

 11 + 32 + 53 == 1 + 9 + 125 == 135

There are a finite number of '''Disarium numbers'''.

;Task

* Find and display the first 18 '''Disarium numbers'''.

;Stretch

* Find and display all 20 '''Disarium numbers'''.

;See also

;* Geeks for Geeks - Disarium numbers
;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)
;* Related task: Narcissistic decimal number
;* Related task: Own digits power sum  ''Which seems to be the same task as Narcissistic decimal number...''

Solution:
fun power(n: Int, exp: Int): Int {
    return when {
        exp > 1 -> n * power(n, exp-1)
        exp == 1 -> n
        else -> 1
    }
}

fun is_disarium(num: Int): Boolean {
    val n = num.toString()
    var sum = 0
    for (i in 1..n.length) {
        sum += power (n[i-1] - '0', i)
    }
    return sum == num
}

fun main() {
    var i = 0
    var count = 0
    while (count < 19) {
        if (is_disarium(i)) {
            print("$i ")
            count++
        }
        i++
    }
    println("")
}


Display a linear combination

Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots).

Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is:

:\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots

where \alpha^{i_k}\neq 0

The output must comply to the following rules:
*   don't show null terms, unless the whole combination is null.
:::::::  '''e(1)'''     is fine,     '''e(1) + 0*e(3)'''     or     '''e(1) + 0'''     is wrong.
*   don't show scalars when they are equal to one or minus one.
:::::::  '''e(3)'''     is fine,     '''1*e(3)'''     is wrong.
*   don't prefix by a minus sign if it follows a preceding term.   Instead you use subtraction.
:::::::  '''e(4) - e(5)'''     is fine,     '''e(4) + -e(5)'''     is wrong.

Show here output for the following lists of scalars:

 1)    1,  2,  3
 2)    0,  1,  2,  3
 3)    1,  0,  3,  4
 4)    1,  2,  0
 5)    0,  0,  0
 6)    0
 7)    1,  1,  1
 8)   -1, -1, -1
 9)   -1, -2,  0, -3
10)   -1

Solution:
// version 1.1.2

fun linearCombo(c: IntArray): String {
    val sb = StringBuilder()
    for ((i, n) in c.withIndex()) {
        if (n == 0) continue
        val op = when {
            n < 0 && sb.isEmpty() -> "-"
            n < 0                 -> " - "
            n > 0 && sb.isEmpty() -> ""
            else                  -> " + "
        }
        val av = Math.abs(n)
        val coeff = if (av == 1) "" else "$av*"
        sb.append("$op${coeff}e(${i + 1})")
    }
    return if(sb.isEmpty()) "0" else sb.toString()
}

fun main(args: Array<String>) {
    val combos = arrayOf(
        intArrayOf(1, 2, 3),
        intArrayOf(0, 1, 2, 3),
        intArrayOf(1, 0, 3, 4),
        intArrayOf(1, 2, 0),
        intArrayOf(0, 0, 0),
        intArrayOf(0),
        intArrayOf(1, 1, 1),
        intArrayOf(-1, -1, -1),
        intArrayOf(-1, -2, 0, -3),
        intArrayOf(-1)
    )
    for (c in combos) {
        println("${c.contentToString().padEnd(15)}  ->  ${linearCombo(c)}")
    }
}


Diversity prediction theorem

The   ''wisdom of the crowd''   is the collective opinion of a group of individuals rather than that of a single expert.

Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise,   an explanation that assumes independence of the individual judgments from each other.

Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.

Scott E. Page introduced the diversity prediction theorem:
: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''.

Therefore,   when the diversity in a group is large,   the error of the crowd is small.

;Definitions:
::*   Average Individual Error:   Average of the individual squared errors
::*   Collective Error:           Squared error of the collective prediction
::*   Prediction Diversity:       Average squared distance from the individual predictions to the collective prediction
::*   Diversity Prediction Theorem:   ''Given a crowd of predictive models'',     then
::::::   Collective Error   =   Average Individual Error   -   Prediction Diversity

;Task:
For a given   true   value and a number of number of estimates (from a crowd),   show   (here on this page):
:::*   the true value   and   the crowd estimates
:::*   the average error
:::*   the crowd error
:::*   the prediction diversity

Use   (at least)   these two examples:
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51'''
:::*   a true value of   '''49'''   with crowd estimates of:   ''' 48   47   51   42'''

;Also see:
:*   Wikipedia entry:   Wisdom of the crowd
:*   University of Michigan: PDF paper         (exists on a web archive,   the ''Wayback Machine'').

Solution:
// version 1.1.4-3

fun square(d: Double) = d * d

fun averageSquareDiff(d: Double, predictions: DoubleArray) =
    predictions.map { square(it - d) }.average()

fun diversityTheorem(truth: Double, predictions: DoubleArray): String {
    val average = predictions.average()
    val f = "%6.3f"
    return "average-error : ${f.format(averageSquareDiff(truth, predictions))}\n" +
           "crowd-error   : ${f.format(square(truth - average))}\n" +
           "diversity     : ${f.format(averageSquareDiff(average, predictions))}\n"
}

fun main(args: Array<String>) {
    println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0)))
    println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0, 42.0)))
}


Dot product

Create a function/use an in-built function, to compute the   '''dot product''',   also known as the   '''scalar product'''   of two vectors.

If possible, make the vectors of arbitrary length.

As an example, compute the dot product of the vectors:
::::     [1,  3, -5]       and
::::     [4,      -2, -1]

If implementing the dot product of two vectors directly:
:::*   each vector must be the same length
:::*   multiply corresponding terms from each vector
:::*   sum the products   (to produce the answer)

;Related task:
*   [[Vector products]]

Solution:
fun dot(v1: Array<Double>, v2: Array<Double>) =
    v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }

fun main(args: Array<String>) {
    dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }
}


Draw a clock

Draw a clock.

More specific:
# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.
# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.
# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.
# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.

;Key points
* animate simple object
* timed event
* polling system resources
* code clarity

Solution:
// version 1.1

import java.awt.*
import java.time.LocalTime
import javax.swing.*

class Clock : JPanel() {
    private val degrees06: Float = (Math.PI / 30.0).toFloat()
    private val degrees30: Float = degrees06 * 5.0f
    private val degrees90: Float =  degrees30 * 3.0f
    private val size = 590
    private val spacing = 40
    private val diameter = size - 2 * spacing
    private val cx = diameter / 2 + spacing
    private val cy = cx

    init {
        preferredSize = Dimension(size, size)
        background =  Color.white
        Timer(1000) {
            repaint()
        }.start()
    }

    override public fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        drawFace(g)
        val time  = LocalTime.now()
        val hour = time.hour
        val minute = time.minute
        val second = time.second
        var angle: Float = degrees90 - degrees06 * second
        drawHand(g, angle, diameter / 2 - 30, Color.red)
        val minsecs: Float = minute + second / 60.0f
        angle = degrees90 - degrees06 * minsecs
        drawHand(g, angle, diameter / 3 + 10, Color.black)
        val hourmins: Float = hour + minsecs / 60.0f
        angle = degrees90 - degrees30 * hourmins
        drawHand(g, angle, diameter / 4 + 10, Color.black)
    }

    private fun drawFace(g: Graphics2D) {
        g.stroke = BasicStroke(2.0f)
        g.color = Color.yellow
        g.fillOval(spacing, spacing, diameter, diameter)
        g.color = Color.black
        g.drawOval(spacing, spacing, diameter, diameter)
    }

    private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) {
        val x: Int  = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt()
        val y: Int =  cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt()
        g.color = color
        g.drawLine(cx, cy, x, y)
    }
}

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


Draw a rotating cube

Task
Draw a rotating cube.

It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.

;Related tasks
* Draw a cuboid
* write language name in 3D ASCII

Solution:
// version 1.1

import java.awt.*
import javax.swing.*

class RotatingCube : JPanel() {
    private val nodes = arrayOf(
        doubleArrayOf(-1.0, -1.0, -1.0),
        doubleArrayOf(-1.0, -1.0,  1.0),
        doubleArrayOf(-1.0,  1.0, -1.0),
        doubleArrayOf(-1.0,  1.0,  1.0),
        doubleArrayOf( 1.0, -1.0, -1.0),
        doubleArrayOf( 1.0, -1.0,  1.0),
        doubleArrayOf( 1.0,  1.0, -1.0),
        doubleArrayOf( 1.0,  1.0,  1.0)
    )
    private val edges = arrayOf(
        intArrayOf(0, 1),
        intArrayOf(1, 3),
        intArrayOf(3, 2),
        intArrayOf(2, 0),
        intArrayOf(4, 5),
        intArrayOf(5, 7),
        intArrayOf(7, 6),
        intArrayOf(6, 4),
        intArrayOf(0, 4),
        intArrayOf(1, 5),
        intArrayOf(2, 6),
        intArrayOf(3, 7)
    )

    init {
        preferredSize = Dimension(640, 640)
        background = Color.white
        scale(100.0)
        rotateCube(Math.PI / 4.0, Math.atan(Math.sqrt(2.0)))
        Timer(17) {
            rotateCube(Math.PI / 180.0, 0.0)
            repaint()
        }.start()
    }

    private fun scale(s: Double) {
        for (node in nodes) {
            node[0] *= s
            node[1] *= s
            node[2] *= s
        }
    }

    private fun rotateCube(angleX: Double, angleY: Double) {
        val sinX = Math.sin(angleX)
        val cosX = Math.cos(angleX)
        val sinY = Math.sin(angleY)
        val cosY = Math.cos(angleY)
        for (node in nodes) {
            val x = node[0]
            val y = node[1]
            var z = node[2]
            node[0] = x * cosX - z * sinX
            node[2] = z * cosX + x * sinX
            z = node[2]
            node[1] = y * cosY - z * sinY
            node[2] = z * cosY + y * sinY
        }
    }

    private fun drawCube(g: Graphics2D) {
        g.translate(width / 2, height / 2)
        for (edge in edges) {
            val xy1 = nodes[edge[0]]
            val xy2 = nodes[edge[1]]
            g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(),
                       Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt())
        }
        for (node in nodes) {
            g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8)
        }
    }

    override public fun paintComponent(gg: Graphics) {
        super.paintComponent(gg)
        val g = gg as Graphics2D
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
        g.color = Color.blue
        drawCube(g)
    }
}

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


Draw a sphere

{{requires|Graphics}}

;Task:
Draw a sphere.

The sphere can be represented graphically, or in ASCII art, depending on the language capabilities.

Either static or rotational projection is acceptable for this task.

;Related tasks:
* draw a cuboid
* draw a rotating cube
* write language name in 3D ASCII
* draw a Deathstar

Solution:
// version 1.0.6

const val shades = ".:!*oe&#%@"
val light  = doubleArrayOf(30.0, 30.0, -50.0)

fun normalize(v: DoubleArray) {
    val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])
    v[0] /= len; v[1] /= len; v[2] /= len
}

fun dot(x: DoubleArray, y: DoubleArray): Double {
    val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2]
    return if (d < 0.0) -d else 0.0
}

fun drawSphere(r: Double, k: Double, ambient: Double) {
    val vec = DoubleArray(3)
    var intensity: Int
    var b : Double
    var x: Double
    var y: Double
    for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) {
        x = i + 0.5
        for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) {
            y = j / 2.0 + 0.5
            if (x * x + y * y <= r * r) {
                vec[0] = x
                vec[1] = y
                vec[2] = Math.sqrt(r * r - x * x - y * y)
                normalize(vec)
                b = Math.pow(dot(light, vec), k) + ambient
                intensity = ((1.0 - b) * (shades.length - 1)).toInt()
                if (intensity < 0) intensity = 0
                if (intensity >= shades.length - 1) intensity = shades.length - 2
                print(shades[intensity])
            }
            else print(' ')
        }
        println()
    }
}

fun main(args: Array<String>) {
    normalize(light)
    drawSphere(20.0, 4.0, 0.1)
    drawSphere(10.0, 2.0, 0.4)
}


Dutch national flag problem

The Dutch national flag is composed of three coloured bands in the order:
::*   red     (top)
::*   then white,   and
::*   lastly blue   (at the bottom).

The problem posed by Edsger Dijkstra is:
:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.
When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...

;Task
# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.
# Sort the balls in a way idiomatic to your language.
# Check the sorted balls ''are'' in the order of the Dutch national flag.

;C.f.:
* Dutch national flag problem
* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)

Solution:
// version 1.1.4

import java.util.Random

enum class DutchColors { RED, WHITE, BLUE }

fun Array<DutchColors>.swap(i: Int, j: Int) {
    val temp = this[i]
    this[i] = this[j]
    this[j] = temp
}

fun Array<DutchColors>.sort() {
    var lo = 0
    var mid = 0
    var hi = this.lastIndex

    while (mid <= hi) {
        when (this[mid]) {
            DutchColors.RED   -> this.swap(lo++, mid++)
            DutchColors.WHITE -> mid++
            DutchColors.BLUE  -> this.swap(mid, hi--)
        }
    }
}

fun Array<DutchColors>.isSorted(): Boolean {
    return (1 until this.size)
        .none { this[it].ordinal < this[it - 1].ordinal }
}

const val NUM_BALLS = 9

fun main(args: Array<String>) {
    val r = Random()
    val balls  = Array(NUM_BALLS) { DutchColors.RED }
    val colors = DutchColors.values()

    // give balls random colors whilst ensuring they're not already sorted
    do {
        for (i in 0 until NUM_BALLS) balls[i] = colors[r.nextInt(3)]
    }
    while (balls.isSorted())

    // print the colors of the balls before sorting
    println("Before sorting : ${balls.contentToString()}")

    // sort the balls in DutchColors order
    balls.sort()

    // print the colors of the balls after sorting
    println("After sorting  : ${balls.contentToString()}")
}


EKG sequence convergence

The sequence is from the natural numbers and is defined by:
* a(1) = 1;
* a(2) = Start = 2;
* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.

The sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).

Variants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call:
* The sequence described above , starting 1, 2, ... the EKG(2) sequence;
* the sequence starting 1, 3, ... the EKG(3) sequence;
* ... the sequence starting 1, N, ... the EKG(N) sequence.

;Convergence
If an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.
EKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).

;Task:
# Calculate and show here the first 10 members of EKG(2).
# Calculate and show here the first 10 members of EKG(5).
# Calculate and show here the first 10 members of EKG(7).
# Calculate and show here the first 10 members of EKG(9).
# Calculate and show here the first 10 members of EKG(10).
# Calculate and show here at which term EKG(5) and EKG(7) converge   ('''stretch goal''').

;Related Tasks:
# [[Greatest common divisor]]
# [[Sieve of Eratosthenes]]

;Reference:
* The EKG Sequence and the Tree of Numbers. (Video).

Solution:
// Version 1.2.60

fun gcd(a: Int, b: Int): Int {
    var aa = a
    var bb = b
    while (aa != bb) {
        if (aa > bb)
            aa -= bb
        else
            bb -= aa
    }
    return aa
}

const val LIMIT = 100

fun main(args: Array<String>) {
    val starts = listOf(2, 5, 7, 9, 10)
    val ekg = Array(5) { IntArray(LIMIT) }

    for ((s, start) in starts.withIndex()) {
        ekg[s][0] = 1
        ekg[s][1] = start
        for (n in 2 until LIMIT) {
            var i = 2
            while (true) {
                // a potential sequence member cannot already have been used
                // and must have a factor in common with previous member
                if (!ekg[s].slice(0 until n).contains(i) &&
                    gcd(ekg[s][n - 1], i) > 1) {
                        ekg[s][n] = i
                        break
                }
                i++
            }
        }
        System.out.printf("EKG(%2d): %s\n", start, ekg[s].slice(0 until 30))
    }

    // now compare EKG5 and EKG7 for convergence
    for (i in 2 until LIMIT) {
        if (ekg[1][i] == ekg[2][i] &&
        ekg[1].slice(0 until i).sorted() == ekg[2].slice(0 until i).sorted()) {
            println("\nEKG(5) and EKG(7) converge at term ${i + 1}")
            return
        }
    }
    println("\nEKG5(5) and EKG(7) do not converge within $LIMIT terms")
}


Eban numbers

Definition:
An   '''eban'''   number is a number that has no letter    '''e'''    in it when the number is spelled in English.

Or more literally,   spelled numbers that contain the letter   '''e'''   are banned.

The American version of spelling numbers will be used here   (as opposed to the British).

'''2,000,000,000'''   is two billion,   ''not''   two milliard.

Only numbers less than   '''one sextillion'''   ('''1021''')   will be considered in/for this task.

This will allow optimizations to be used.

;Task:
:::*   show all eban numbers   <=   '''1,000'''   (in a horizontal format),                   and a count
:::*   show all eban numbers between   '''1,000'''   and   '''4,000'''   (inclusive),   and a count
:::*   show a count of all eban numbers up and including            '''10,000'''
:::*   show a count of all eban numbers up and including                '''100,000'''
:::*   show a count of all eban numbers up and including                   '''1,000,000'''
:::*   show a count of all eban numbers up and including                      '''10,000,000'''
:::*   show all output here.

;See also:
:*   The MathWorld entry:    eban numbers.
:*   The OEIS      entry:   A6933,                eban numbers.
:*   [[Number names]].

Solution:
// Version 1.3.21

typealias Range = Triple<Int, Int, Boolean>

fun main() {
    val rgs = listOf<Range>(
        Range(2, 1000, true),
        Range(1000, 4000, true),
        Range(2, 10_000, false),
        Range(2, 100_000, false),
        Range(2, 1_000_000, false),
        Range(2, 10_000_000, false),
        Range(2, 100_000_000, false),
        Range(2, 1_000_000_000, false)
    )
    for (rg in rgs) {
        val (start, end, prnt) = rg
        if (start == 2) {
            println("eban numbers up to and including $end:")
        } else {
            println("eban numbers between $start and $end (inclusive):")
        }
        var count = 0
        for (i in start..end step 2) {
            val b = i / 1_000_000_000
            var r = i % 1_000_000_000
            var m = r / 1_000_000
            r = i % 1_000_000
            var t = r / 1_000
            r %= 1_000
            if (m >= 30 && m <= 66) m %= 10
            if (t >= 30 && t <= 66) t %= 10
            if (r >= 30 && r <= 66) r %= 10
            if (b == 0 || b == 2 || b == 4 || b == 6) {
                if (m == 0 || m == 2 || m == 4 || m == 6) {
                    if (t == 0 || t == 2 || t == 4 || t == 6) {
                        if (r == 0 || r == 2 || r == 4 || r == 6) {
                            if (prnt) print("$i ")
                            count++
                        }
                    }
                }
            }
        }
        if (prnt) println()
        println("count = $count\n")
    }
}


Eertree

An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string.

The data structure has commonalities to both ''tries'' and ''suffix trees''.
  See links below.

;Task:
Construct an eertree for the string "eertree", then output all sub-palindromes by traversing the tree.

;See also:
*   Wikipedia entry:   trie.
*   Wikipedia entry:   suffix tree
*   Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.

Solution:
// version 1.1.4

class Node {
    val edges = mutableMapOf<Char, Node>()  // edges (or forward links)
    var link: Node? = null                  // suffix link (backward links)
    var len = 0                             // the length of the node
}

class Eertree(str: String) {
    val nodes = mutableListOf<Node>()

    private val rto = Node()                // odd length root node, or node -1
    private val rte = Node()                // even length root node, or node 0
    private val s = StringBuilder("0")      // accumulated input string, T = S[1..i]
    private var maxSufT = rte               // maximum suffix of tree T

    init {
        // Initialize and build the tree
        rte.link = rto
        rto.link = rte
        rto.len  = -1
        rte.len  = 0
        for (ch in str) add(ch)
    }

    private fun getMaxSuffixPal(startNode: Node, a: Char): Node {
        // We traverse the suffix-palindromes of T in the order of decreasing length.
        // For each palindrome we read its length k and compare T[i-k] against a
        // until we get an equality or arrive at the -1 node.
        var u = startNode
        val i = s.length
        var k = u.len
        while (u !== rto && s[i - k - 1] != a) {
            if (u === u.link!!) throw RuntimeException("Infinite loop detected")
            u = u.link!!
            k = u.len
        }
        return u
    }

    private fun add(a: Char): Boolean {
        // We need to find the maximum suffix-palindrome P of Ta
        // Start by finding maximum suffix-palindrome Q of T.
        // To do this, we traverse the suffix-palindromes of T
        // in the order of decreasing length, starting with maxSuf(T)
        val q = getMaxSuffixPal(maxSufT, a)

        // We check Q to see whether it has an outgoing edge labeled by a.
        val createANewNode = a !in q.edges.keys

        if (createANewNode) {
            // We create the node P of length Q + 2
            val p = Node()
            nodes.add(p)
            p.len = q.len + 2
            if (p.len == 1) {
                // if P = a, create the suffix link (P, 0)
                p.link = rte
            }
            else {
                // It remains to create the suffix link from P if |P|>1. Just
                // continue traversing suffix-palindromes of T starting with the
                // the suffix link of Q.
                p.link = getMaxSuffixPal(q.link!!, a).edges[a]
            }

            // create the edge (Q, P)
            q.edges[a] = p
        }

        // P becomes the new maxSufT
        maxSufT = q.edges[a]!!

        // Store accumulated input string
        s.append(a)

        return createANewNode
    }

    fun getSubPalindromes(): List<String> {
        // Traverse tree to find sub-palindromes
        val result = mutableListOf<String>()
        // Odd length words
        getSubPalindromes(rto, listOf(rto), "", result)
        // Even length words
        getSubPalindromes(rte, listOf(rte), "", result)
        return result
    }

    private fun getSubPalindromes(nd: Node, nodesToHere: List<Node>,
                          charsToHere: String, result: MutableList<String>) {
        // Each node represents a palindrome, which can be reconstructed
        // by the path from the root node to each non-root node.

        // Traverse all edges, since they represent other palindromes
        for ((lnkName, nd2) in nd.edges) {
            getSubPalindromes(nd2, nodesToHere + nd2, charsToHere + lnkName, result)
        }

        // Reconstruct based on charsToHere characters.
        if (nd !== rto && nd !== rte) { // Don't print for root nodes
            val assembled = charsToHere.reversed() +
                if (nodesToHere[0] === rte)  // Even string
                    charsToHere
                else  // Odd string
                    charsToHere.drop(1)
            result.add(assembled)
        }
    }
}

fun main(args: Array<String>) {
    val str = "eertree"
    println("Processing string '$str'")
    val eertree = Eertree(str)
    println("Number of sub-palindromes: ${eertree.nodes.size}")
    val result = eertree.getSubPalindromes()
    println("Sub-palindromes: $result")
}


Egyptian division

Egyptian division is a method of dividing integers using addition and
doubling that is similar to the algorithm of [[Ethiopian multiplication]]

'''Algorithm:'''

Given two numbers where the '''dividend''' is to be divided by the '''divisor''':

# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.
# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.
# Continue with successive i'th rows of 2^i and 2^i * divisor.
# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.
# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''
# Consider each row of the table, in the ''reverse'' order of its construction.
# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.
# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).

'''Example: 580 / 34'''

''' Table creation: '''

::: {| class="wikitable"
! powers_of_2
! doublings
|-
| 1
| 34
|-
| 2
| 68
|-
| 4
| 136
|-
| 8
| 272
|-
| 16
| 544
|}

''' Initialization of sums: '''

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| 16
| 544
|

|

|-
|
|
| 0
| 0
|}

''' Considering table rows, bottom-up: '''

When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
| 16
| 544
|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
| 16
| 544
|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
|

|

|-
| 4
| 136
| 16
| 544
|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| 1
| 34
|

|

|-
| 2
| 68
| 16
| 544
|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

::: {| class="wikitable"
! powers_of_2
! doublings
! answer
! accumulator
|-
| '''1'''
| '''34'''
| 17
| 578
|-
| 2
| 68
|

|

|-
| 4
| 136
|

|

|-
| 8
| 272
|

|

|-
| '''16'''
| '''544'''
|

|

|}

;Answer:
So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.

;Task:
The task is to create a function that does Egyptian division. The function should
closely follow the description above in using a list/array of powers of two, and
another of doublings.

* Functions should be clear interpretations of the algorithm.
* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.

;Related tasks:
:*   Egyptian fractions

;References:
:*   Egyptian Number System

Solution:
// version 1.1.4

data class DivMod(val quotient: Int, val remainder: Int)

fun egyptianDivide(dividend: Int, divisor: Int): DivMod {
    require (dividend >= 0 && divisor > 0)
    if (dividend < divisor) return DivMod(0, dividend)
    val powersOfTwo = mutableListOf(1)
    val doublings = mutableListOf(divisor)
    var doubling = divisor
    while (true) {
       doubling *= 2
       if (doubling > dividend) break
       powersOfTwo.add(powersOfTwo[powersOfTwo.lastIndex] * 2)
       doublings.add(doubling)
    }
    var answer = 0
    var accumulator = 0
    for (i in doublings.size - 1 downTo 0) {
        if (accumulator + doublings[i] <= dividend) {
            accumulator += doublings[i]
            answer += powersOfTwo[i]
            if (accumulator == dividend) break
        }
    }
    return DivMod(answer, dividend - accumulator)
}

fun main(args: Array<String>) {
    val dividend = 580
    val divisor = 34
    val (quotient, remainder) = egyptianDivide(dividend, divisor)
    println("$dividend divided by $divisor is $quotient with remainder $remainder")
}


Elementary cellular automaton

An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors.  Those three values can be encoded with three bits.

The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order.  Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.

;Task:
Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state.  You can demonstrate your solution with any automaton of your choice.

The space state should ''wrap'':  this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.

This task is basically a generalization of [[one-dimensional cellular automata]].

;See also
* Cellular automata (natureofcode.com)

Solution:
// version 1.1.51

import java.util.BitSet

const val SIZE  = 32
const val LINES = SIZE / 2
const val RULE  = 90

fun ruleTest(x: Int) = (RULE and (1 shl (7 and x))) != 0

infix fun Boolean.shl(bitCount: Int) = (if (this) 1 else 0) shl bitCount

fun Boolean.toInt() = if (this) 1 else 0

fun evolve(s: BitSet) {
    val t = BitSet(SIZE)  // all false by default
    t[SIZE - 1] = ruleTest((s[0] shl 2) or (s[SIZE - 1] shl 1) or s[SIZE - 2].toInt())
    t[0] = ruleTest((s[1] shl 2) or (s[0] shl 1) or s[SIZE - 1].toInt())
    for (i in 1 until SIZE - 1) {
        t[i] = ruleTest((s[i + 1] shl 2) or (s[i] shl 1) or s[i - 1].toInt())
    }
    for (i in 0 until SIZE) s[i] = t[i]
}

fun show(s: BitSet) {
    for (i in SIZE - 1 downTo 0) print(if (s[i]) "*" else " ")
    println()
}

fun main(args: Array<String>) {
    var state = BitSet(SIZE)
    state.set(LINES)
    println("Rule $RULE:")
    repeat(LINES) {
        show(state)
        evolve(state)
    }
}


Elementary cellular automaton/Infinite length

The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.

To be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support.  In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.

Examples:

1        ->   ..., 0, 0,      1,      0, 0, ...
0, 1     ->   ..., 1, 1,   0, 1,      0, 0, ...
1, 0, 1  ->   ..., 0, 0,   1, 0, 1,   0, 0, ...

More complex methods can be imagined, provided it is possible to somehow encode the infinite sections.  But for this task we will stick to this simple version.

Solution:
// version 1.1.51

fun evolve(l: Int, rule: Int) {
    println(" Rule #$rule:")
    var cells = StringBuilder("*")
    for (x in 0 until l) {
        addNoCells(cells)
        val width = 40 + (cells.length shr 1)
        println(cells.padStart(width))
        cells = step(cells, rule)
    }
}

fun step(cells: StringBuilder, rule: Int): StringBuilder {
    val newCells = StringBuilder()
    for (i in 0 until cells.length - 2) {
        var bin = 0
        var b = 2
        for (n in i until i + 3) {
            bin += (if (cells[n] == '*') 1 else 0) shl b
            b = b shr 1
        }
        val a = if ((rule and (1 shl bin)) != 0) '*' else '.'
        newCells.append(a)
    }
    return newCells
}

fun addNoCells(s: StringBuilder) {
    val l = if (s[0] == '*') '.' else '*'
    val r = if (s[s.length - 1] == '*') '.' else '*'
    repeat(2) {
       s.insert(0, l)
       s.append(r)
    }
}

fun main(args: Array<String>) {
    evolve(35, 90)
    println()
}


Elementary cellular automaton/Random number generator

Mathematica software for its default random number generator.

Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.

The purpose of this task is to demonstrate this.  With the code written in the most significant.

You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.

For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.

;Reference:
* Cellular automata: Is Rule 30 random? (PDF).

Solution:
// version 1.1.51

const val N = 64

fun pow2(x: Int) = 1L shl x

fun evolve(state: Long, rule: Int) {
    var state2 = state
    for (p in 0..9) {
        var b = 0
        for (q in 7 downTo 0) {
            val st = state2
            b = (b.toLong() or ((st and 1L) shl q)).toInt()
            state2 = 0L
            for (i in 0 until N) {
                val t = ((st ushr (i - 1)) or (st shl (N + 1 - i)) and 7L).toInt()
                if ((rule.toLong() and pow2(t)) != 0L) state2 = state2 or pow2(i)
            }
        }
        print(" $b")
    }
    println()
}

fun main(args: Array<String>) {
    evolve(1, 30)
}


Elliptic curve arithmetic

digital signatures.

The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the   elliptic curve DSA   protocol.

In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:

::::   y^2 = x^3 + a x + b

'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used.

For this particular task, we'll use the following parameters:

::::    a=0,   b=7

The most interesting thing about elliptic curves is the fact that it is possible to define a   group   structure on it.

To do so we define an   internal composition   rule with an additive notation '''+''',   such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:

::::    P + Q + R = 0

Here   '''0'''   (zero)   is the ''infinity point'',   for which the '''x''' and '''y''' values are not defined.   It's basically the same kind of point which defines the horizon in   projective geometry.

We'll also assume here that this infinity point is unique and defines the   neutral element   of the addition.

This was not the definition of the addition, but only its desired property.    For a more accurate definition, we proceed as such:

Given any three aligned points '''P''', '''Q''' and '''R''',   we define the sum   '''S = P + Q'''   as the point (possibly the infinity point) such that   '''S''', '''R'''   and the infinity point are aligned.

Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis   (because in that case there is no other candidate than the infinity point to complete the alignment triplet).

'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.

The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points.   You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points.

You will use the '''a''' and '''b''' parameters of secp256k1, i.e.  respectively zero and seven.

''Hint'':   You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''.

''Extra credit'':   define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns,
for any point '''P''' and integer '''n''',   the point '''P + P + ... + P'''     ('''n''' times).

Solution:
// version 1.1.4

const val C = 7

class Pt(val x: Double, val y: Double) {
    val zero get() = Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)

    val isZero get() = x > 1e20 || x < -1e20

    fun dbl(): Pt {
        if (isZero) return this
        val l = 3.0 * x * x / (2.0 * y)
        val t = l * l - 2.0 * x
        return Pt(t, l * (x - t) - y)
    }

    operator fun unaryMinus() = Pt(x, -y)

    operator fun plus(other: Pt): Pt {
        if (x == other.x && y == other.y) return dbl()
        if (isZero) return other
        if (other.isZero) return this
        val l = (other.y - y) / (other.x - x)
        val t = l * l - x - other.x
        return Pt(t, l * (x - t) - y)
    }

    operator fun times(n: Int): Pt {
        var r: Pt = zero
        var p = this
        var i = 1
        while (i <= n) {
            if ((i and n) != 0) r += p
            p = p.dbl()
            i = i shl 1
        }
        return r
    }

    override fun toString() =
        if (isZero) "Zero" else "(${"%.3f".format(x)}, ${"%.3f".format(y)})"
}

fun Double.toPt() = Pt(Math.cbrt(this * this - C), this)

fun main(args: Array<String>) {
    val a = 1.0.toPt()
    val b = 2.0.toPt()
    val c = a + b
    val d = -c
    println("a         = $a")
    println("b         = $b")
    println("c = a + b = $c")
    println("d = -c    = $d")
    println("c + d     = ${c + d}")
    println("a + b + d = ${a + b + d}")
    println("a * 12345 = ${a * 12345}")
}


Empty directory

Starting with a path to some directory, determine whether the directory is empty.

An empty directory contains no files nor subdirectories.
With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.

Solution:
// version 1.1.4

import java.io.File

fun main(args: Array<String>) {
    val dirPath = "docs" // or whatever
    val isEmpty = (File(dirPath).list().isEmpty())
    println("$dirPath is ${if (isEmpty) "empty" else "not empty"}")
}


Empty string

Languages may have features for dealing specifically with empty strings
(those containing no characters).

;Task:
::*   Demonstrate how to assign an empty string to a variable.
::*   Demonstrate how to check that a string is empty.
::*   Demonstrate how to check that a string is not empty.

Solution:
fun main(args: Array<String>) {
    val s = ""
    println(s.isEmpty())    // true
    println(s.isNotEmpty()) // false
    println(s.length)       // 0
    println(s.none())       // true
    println(s.any())        // false
}


Entropy/Narcissist

Write a computer program that computes and shows its own   [[entropy]].

;Related Tasks:
:*   [[Fibonacci_word]]
:*   [[Entropy]]

Solution:
// version 1.1.0 (entropy_narc.kt)

fun log2(d: Double) = Math.log(d) / Math.log(2.0)

fun shannon(s: String): Double {
    val counters = mutableMapOf<Char, Int>()
    for (c in s) {
        if (counters.containsKey(c)) counters[c] = counters[c]!! + 1
        else counters.put(c, 1)
    }
    val nn = s.length.toDouble()
    var sum = 0.0
    for (key in counters.keys) {
       val term = counters[key]!! / nn
       sum += term * log2(term)
    }
    return -sum
}

fun main(args: Array<String>) {
   val prog = java.io.File("entropy_narc.kt").readText()
   println("This program's entropy is ${"%18.16f".format(shannon(prog))}")
}


Equilibrium index

An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.

For example, in a sequence   A:

:::::   A_0 = -7
:::::   A_1 =  1
:::::   A_2 =  5
:::::   A_3 =  2
:::::   A_4 = -4
:::::   A_5 =  3
:::::   A_6 =  0

3   is an equilibrium index, because:

:::::   A_0 + A_1 + A_2 = A_4 + A_5 + A_6

6   is also an equilibrium index, because:

:::::   A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0

(sum of zero elements is zero)

7   is not an equilibrium index, because it is not a valid index of sequence A.

;Task;
Write a function that, given a sequence, returns its equilibrium indices (if any).

Assume that the sequence may be very long.

Solution:
// version 1.1

fun equilibriumIndices(a: IntArray): MutableList<Int> {
   val ei = mutableListOf<Int>()
   if (a.isEmpty()) return ei // empty list
   val sumAll  = a.sumBy { it }
   var sumLeft = 0
   var sumRight: Int
   for (i in 0 until a.size) {
       sumRight = sumAll - sumLeft - a[i]
       if (sumLeft == sumRight) ei.add(i)
       sumLeft += a[i]
   }
   return ei
}

fun main(args: Array<String>) {
    val a = intArrayOf(-7, 1, 5, 2, -4, 3, 0)
    val ei = equilibriumIndices(a)
    when (ei.size) {
         0     -> println("There are no equilibrium indices")
         1     -> println("The only equilibrium index is : ${ei[0]}")
         else  -> println("The equilibrium indices are : ${ei.joinToString(", ")}")
    }
}


Esthetic numbers

An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.

;E.G.

:* '''12''' is an esthetic number. One and two differ by 1.

:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.

:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.

These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.

Esthetic numbers are also sometimes referred to as stepping numbers.

;Task

:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.

:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)

:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.

:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.

;Related task:
*   numbers with equal rises and falls

;See also:
:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1
:;*Numbers Aplenty - Esthetic numbers
:;*Geeks for Geeks - Stepping numbers

Solution:
import kotlin.math.abs

fun isEsthetic(n: Long, b: Long): Boolean {
    if (n == 0L) {
        return false
    }
    var i = n % b
    var n2 = n / b
    while (n2 > 0) {
        val j = n2 % b
        if (abs(i - j) != 1L) {
            return false
        }
        n2 /= b
        i = j
    }
    return true
}

fun listEsths(n: Long, n2: Long, m: Long, m2: Long, perLine: Int, all: Boolean) {
    val esths = mutableListOf<Long>()
    fun dfs(n: Long, m: Long, i: Long) {
        if (i in n..m) {
            esths.add(i)
        }
        if (i == 0L || i > m) {
            return
        }
        val d = i % 10
        val i1 = i * 10 + d - 1
        val i2 = i1 + 2
        when (d) {
            0L -> {
                dfs(n, m, i2)
            }
            9L -> {
                dfs(n, m, i1)
            }
            else -> {
                dfs(n, m, i1)
                dfs(n, m, i2)
            }
        }
    }

    for (i in 0L until 10L) {
        dfs(n2, m2, i)
    }

    val le = esths.size
    println("Base 10: $le esthetic numbers between $n and $m:")
    if (all) {
        for (c_esth in esths.withIndex()) {
            print("${c_esth.value} ")
            if ((c_esth.index + 1) % perLine == 0) {
                println()
            }
        }
        println()
    } else {
        for (i in 0 until perLine) {
            print("${esths[i]} ")
        }
        println()
        println("............")
        for (i in le - perLine until le) {
            print("${esths[i]} ")
        }
        println()
    }
    println()
}

fun main() {
    for (b in 2..16) {
        println("Base $b: ${4 * b}th to ${6 * b}th esthetic numbers:")
        var n = 1L
        var c = 0L
        while (c < 6 * b) {
            if (isEsthetic(n, b.toLong())) {
                c++
                if (c >= 4 * b) {
                    print("${n.toString(b)} ")
                }
            }
            n++
        }
        println()
    }
    println()

    // the following all use the obvious range limitations for the numbers in question
    listEsths(1000, 1010, 9999, 9898, 16, true);
    listEsths(1e8.toLong(), 101_010_101, 13 * 1e7.toLong(), 123_456_789, 9, true);
    listEsths(1e11.toLong(), 101_010_101_010, 13 * 1e10.toLong(), 123_456_789_898, 7, false);
    listEsths(1e14.toLong(), 101_010_101_010_101, 13 * 1e13.toLong(), 123_456_789_898_989, 5, false);
    listEsths(1e17.toLong(), 101_010_101_010_101_010, 13 * 1e16.toLong(), 123_456_789_898_989_898, 4, false);
}


Euler's identity

{{Wikipedia|Euler's_identity}}

In mathematics, ''Euler's identity'' is the equality:

                ei\pi + 1 = 0

where

    e is Euler's number, the base of natural logarithms,
    ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and
    \pi is pi, the ratio of the circumference of a circle to its diameter.

Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:

    The number 0.
    The number 1.
    The number \pi (\pi = 3.14159+),
    The number e (e = 2.71828+), which occurs widely in mathematical analysis.
    The number ''i'', the imaginary unit of the complex numbers.

;Task
Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation.

Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation.

If that is the case, or there is some other limitation, show
that ei\pi + 1 is ''approximately'' equal to zero and
show the amount of error in the calculation.

If your language is capable of symbolic calculations, show
that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.

Solution:
// Version 1.2.40

import kotlin.math.sqrt
import kotlin.math.PI

const val EPSILON = 1.0e-16
const val SMALL_PI = '\u03c0'
const val APPROX_EQUALS = '\u2245'

class Complex(val real: Double, val imag: Double) {
    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
    )

    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()

    val modulus: Double get() = sqrt(real * real + imag * imag)

    override fun toString() =
        if (imag >= 0.0) "$real + ${imag}i"
        else "$real - ${-imag}i"
}

fun main(args: Array<String>) {
    var fact = 1.0
    val x = Complex(0.0, PI)
    var e = Complex(1.0, PI)
    var n = 2
    var pow = x
    do {
        val e0 = e
        fact *= n++
        pow *= x
        e += pow / Complex(fact, 0.0)
    }
    while ((e - e0).modulus >= EPSILON)
    e += Complex(1.0, 0.0)
    println("e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0")
}


Euler's sum of powers conjecture

There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.

This conjecture is called Euler's sum of powers conjecture and can be stated as such:

:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.

In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.

The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.

Related tasks are:
* [[Pythagorean quadruples]].
* [[Pythagorean triples]].

Solution:
fun main(args: Array<String>) {
    val p5 = LongArray(250){ it.toLong() * it * it * it * it }
    var sum: Long
    var y: Int
    var found = false
    loop@ for (x0 in 0 .. 249)
        for (x1 in 0 .. x0 - 1)
            for (x2 in 0 .. x1 - 1)
                for (x3 in 0 .. x2 - 1) {
                    sum = p5[x0] + p5[x1] + p5[x2] + p5[x3]
                    y = p5.binarySearch(sum)
                    if (y >= 0) {
                        println("$x0^5 + $x1^5 + $x2^5 + $x3^5 = $y^5")
                        found = true
                        break@loop
                    }
                }
    if (!found) println("No solution was found")
}


Even or odd

Test whether an integer is even or odd.

There is more than one way to solve this task:

* Use the even and odd predicates, if the language provides them.
* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.
* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.
* Use modular congruences:
** ''i''  0 (mod 2) iff ''i'' is even.
** ''i''  1 (mod 2) iff ''i'' is odd.

Solution:
// version 1.0.5-2

fun main(args: Array<String>) {
    while (true) {
        print("Enter an integer or 0 to finish : ")
        val n = readLine()!!.toInt()
        when {
            n == 0     -> return
            n % 2 == 0 -> println("Your number is even")
            else       -> println("Your number is odd")
        }
    }
}


Evolutionary algorithm

Starting with:
* The target string: "METHINKS IT IS LIKE A WEASEL".
* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).
* A fitness function that computes the 'closeness' of its argument to the target string.
* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.
:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.
:* repeat until the parent converges, (hopefully), to the target.

;See also:
*   Wikipedia entry:   Weasel algorithm.
*   Wikipedia entry:   Evolutionary algorithm.

Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions

A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,
* While the parent is not yet the target:
:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.

Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges"

 (:* repeat until the parent converges, (hopefully), to the target.

Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!

As illustration of this error, the code for 8th has the following remark.

 Create a new string based on the TOS, '''changing randomly any characters which
 don't already match the target''':

''NOTE:'' this has been changed, the 8th version is completely random now

Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!

To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.

Solution:
import java.util.*

val target = "METHINKS IT IS LIKE A WEASEL"
val validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "

val random = Random()

fun randomChar() = validChars[random.nextInt(validChars.length)]
fun hammingDistance(s1: String, s2: String) =
        s1.zip(s2).map { if (it.first == it.second) 0 else 1 }.sum()

fun fitness(s1: String) = target.length - hammingDistance(s1, target)

fun mutate(s1: String, mutationRate: Double) =
        s1.map { if (random.nextDouble() > mutationRate) it else randomChar() }
                .joinToString(separator = "")

fun main(args: Array<String>) {
    val initialString = (0 until target.length).map { randomChar() }.joinToString(separator = "")

    println(initialString)
    println(mutate(initialString, 0.2))

    val mutationRate = 0.05
    val childrenPerGen = 50

    var i = 0
    var currVal = initialString
    while (currVal != target) {
        i += 1
        currVal = (0..childrenPerGen).map { mutate(currVal, mutationRate) }.maxBy { fitness(it) }!!
    }
    println("Evolution found target after $i generations")
}


Execute Brain****

Brainf***}}
RCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages.

Below are links to each of the versions of RCBF.

An implementation need only properly implement the following instructions:
{| class="wikitable"
!Command
!Description
|-
| style="text-align:center"| > || Move the pointer to the right
|-
| style="text-align:center"| < || Move the pointer to the left
|-
| style="text-align:center"| + || Increment the memory cell under the pointer
|-
| style="text-align:center"| - || Decrement the memory cell under the pointer
|-
| style="text-align:center"| . || Output the character signified by the cell at the pointer
|-
| style="text-align:center"| , || Input a character and store it in the cell at the pointer
|-
| style="text-align:center"| [ || Jump past the matching ] if the cell under the pointer is 0
|-
| style="text-align:center"| ] || Jump back to the matching [ if the cell under the pointer is nonzero
|}
Any cell size is allowed,   EOF    (End-O-File)   support is optional, as is whether you have bounded or unbounded memory.

Solution:
// version 1.1.2

class Brainf__k(val prog: String, memSize: Int) {
    private val mem = IntArray(memSize)
    private var ip = 0
    private var dp = 0
    private val memVal get() = mem.getOrElse(dp) { 0 }

    fun execute() {
        while (ip < prog.length) {
            when (prog[ip++]) {
                '>' -> dp++
                '<' -> dp--
                '+' -> mem[dp] = memVal + 1
                '-' -> mem[dp] = memVal - 1
                ',' -> mem[dp] = System.`in`.read()
                '.' -> print(memVal.toChar())
                '[' -> handleLoopStart()
                ']' -> handleLoopEnd()
            }
        }
    }

    private fun handleLoopStart() {
        if (memVal != 0) return
        var depth = 1
        while (ip < prog.length) {
            when (prog[ip++]) {
                '[' -> depth++
                ']' -> if (--depth == 0) return
            }
        }
        throw IllegalStateException("Could not find matching end bracket")
    }

    private fun handleLoopEnd() {
        var depth = 0
        while (ip >= 0) {
            when (prog[--ip]) {
                ']' -> depth++
                '[' -> if (--depth == 0) return
            }
        }
        throw IllegalStateException("Could not find matching start bracket")
    }
}

fun main(args: Array<String>) {
    val prog = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."
    Brainf__k(prog, 10).execute()
}


Execute HQ9+

Implement a   ''' [[HQ9+]] '''   interpreter or compiler.

Solution:
// version 1.1.3

fun hq9plus(code: String) {
    var acc = 0
    val sb = StringBuilder()
    for (c in code) {
        sb.append(
            when (c) {
                'h', 'H' -> "Hello, world!\n"
                'q', 'Q' -> code + "\n"
                '9'-> {
                    val sb2 = StringBuilder()
                    for (i in 99 downTo 1) {
                        val s = if (i > 1) "s" else ""
                        sb2.append("$i bottle$s of beer on the wall\n")
                        sb2.append("$i bottle$s of beer\n")
                        sb2.append("Take one down, pass it around\n")
                    }
                    sb2.append("No more bottles of beer on the wall!\n")
                    sb2.toString()
                 }
                '+'  -> { acc++; "" }  // yeah, it's weird!
                else -> throw IllegalArgumentException("Code contains illegal operation '$c'")
            }
        )
    }
    println(sb)
}

fun main(args: Array<String>) {
    val code = args[0]  // pass in code as command line argument (using hq9+)
    hq9plus(code)
}


Execute SNUSP

SNUSP}}'''RCSNUSP''' is a set of [[SNUSP compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCSNUSP.

An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.

Solution:
// version 1.1.2

// requires 5 chars (10 bytes) of data store
const val hw = """
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
      \==-<<<<+>+++/ /=.>.+>.--------.-/"""

// input is a multi-line string.
fun snusp(dlen: Int, raw: String) {
    val ds = CharArray(dlen)  // data store
    var dp = 0                // data pointer
    var s = raw

    // remove leading '\n' from string if present
    s = s.trimStart('\n')

    // make 2 dimensional instruction store and declare instruction pointers
    val cs = s.split('\n')
    var ipr = 0
    var ipc = 0

    // look for starting instruction
    findStart@  for ((r, row) in cs.withIndex()) {
        for ((i, c) in row.withIndex()) {
            if (c == '$') {
                ipr = r
                ipc = i
                break@findStart
            }
        }
    }

    var id = 0
    val step = fun() {
        if (id and 1 == 0)
            ipc += 1 - (id and 2)
        else
            ipr += 1 - (id and 2)
    }

    // execute
    while ((ipr in 0 until cs.size) && (ipc in 0 until cs[ipr].length)) {
        when (cs[ipr][ipc]) {
            '>'  -> dp++
            '<'  -> dp--
            '+'  -> ds[dp]++
            '-'  -> ds[dp]--
            '.'  -> print(ds[dp])
            ','  -> ds[dp] = readLine()!![0]
            '/'  -> id = id.inv()
            '\\' -> id = id xor 1
            '!'  -> step()
            '?'  -> if (ds[dp] == '\u0000') step()
        }
        step()
    }
}

fun main(args: Array<String>) {
    snusp(5, hw)
}


Exponentiation order

This task will demonstrate the order of exponentiation   ('''xy''')    when there are multiple exponents.

(Many programming languages,   especially those with extended-precision integer arithmetic,   usually support one of  **, ^, |  or some such for exponentiation.)

;Task requirements
Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).

If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.

Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):

::::*   5**3**2
::::*   (5**3)**2
::::*   5**(3**2)

If there are other methods (or formats) of multiple exponentiations, show them as well.

;See also:
* MathWorld entry:   exponentiation

;Related tasks:
*   exponentiation operator
*   arbitrary-precision integers (included)
*   [[Exponentiation with infix operators in (or operating on) the base]]

Solution:
// version 1.0.5-2

infix fun Int.ipow(exp: Int): Int = when {
    exp < 0   -> throw IllegalArgumentException("negative exponents not allowed")
    exp == 0  -> 1
    else      -> {
        var ans = 1
        var base = this
        var e = exp
        while(e != 0) {
            if (e and 1 == 1) ans *= base
            e = e shr 1
            base *= base
        }
        ans
    }
}

fun main(args: Array<String>) {
    println("5**3**2   = ${5 ipow 3 ipow 2}")
    println("(5**3)**2 = ${(5 ipow 3) ipow 2}")
    println("5**(3**2) = ${5 ipow (3 ipow 2)}")
}


Extend your language

{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.

If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:

Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:

   if (condition1isTrue) {
      if (condition2isTrue)
         bothConditionsAreTrue();
      else
         firstConditionIsTrue();
   }
   else if (condition2isTrue)
      secondConditionIsTrue();
   else
      noConditionIsTrue();

Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.

This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:

   if2 (condition1isTrue) (condition2isTrue)
      bothConditionsAreTrue();
   else1
      firstConditionIsTrue();
   else2
      secondConditionIsTrue();
   else
      noConditionIsTrue();

Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.

Solution:
// version 1.0.6

data class IfBoth(val cond1: Boolean, val cond2: Boolean) {
    fun elseFirst(func: () -> Unit): IfBoth {
        if (cond1 && !cond2) func()
        return this
    }

    fun elseSecond(func: () -> Unit): IfBoth {
        if (cond2 && !cond1) func()
        return this
    }

    fun elseNeither(func: () -> Unit): IfBoth {
        if (!cond1 && !cond2) func()
        return this  // in case it's called out of order
    }
}

fun ifBoth(cond1: Boolean, cond2: Boolean, func: () -> Unit): IfBoth {
    if (cond1 && cond2) func()
    return IfBoth(cond1, cond2)
}

fun main(args: Array<String>) {
    var a = 0
    var b = 1
    ifBoth (a == 1, b == 3) {
        println("a = 1 and b = 3")
    }
    .elseFirst {
        println("a = 1 and b <> 3")
    }
    .elseSecond {
        println("a <> 1 and b = 3")
    }
    .elseNeither {
        println("a <> 1 and b <> 3")
    }

    // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order
    a = 1
    b = 0
    ifBoth (a == 1, b == 3) {
        println("a = 1 and b = 3")
    }
    .elseNeither {
        println("a <> 1 and b <> 3")
    }
    .elseFirst {
        println("a = 1 and b <> 3")
    }
}


Extreme floating point values

The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.

The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.

Print the values of these variables if possible; and show some arithmetic with these values and variables.

If your language can directly enter these extreme floating point values then show it.

;See also:
*   What Every Computer Scientist Should Know About Floating-Point Arithmetic

;Related tasks:
*   [[Infinity]]
*   [[Detect division by zero]]
*   [[Literals/Floating point]]

Solution:
// version 1.0.5-2

@Suppress("DIVISION_BY_ZERO", "FLOAT_LITERAL_CONFORMS_ZERO")

fun main(args: Array<String>) {
    val inf     =  1.0 / 0.0
    val negInf  = -1.0 / 0.0
    val nan     =  0.0 / 0.0
    val negZero = -1.0e-325

    println("*** Indirect ***\n")
    println("Infinity          :  $inf")
    println("Negative infinity :  $negInf")
    println("Not a number      :  $nan")
    println("Negative zero     :  $negZero")

    println("\n*** Direct ***\n")
    println("Infinity          :  ${Double.POSITIVE_INFINITY}")
    println("Negative infinity :  ${Double.NEGATIVE_INFINITY}")
    println("Not a number      :  ${Double.NaN}")
    println("Negative zero     :  ${-0.0}")

    println("\n*** Calculations ***\n")
    println("inf * inf         :  ${inf * inf}")
    println("inf + negInf      :  ${inf + negInf}")
    println("nan / nan         :  ${nan / nan}")
    println("negZero + 0.0     :  ${negZero + 0.0}")
}


FASTA format

In FASTA.

A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.

;Task:
Write a program that reads a FASTA file such as:

>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED

Solution:
// version 1.1.2

import java.util.Scanner
import java.io.File

fun checkNoSpaces(s: String) = ' ' !in s && '\t' !in s

fun main(args: Array<String>) {
    var first = true
    val sc = Scanner(File("input.fasta"))
    while (sc.hasNextLine()) {
        val line = sc.nextLine()
        if (line[0] == '>') {
            if (!first) println()
            print("${line.substring(1)}: ")
            if (first) first = false
        }
        else if (first) {
            println("Error : File does not begin with '>'")
            break
        }
        else if (checkNoSpaces(line))
            print(line)
        else {
            println("\nError : Sequence contains space(s)")
            break
        }
    }
    sc.close()
}


Fairshare between two and more

The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)

The Thue-Morse sequence of ones-and-zeroes can be generated by:
:''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"''

;Sharing fairly between two or more:
Use this method:
:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''

;Task
Counting from zero;   using a function/method/routine to express an integer count in base '''b''',
sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.

Show the first 25 terms of the fairshare sequence:
:*   For two people:
:*   For three people
:*   For five people
:*   For eleven people

;Related tasks:
:*   [[Non-decimal radices/Convert]]
:*   [[Thue-Morse]]

;See also:
:*   A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))

Solution:
fun turn(base: Int, n: Int): Int {
    var sum = 0
    var n2 = n
    while (n2 != 0) {
        val re = n2 % base
        n2 /= base
        sum += re
    }
    return sum % base
}

fun fairShare(base: Int, count: Int) {
    print(String.format("Base %2d:", base))
    for (i in 0 until count) {
        val t = turn(base, i)
        print(String.format(" %2d", t))
    }
    println()
}

fun turnCount(base: Int, count: Int) {
    val cnt = IntArray(base) { 0 }
    for (i in 0 until count) {
        val t = turn(base, i)
        cnt[t]++
    }

    var minTurn = Int.MAX_VALUE
    var maxTurn = Int.MIN_VALUE
    var portion = 0
    for (i in 0 until base) {
        val num = cnt[i]
        if (num > 0) {
            portion++
        }
        if (num < minTurn) {
            minTurn = num
        }
        if (num > maxTurn) {
            maxTurn = num
        }
    }

    print("  With $base people: ")
    when (minTurn) {
        0 -> {
            println("Only $portion have a turn")
        }
        maxTurn -> {
            println(minTurn)
        }
        else -> {
            println("$minTurn or $maxTurn")
        }
    }
}

fun main() {
    fairShare(2, 25)
    fairShare(3, 25)
    fairShare(5, 25)
    fairShare(11, 25)

    println("How many times does each get a turn in 50000 iterations?")
    turnCount(191, 50000)
    turnCount(1377, 50000)
    turnCount(49999, 50000)
    turnCount(50000, 50000)
    turnCount(50001, 50000)
}


Farey sequence

The   Farey sequence   ''' ''F''n'''   of order   '''n'''   is the sequence of completely reduced fractions between   '''0'''   and   '''1'''   which, when in lowest terms, have denominators less than or equal to   '''n''',   arranged in order of increasing size.

The   ''Farey sequence''   is sometimes incorrectly called a   ''Farey series''.

Each Farey sequence:
:::*   starts with the value   '''0'''   (zero),   denoted by the fraction      \frac{0}{1}
:::*   ends with the value   '''1'''   (unity),   denoted by the fraction    \frac{1}{1}.

The Farey sequences of orders   '''1'''   to   '''5'''   are:

:::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}
:
:::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1}
:
:::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1}
:
:::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1}
:
:::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1}

;Task
*   Compute and show the Farey sequence for orders   '''1'''   through   '''11'''   (inclusive).
*   Compute and display the   ''number''   of fractions in the Farey sequence for order   '''100'''   through   '''1,000'''   (inclusive)   by hundreds.
*   Show the fractions as    '''n/d'''    (using the solidus [or slash] to separate the numerator from the denominator).

The length   (the number of fractions)   of a Farey sequence asymptotically approaches:

:::::::::::  3 x n2   /   \pi2

;See also:
*    OEIS sequence           A006842 numerators of Farey series of order 1, 2, ***
*    OEIS sequence           A006843 denominators of Farey series of order 1, 2, ***
*    OEIS sequence           A005728 number of fractions in Farey series of order n
*   MathWorld entry          Farey sequence
*   Wikipedia   entry   Farey sequence

Solution:
// version 1.1

fun farey(n: Int): List<String> {
    var a = 0
    var b = 1
    var c = 1
    var d = n
    val f = mutableListOf("$a/$b")
    while (c <= n) {
        val k = (n + b) / d
        val aa = a
        val bb = b
        a = c
        b = d
        c = k * c - aa
        d = k * d - bb
        f.add("$a/$b")
    }
    return f.toList()
}

fun main(args: Array<String>) {
    for (i in 1..11)
        println("${"%2d".format(i)}: ${farey(i).joinToString(" ")}")
    println()
    for (i in 100..1000 step 100)
        println("${"%4d".format(i)}: ${"%6d".format(farey(i).size)} fractions")
}


Fast Fourier transform

Calculate the   FFT   (Fast Fourier Transform)   of an input sequence.

The most general case allows for complex numbers at the input
and results in a sequence of equal length, again of complex numbers.
If you need to restrict yourself to real numbers, the output should
be the magnitude   (i.e.:   sqrt(re2 + im2))   of the complex result.

The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.

Solution:
object FFT {
    fun fft(a: Array<Complex>) = _fft(a, Complex(0.0, 2.0), 1.0)
    fun rfft(a: Array<Complex>) = _fft(a, Complex(0.0, -2.0), 2.0)

    private fun _fft(a: Array<Complex>, direction: Complex, scalar: Double): Array<Complex> =
            if (a.size == 1)
                a
            else {
                val n = a.size
                require(n % 2 == 0, { "The Cooley-Tukey FFT algorithm only works when the length of the input is even." })

                var (evens, odds) = Pair(emptyArray<Complex>(), emptyArray<Complex>())
                for (i in a.indices)
                    if (i % 2 == 0) evens += a[i]
                    else odds += a[i]
                evens = _fft(evens, direction, scalar)
                odds = _fft(odds, direction, scalar)

                val pairs = (0 until n / 2).map {
                    val offset = (direction * (java.lang.Math.PI * it / n)).exp * odds[it] / scalar
                    val base = evens[it] / scalar
                    Pair(base + offset, base - offset)
                }
                var (left, right) = Pair(emptyArray<Complex>(), emptyArray<Complex>())
                for ((l, r) in pairs) { left += l; right += r }
                left + right
            }
}


Feigenbaum constant calculation

Calculate the Feigenbaum constant.

;See:
:*   Details in the Wikipedia article:   Feigenbaum constant.

Solution:
// Version 1.2.40

fun feigenbaum() {
    val maxIt = 13
    val maxItJ = 10
    var a1 = 1.0
    var a2 = 0.0
    var d1 = 3.2
    println(" i       d")
    for (i in 2..maxIt) {
        var a = a1 + (a1 - a2) / d1
        for (j in 1..maxItJ) {
            var x = 0.0
            var y = 0.0
            for (k in 1..(1 shl i)) {
                 y = 1.0 - 2.0 * y * x
                 x = a - x * x
            }
            a -= x / y
        }
        val d = (a1 - a2) / (a - a1)
        println("%2d    %.8f".format(i,d))
        d1 = d
        a2 = a1
        a1 = a
    }
}

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


Fibonacci n-step number sequences

These number series are an expansion of the ordinary [[Fibonacci sequence]] where:
# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2
# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3
# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...
# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}

For small values of n, Greek numeric prefixes are sometimes used to individually name each series.

:::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2"
|+ Fibonacci n-step sequences
|- style="background-color: rgb(255, 204, 255);"
! n !! Series name !! Values
|-
|  2 ||  fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
|-
|  3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
|-
|  4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
|-
|  5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
|-
|  6 ||  hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
|-
|  7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
|-
|  8 ||  octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
|-
|  9 ||  nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
|-
| 10 ||  decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
|}

Allied sequences can be generated where the initial values are changed:
: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.

;Task:
# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.

;Related tasks:
*   [[Fibonacci sequence]]
*   Wolfram Mathworld
*   [[Hofstadter Q sequence]]
*   [[Leonardo numbers]]

;Also see:
*   Lucas Numbers - Numberphile (Video)
*   Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
*   Wikipedia, Lucas number
*   MathWorld, Fibonacci Number
*   Some identities for r-Fibonacci numbers
*   OEIS Fibonacci numbers
*   OEIS Lucas numbers

Solution:
// version 1.1.2

fun fibN(initial: IntArray, numTerms: Int) : IntArray {
    val n = initial.size
    require(n >= 2 && numTerms >= 0)
    val fibs = initial.copyOf(numTerms)
    if (numTerms <= n) return fibs
    for (i in n until numTerms) {
        var sum = 0
        for (j in i - n until i) sum += fibs[j]
        fibs[i] = sum
    }
    return fibs
}

fun main(args: Array<String>) {
    val names = arrayOf("fibonacci",  "tribonacci", "tetranacci", "pentanacci", "hexanacci",
                        "heptanacci", "octonacci",  "nonanacci",  "decanacci")
    val initial = intArrayOf(1, 1, 2, 4, 8, 16, 32, 64, 128, 256)
    println(" n  name        values")
    var values = fibN(intArrayOf(2, 1), 15).joinToString(", ")
    println("%2d  %-10s  %s".format(2, "lucas", values))
    for (i in 0..8) {
        values = fibN(initial.sliceArray(0 until i + 2), 15).joinToString(", ")
        println("%2d  %-10s  %s".format(i + 2, names[i], values))
    }
}


Fibonacci word

The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence    as described here:

     Define   F_Word1   as   '''1'''
     Define   F_Word2   as   '''0'''
     Form     F_Word3   as   F_Word2     concatenated with   F_Word1    i.e.:   '''01'''
     Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-2

;Task:
Perform the above steps for     n = 37.

You may display the first few but not the larger values of   n.
{Doing so will get the task's author into trouble with them what be (again!).}

Instead, create a table for   F_Words   '''1'''   to   '''37'''   which shows:
::*   The number of characters in the word
::*   The word's [[Entropy]]

;Related tasks:
*   Fibonacci word/fractal
*   [[Entropy]]
*   [[Entropy/Narcissist]]

Solution:
// version 1.0.6

fun fibWord(n: Int): String {
    if (n < 1) throw IllegalArgumentException("Argument can't be less than 1")
    if (n == 1) return "1"
    val words = Array(n){ "" }
    words[0] = "1"
    words[1] = "0"
    for (i in 2 until n) words[i] = words[i - 1] + words[i - 2]
    return words[n - 1]
}

fun log2(d: Double) = Math.log(d) / Math.log(2.0)

fun shannon(s: String): Double {
    if (s.length <= 1) return 0.0
    val count0 = s.count { it == '0' }
    val count1 = s.length - count0
    val nn = s.length.toDouble()
    return -(count0 / nn * log2(count0 / nn) + count1 / nn * log2(count1 / nn))
}

fun main(args: Array<String>) {
    println("N    Length       Entropy             Word")
    println("--  --------  ------------------  ----------------------------------")
    for (i in 1..37) {
        val s = fibWord(i)
        print(String.format("%2d  %8d  %18.16f", i, s.length, shannon(s)))
        if (i < 10) println("  $s")
        else println()
    }
}


File extension is in extensions list

Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.

It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.

For these reasons, this task exists in addition to the [[Extract file extension]] task.

;Related tasks:
* [[Extract file extension]]
* [[String matching]]

Solution:
// version 1.1

/* implicitly allows for extensions containing dots */
fun String.isFileExtensionListed(extensions: List<String>): Boolean {
    return extensions.any { toLowerCase().endsWith("." + it.toLowerCase()) }
}

fun main(args: Array<String>) {
    val extensions = listOf("zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2")
    val fileNames  = listOf(
        "MyData.a##",
        "MyData.tar.Gz",
        "MyData.gzip",
        "MyData.7z.backup",
        "MyData...",
        "MyData",
        "MyData_v1.0.tar.bz2",
        "MyData_v1.0.bz2"
    )

    for (fileName in fileNames) {
        println("${fileName.padEnd(19)} -> ${fileName.isFileExtensionListed(extensions)}")
    }
}


File size distribution

Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.

My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.

Don't forget that empty files may exist, to serve as a marker.

Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?

Solution:
// version 1.2.10

import java.io.File
import kotlin.math.log10
import kotlin.math.floor

fun fileSizeDistribution(path: String) {
    val sizes = IntArray(12)
    val p = File(path)
    val files = p.walk()
    var accessible = 0
    var notAccessible = 0
    var totalSize = 0L
    for (file in files) {
        try {
            if (file.isFile()) {
                val len = file.length()
                accessible++
                if (len == 0L) {
                    sizes[0]++
                    continue
                }
                totalSize += len
                val logLen = log10(len.toDouble())
                val index = floor(logLen).toInt()
                sizes[index + 1]++
            }
        }
        catch (se: SecurityException) {
            notAccessible++
        }
    }

    println("File size distribution for '$path' :-\n")
    for (i in 0 until sizes.size) {
        print(if (i == 0) "  " else "+ ")
        print("Files less than 10 ^ ${"%-2d".format(i)} bytes : ")
        println("%5d".format(sizes[i]))
    }
    println("                                  -----")
    println("= Number of accessible files    : ${"%5d".format(accessible)}")
    println("\n  Total size in bytes           : $totalSize")
    println("\n  Number of inaccessible files  : ${"%5d".format(notAccessible)}")
}

fun main(args: Array<String>) {
    fileSizeDistribution("./")  // current directory
}


Find if a point is within a triangle

Find if a point is within a triangle.

;Task:

::*   Assume points are on a plane defined by (x, y) real number coordinates.

::*   Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC.

::*   You may use any algorithm.

::*   Bonus: explain why the algorithm you chose works.

;Related tasks:
*   [[Determine_if_two_triangles_overlap]]

;Also see:
:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]
:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]
:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]
:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]

Solution:
import kotlin.math.max
import kotlin.math.min

private const val EPS = 0.001
private const val EPS_SQUARE = EPS * EPS

private fun test(t: Triangle, p: Point) {
    println(t)
    println("Point $p is within triangle ? ${t.within(p)}")
}

fun main() {
    var p1 = Point(1.5, 2.4)
    var p2 = Point(5.1, -3.1)
    var p3 = Point(-3.8, 1.2)
    var tri = Triangle(p1, p2, p3)
    test(tri, Point(0.0, 0.0))
    test(tri, Point(0.0, 1.0))
    test(tri, Point(3.0, 1.0))
    println()
    p1 = Point(1.0 / 10, 1.0 / 9)
    p2 = Point(100.0 / 8, 100.0 / 3)
    p3 = Point(100.0 / 4, 100.0 / 9)
    tri = Triangle(p1, p2, p3)
    val pt = Point(p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y))
    test(tri, pt)
    println()
    p3 = Point(-100.0 / 8, 100.0 / 6)
    tri = Triangle(p1, p2, p3)
    test(tri, pt)
}

class Point(val x: Double, val y: Double) {
    override fun toString(): String {
        return "($x, $y)"
    }
}

class Triangle(private val p1: Point, private val p2: Point, private val p3: Point) {
    private fun pointInTriangleBoundingBox(p: Point): Boolean {
        val xMin = min(p1.x, min(p2.x, p3.x)) - EPS
        val xMax = max(p1.x, max(p2.x, p3.x)) + EPS
        val yMin = min(p1.y, min(p2.y, p3.y)) - EPS
        val yMax = max(p1.y, max(p2.y, p3.y)) + EPS
        return !(p.x < xMin || xMax < p.x || p.y < yMin || yMax < p.y)
    }

    private fun nativePointInTriangle(p: Point): Boolean {
        val checkSide1 = side(p1, p2, p) >= 0
        val checkSide2 = side(p2, p3, p) >= 0
        val checkSide3 = side(p3, p1, p) >= 0
        return checkSide1 && checkSide2 && checkSide3
    }

    private fun distanceSquarePointToSegment(p1: Point, p2: Point, p: Point): Double {
        val p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)
        val dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength
        if (dotProduct < 0) {
            return (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y)
        }
        if (dotProduct <= 1) {
            val pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y)
            return pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength
        }
        return (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y)
    }

    private fun accuratePointInTriangle(p: Point): Boolean {
        if (!pointInTriangleBoundingBox(p)) {
            return false
        }
        if (nativePointInTriangle(p)) {
            return true
        }
        if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {
            return true
        }
        return if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {
            true
        } else distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE
    }

    fun within(p: Point): Boolean {
        return accuratePointInTriangle(p)
    }

    override fun toString(): String {
        return "Triangle[$p1, $p2, $p3]"
    }

    companion object {
        private fun side(p1: Point, p2: Point, p: Point): Double {
            return (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y)
        }
    }
}


Find limit of recursion

{{selection|Short Circuit|Console Program Basics}}

;Task:
Find the limit of recursion.

Solution:
// version 1.1.2

fun recurse(i: Int) {
    try {
        recurse(i + 1)
    }
    catch(e: StackOverflowError) {
        println("Limit of recursion is $i")
    }
}

fun main(args: Array<String>) = recurse(0)