IMPORT JAVA.TEXT.*
IMPORT JAVA.UTIL.*
IMPORT JAVA.IO.PRINTSTREAM

INTERNAL FUN PRINTSTREAM.PRINTCALENDAR(YEAR: INT, NCOLS: BYTE, LOCALE: LOCALE?) {
    IF (NCOLS < 1 || NCOLS > 12)
        THROW ILLEGALARGUMENTEXCEPTION("ILLEGAL COLUMN WIDTH.")
    VAL W = NCOLS * 24
    VAL NROWS = MATH.CEIL(12.0 / NCOLS).TOINT()

    VAL DATE = GREGORIANCALENDAR(YEAR, 0, 1)
    VAR OFFS = DATE.GET(CALENDAR.DAY_OF_WEEK) - 1

    VAL DAYS = DATEFORMATSYMBOLS(LOCALE).SHORTWEEKDAYS.SLICE(1..7).MAP { IT.SLICE(0..1) }.JOINTOSTRING(" ", " ")
    VAL MONS = ARRAY(12) { ARRAY(8) { "" } }
    DATEFORMATSYMBOLS(LOCALE).MONTHS.SLICE(0..11).FOREACHINDEXED { M, NAME ->
        VAL LEN = 11 + NAME.LENGTH / 2
        VAL FORMAT = MESSAGEFORMAT.FORMAT("%{0}S%{1}S", LEN, 21 - LEN)
        MONS[M][0] = STRING.FORMAT(FORMAT, NAME, "")
        MONS[M][1] = DAYS
        VAL DIM = DATE.GETACTUALMAXIMUM(CALENDAR.DAY_OF_MONTH)
        FOR (D IN 1..42) {
            VAL ISDAY = D > OFFS && D <= OFFS + DIM
            VAL ENTRY = IF (ISDAY) STRING.FORMAT(" %2S", D - OFFS) ELSE "   "
            IF (D % 7 == 1)
                MONS[M][2 + (D - 1) / 7] = ENTRY
            ELSE
                MONS[M][2 + (D - 1) / 7] += ENTRY
        }
        OFFS = (OFFS + DIM) % 7
        DATE.ADD(CALENDAR.MONTH, 1)
    }

    PRINTF("%" + (W / 2 + 10) + "S%N", "[SNOOPY PICTURE]")
    PRINTF("%" + (W / 2 + 4) + "S%N%N", YEAR)

    FOR (R IN 0..NROWS - 1) {
        FOR (I IN 0..7) {
            VAR C = R * NCOLS
            WHILE (C < (R + 1) * NCOLS && C < 12) {
                PRINTF("   %S", MONS[C][I].TOUPPERCASE())  // ORIGINAL CHANGED TO PRINT IN UPPER CASE
                C++
            }
            PRINTLN()
        }
        PRINTLN()
    }
}

FUN MAIN(ARGS: ARRAY<STRING>) {
    SYSTEM.OUT.PRINTCALENDAR(1969, 3, LOCALE.US)
}

// version 1.1.3

import java.io.File
import java.io.BufferedReader
import java.io.InputStreamReader

fun main(args: Array<String>) {
    val keywords = listOf(
        "import", "internal", "fun", "if", "throw", "val", "var", "for", "in", "while"
    )

    val singleCase = listOf(
        "java.text",
        "java.util",
        "java.io",
        "else",     // really a keyword but doesn't have a following space here
        "ceil",
        "it",       // really a keyword but doesn't have a following space here
        "get(",     // also included in GETACTUALMAXIMUM
        "slice",
        "map",
        "months",
        "length",
        ".format",  // also variable called FORMAT
        "add",
        "printf",
        "println",
        "out",
        "main",
        "args",
        "s%{1}s",
        "%2s",
        "s%n%n",
        "s%n",
        "%s"
    )

    val mixedCase = listOf(
        "PRINTSTREAM" to "PrintStream",
        "INT," to "Int,",  // also included in PRINTCALENDAR
        "BYTE" to "Byte",
        "LOCALE?" to "Locale?",  // also variable called LOCALE
        "LOCALE." to "Locale.",
        "ILLEGALARGUMENTEXCEPTION" to "IllegalArgumentException",
        "MATH" to "Math",
        "GREGORIANCALENDAR" to "GregorianCalendar",
        "DATEFORMATSYMBOLS" to "DateFormatSymbols",
        "ARRAY" to "Array",
        "MESSAGEFORMAT" to "MessageFormat",
        "JOINTOSTRING" to "joinToString",
        "STRING" to "String",
        "CALENDAR." to "Calendar.", // also included in PRINTCALENDAR
        "SYSTEM" to "System",
        "TOINT" to "toInt",
        "SHORTWEEKDAYS" to "shortWeekdays",
        "FOREACHINDEXED" to "forEachIndexed",
        "GETACTUALMAXIMUM" to "getActualMaximum",
        "TOUPPERCASE" to "toUpperCase"
    )

    var text = File("calendar_UC.txt").readText()
    for (k in keywords)   text = text.replace("${k.toUpperCase()} ", "$k ") // add a following space to be on safe side
    for (s in singleCase) text = text.replace(s.toUpperCase(), s)
    for (m in mixedCase)  text = text.replace(m.first, m.second)
    File("calendar_NC.kt").writeText(text)
    val commands = listOf("kotlinc", "calendar_NC.kt", "-include-runtime", "-d", "calendar_X.jar")
    val pb = ProcessBuilder(commands)
    pb.redirectErrorStream(true)
    val process = pb.start()
    process.waitFor()
    val commands2 = listOf("java", "-jar", "calendar_NC.jar")
    val pb2 = ProcessBuilder(commands2)
    pb2.redirectErrorStream(true)
    val process2 = pb2.start()
    val out = StringBuilder()
    val br = BufferedReader(InputStreamReader(process2.inputStream))
    while (true) {
        val line = br.readLine()
        if (line == null) break
        out.append(line).append('\n')
    }
    br.close()
    println(out.toString())
}

import java.text.*
import java.util.*
import java.io.PrintStream

internal fun PrintStream.PRINTCALENDAR(YEAR: Int, NCOLS: Byte, LOCALE: Locale?) {
    if (NCOLS < 1 || NCOLS > 12)
        throw IllegalArgumentException("ILLEGAL COLUMN WIDTH.")
    val W = NCOLS * 24
    val NROWS = Math.ceil(12.0 / NCOLS).toInt()

    val DATE = GregorianCalendar(YEAR, 0, 1)
    var OFFS = DATE.get(Calendar.DAY_OF_WEEK) - 1

    val DAYS = DateFormatSymbols(LOCALE).shortWeekdays.slice(1..7).map { it.slice(0..1) }.joinToString(" ", " ")
    val MONS = Array(12) { Array(8) { "" } }
    DateFormatSymbols(LOCALE).months.slice(0..11).forEachIndexed { M, NAME ->
        val LEN = 11 + NAME.length / 2
        val FORMAT = MessageFormat.format("%{0}s%{1}s", LEN, 21 - LEN)
        MONS[M][0] = String.format(FORMAT, NAME, "")
        MONS[M][1] = DAYS
        val DIM = DATE.getActualMaximum(Calendar.DAY_OF_MONTH)
        for (D in 1..42) {
            val ISDAY = D > OFFS && D <= OFFS + DIM
            val ENTRY = if (ISDAY) String.format(" %2s", D - OFFS) else "   "
            if (D % 7 == 1)
                MONS[M][2 + (D - 1) / 7] = ENTRY
            else
                MONS[M][2 + (D - 1) / 7] += ENTRY
        }
        OFFS = (OFFS + DIM) % 7
        DATE.add(Calendar.MONTH, 1)
    }

    printf("%" + (W / 2 + 10) + "s%n", "[SNOOPY PICTURE]")
    printf("%" + (W / 2 + 4) + "s%n%n", YEAR)

    for (R in 0..NROWS - 1) {
        for (I in 0..7) {
            var C = R * NCOLS
            while (C < (R + 1) * NCOLS && C < 12) {
                printf("   %s", MONS[C][I].toUpperCase())  // ORIGINAL CHANGED TO PRINT in UPPER CASE
                C++
            }
            println()
        }
        println()
    }
}

fun main(args: Array<String>) {
    System.out.PRINTCALENDAR(1969, 3, Locale.US)
}

                              [SNOOPY PICTURE]
                                    1969

          JANUARY                 FEBRUARY                 MARCH
    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA
              1  2  3  4                       1                       1
     5  6  7  8  9 10 11     2  3  4  5  6  7  8     2  3  4  5  6  7  8
    12 13 14 15 16 17 18     9 10 11 12 13 14 15     9 10 11 12 13 14 15
    19 20 21 22 23 24 25    16 17 18 19 20 21 22    16 17 18 19 20 21 22
    26 27 28 29 30 31       23 24 25 26 27 28       23 24 25 26 27 28 29
                                                    30 31

           APRIL                    MAY                     JUNE
    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA
           1  2  3  4  5                 1  2  3     1  2  3  4  5  6  7
     6  7  8  9 10 11 12     4  5  6  7  8  9 10     8  9 10 11 12 13 14
    13 14 15 16 17 18 19    11 12 13 14 15 16 17    15 16 17 18 19 20 21
    20 21 22 23 24 25 26    18 19 20 21 22 23 24    22 23 24 25 26 27 28
    27 28 29 30             25 26 27 28 29 30 31    29 30

            JULY                   AUGUST                SEPTEMBER
    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA
           1  2  3  4  5                    1  2        1  2  3  4  5  6
     6  7  8  9 10 11 12     3  4  5  6  7  8  9     7  8  9 10 11 12 13
    13 14 15 16 17 18 19    10 11 12 13 14 15 16    14 15 16 17 18 19 20
    20 21 22 23 24 25 26    17 18 19 20 21 22 23    21 22 23 24 25 26 27
    27 28 29 30 31          24 25 26 27 28 29 30    28 29 30
                            31

          OCTOBER                 NOVEMBER                DECEMBER
    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA    SU MO TU WE TH FR SA
              1  2  3  4                       1        1  2  3  4  5  6
     5  6  7  8  9 10 11     2  3  4  5  6  7  8     7  8  9 10 11 12 13
    12 13 14 15 16 17 18     9 10 11 12 13 14 15    14 15 16 17 18 19 20
    19 20 21 22 23 24 25    16 17 18 19 20 21 22    21 22 23 24 25 26 27
    26 27 28 29 30 31       23 24 25 26 27 28 29    28 29 30 31
                            30

The code provides an algorithm for a calendar task, formatted to fit a page that is 132 characters wide, and is entirely in uppercase, inspired by 1969 era line printers and the article "Real programmers think in UPPERCASE". The code also considers the limitations of the Kotlin language, which is case-sensitive, by saving the uppercase version of the Calendar program to a text file, and then creating a separate program that makes minimum changes to the uppercase text file to make it runnable. The output is a calendar with a placeholder for a Snoopy image.


Translation of: Go

// version 1.1.2

var total = 0L
var prim = 0L
var maxPeri = 0L

fun newTri(s0: Long, s1: Long, s2: Long) {
    val p = s0 + s1 + s2
    if (p <= maxPeri) {
        prim++
        total += maxPeri / p
        newTri( s0 - 2 * s1 + 2 * s2,  2 * s0 - s1 + 2 * s2,  2 * s0 - 2 * s1 + 3 * s2)
        newTri( s0 + 2 * s1 + 2 * s2,  2 * s0 + s1 + 2 * s2,  2 * s0 + 2 * s1 + 3 * s2)
        newTri(-s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2)
    }
}

fun main(args: Array<String>) {
    maxPeri = 100
    while (maxPeri <= 10_000_000_000L) {
        prim = 0
        total = 0
        newTri(3, 4, 5)
        println("Up to $maxPeri: $total triples, $prim primatives")
        maxPeri *= 10
    }
}

The code calculates the number of Pythagorean triples with a perimeter not exceeding a given limit, and also determines how many of these triples are primitive. It is optimized to handle large perimeter values up to 10 billion.


Translation of: Java
import javax.swing.JFrame

fun main(args : Array<String>) {
    JFrame("Title").apply {
        setSize(800, 600)
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }
}

"Creates an empty GUI window that can respond to close requests."


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val text = File("input.txt").readText().toLowerCase()
    val letterMap = text.filter { it in 'a'..'z' }.groupBy { it }.toSortedMap()
    for (letter in letterMap) println("${letter.key} = ${letter.value.size}")
    val sum = letterMap.values.sumBy { it.size }
    println("\nTotal letters = $sum")
}

Open a text file 'input.txt', count the frequency of each letter from A to Z, and also count all characters including punctuation. The text file contains two pangrams.


// version 1.1.2

class Node<T: Number>(var data: T, var next: Node<T>? = null) {
    override fun toString(): String {
        val sb = StringBuilder(this.data.toString())
        var node = this.next
        while (node != null) {
            sb.append(" -> ", node.data.toString())
            node = node.next
        }
        return sb.toString()
    }
}

fun main(args: Array<String>) {
    val n = Node(1, Node(2, Node(3)))
    println(n)
}

define a data structure for a singly-linked list element. This element contains a data member for storing a numeric value and a mutable link to the next element in the list.


Translation of: Java
// version 1.1.2

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

class FractalTree : JFrame("Fractal Tree") {
    init {
        background = Color.black
        setBounds(100, 100, 800, 600)
        isResizable = false
        defaultCloseOperation = EXIT_ON_CLOSE
    }

    private fun drawTree(g: Graphics, x1: Int, y1: Int, angle: Double, depth: Int) {
        if (depth == 0) return
        val x2 = x1 + (Math.cos(Math.toRadians(angle)) * depth * 10.0).toInt()
        val y2 = y1 + (Math.sin(Math.toRadians(angle)) * depth * 10.0).toInt()
        g.drawLine(x1, y1, x2, y2)
        drawTree(g, x2, y2, angle - 20, depth - 1)
        drawTree(g, x2, y2, angle + 20, depth - 1)
    }

    override fun paint(g: Graphics) {
        g.color = Color.white
        drawTree(g, 400, 500, -90.0, 9)
    }
}

fun main(args: Array<String>) {
    FractalTree().isVisible = true
}

generate and draw a fractal tree by first drawing the trunk, then splitting the trunk at the end by a certain angle to form two branches, and repeating this process until a desired level of branching is reached.


fun printFactors(n: Int) {
    if (n < 1) return
    print("$n => ")
    (1..n / 2)
        .filter { n % it == 0 }
        .forEach { print("$it ") }
    println(n)
}

fun main(args: Array<String>) {
    val numbers = intArrayOf(11, 21, 32, 45, 67, 96)
    for (number in numbers) printFactors(number)
}

compute the factors of a given positive integer, excluding zero and negative numbers. The factors are the positive integers that can divide the input number to yield a positive integer. For prime numbers, the factors are 1 and the number itself.


import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths

enum class AlignFunction {
    LEFT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + s.length + 's').format(s)) },
    RIGHT { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + l + 's').format(s)) },
    CENTER { override fun invoke(s: String, l: Int) = ("%-" + l + 's').format(("%" + ((l + s.length) / 2) + 's').format(s)) };

    abstract operator fun invoke(s: String, l: Int): String
}

/** Aligns fields into columns, separated by "|".
 * @constructor Initializes columns aligner from lines in a list of strings.
 * @property lines Lines in a single string. Empty string does form a column.
 */
class ColumnAligner(val lines: List<String>) {
     operator fun invoke(a: AlignFunction) : String {
        var result = ""
        for (lineWords in words) {
            for (i in lineWords.indices) {
                if (i == 0)
                    result += '|'
                result += a(lineWords[i], column_widths[i])
                result += '|'
            }
            result += '\n'
        }
        return result
    }

    private val words = arrayListOf<Array<String>>()
    private val column_widths = arrayListOf<Int>()

    init {
        lines.forEach  {
            val lineWords = java.lang.String(it).split("\\$")
            words += lineWords
            for (i in lineWords.indices) {
                if (i >= column_widths.size) {
                    column_widths += lineWords[i].length
                } else {
                    column_widths[i] = Math.max(column_widths[i], lineWords[i].length)
                }
            }
        }
    }
}

fun main(args: Array<String>) {
    if (args.isEmpty()) {
        println("Usage: ColumnAligner file [L|R|C]")
        return
    }
    val ca = ColumnAligner(Files.readAllLines(Paths.get(args[0]), StandardCharsets.UTF_8))
    val alignment = if (args.size >= 2) args[1] else "L"
    when (alignment) {
        "L" -> print(ca(AlignFunction.LEFT))
        "R" -> print(ca(AlignFunction.RIGHT))
        "C" -> print(ca(AlignFunction.CENTER))
        else -> System.err.println("Error! Unknown alignment: " + alignment)
    }
}

The code reads a text file with lines separated by a dollar character. It aligns each column of fields by ensuring at least one space between words in each column. It also allows each word in a column to be left, right, or center justified. The minimum space between columns is computed from the text, not hard-coded. Trailing dollar characters or consecutive spaces at the end of lines do not affect the alignment. The output is suitable for viewing in a mono-spaced font on a plain text editor or basic terminal.


Translation of: Java
// version 1.1

import java.awt.*
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.*

class Cuboid: 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)
    )

    private var mouseX: Int = 0
    private var prevMouseX: Int = 0
    private var mouseY: Int = 0
    private var prevMouseY: Int = 0

    init {
        preferredSize = Dimension(640, 640)
        background = Color.white
        scale(80.0, 120.0, 160.0)
        rotateCube(Math.PI / 5.0, Math.PI / 9.0)
        addMouseListener(object: MouseAdapter() {
            override fun mousePressed(e: MouseEvent) {
                mouseX = e.x
                mouseY = e.y
            }
        })

        addMouseMotionListener(object: MouseAdapter() {
            override fun mouseDragged(e: MouseEvent) {
                prevMouseX = mouseX
                prevMouseY = mouseY
                mouseX = e.x
                mouseY = e.y
                val incrX = (mouseX - prevMouseX) * 0.01
                val incrY = (mouseY - prevMouseY) * 0.01
                rotateCube(incrX, incrY)
                repaint()
            }
        })
    }

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

    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 = "Cuboid"
        f.isResizable = false
        f.add(Cuboid(), BorderLayout.CENTER)
        f.pack()
        f.setLocationRelativeTo(null)
        f.isVisible = true
    }
}

generate a graphical or ASCII art representation of a cuboid with dimensions 2x3x4, ensuring three faces are visible, and allowing for either static or rotational projection.


import org.apache.directory.api.ldap.model.exception.LdapException
import org.apache.directory.ldap.client.api.LdapNetworkConnection
import java.io.IOException
import java.util.logging.Level
import java.util.logging.Logger

class LDAP(map: Map<String, String>) {
    fun run() {
        var connection: LdapNetworkConnection? = null
        try {
            if (info) log.info("LDAP Connection to $hostname on port $port")
            connection = LdapNetworkConnection(hostname, port.toInt())

            try {
                if (info) log.info("LDAP bind")
                connection.bind()
            } catch (e: LdapException) {
                log.severe(e.toString())
            }

            try {
                if (info) log.info("LDAP unbind")
                connection.unBind()
            } catch (e: LdapException) {
                log.severe(e.toString())
            }
        } finally {
            try {
                if (info) log.info("LDAP close connection")
                connection!!.close()
            } catch (e: IOException) {
                log.severe(e.toString())
            }
        }
    }

    private val log = Logger.getLogger(LDAP::class.java.name)
    private val info = log.isLoggable(Level.INFO)
    private val hostname: String by map
    private val port: String by map
}

fun main(args: Array<String>) = LDAP(mapOf("hostname" to "localhost", "port"  to "10389")).run()

establish a connection to an Active Directory or Lightweight Directory Access Protocol server.


import java.io.*

fun String.rot13() = map {
    when {
        it.isUpperCase() -> { val x = it + 13; if (x > 'Z') x - 26 else x }
        it.isLowerCase() -> { val x = it + 13; if (x > 'z') x - 26 else x }
        else -> it
    } }.toCharArray()

fun InputStreamReader.println() =
        try { BufferedReader(this).forEachLine { println(it.rot13()) } }
        catch (e: IOException) { e.printStackTrace() }

fun main(args: Array<String>) {
    if (args.any())
        args.forEach { FileReader(it).println() }
    else
        InputStreamReader(System.`in`).println()
}

implement a rot-13 function that replaces every letter of the ASCII alphabet with the letter which is "rotated" 13 characters around the 26 letter alphabet. The function should work on both upper and lower case letters, preserve case, and pass all non-alphabetic characters without alteration. Optionally, the function can be wrapped in a utility program that performs rot-13 encoding line-by-line for every line of input in each file listed on its command line or acts as a filter on its standard input.


// version 1.1

data class Employee(val name: String, var category: String) : Comparable<Employee> {
    override fun compareTo(other: Employee) = this.name.compareTo(other.name)
}

fun main(args: Array<String>) {
    val employees = arrayOf(
        Employee("David", "Manager"),
        Employee("Alice", "Sales"),
        Employee("Joanna", "Director"),
        Employee("Henry", "Admin"),
        Employee("Tim", "Sales"),
        Employee("Juan", "Admin")
    )
    employees.sort()
    for ((name, category) in employees) println("${name.padEnd(6)} : $category")
}

sort an array of composite structures, specifically name-value pairs, by the key name using a custom comparator.


fun main(args: Array<String>) {
    (1..5).forEach {
        (1..it).forEach { print('*') }
        println()
    }
}

demonstrate how to use nested for loops to print a specific pattern. The number of iterations in the inner loop is controlled by the outer loop, resulting in a pattern of increasing asterisks.


Translation of: Java
fun main(args: Array<String>) {
    // map definition:
    val map = mapOf("foo" to 5,
                    "bar" to 10,
                    "baz" to 15,
                    "foo" to 6)

    // retrieval:
    println(map["foo"]) // => 6
    println(map["invalid"]) // => null

    // check keys:
    println("foo" in map) // => true
    println("invalid" in map) // => false

    // iterate over keys:
    for (k in map.keys) print("$k ")
    println()

    // iterate over values:
    for (v in map.values) print("$v ")
    println()

    // iterate over key, value pairs:
    for ((k, v) in map) println("$k => $v")
}

"Create an associative array, also known as a dictionary, map, or hash."


// version 1.1.3

class Lcg(val a: Long, val c: Long, val m: Long, val d: Long, val s: Long) {
    private var state = s

    fun nextInt(): Long {
        state = (a * state + c) % m
        return state / d
    }
}

fun main(args: Array<String>) {
    println("First 10 BSD random numbers - seed 0")
    val bsd = Lcg(1103515245, 12345, 1 shl 31, 1, 0)
    for (i in 1..10) println("${bsd.nextInt()}")
    println("\nFirst 10 MSC random numbers - seed 0")
    val msc = Lcg(214013, 2531011, 1 shl 31, 1 shl 16, 0)
    for (i in 1..10) println("${msc.nextInt()}")
}

The code implements two historic random number generators: the rand() function from BSD libc and the rand() function from the Microsoft C Runtime (MSCVRT.DLL). These generators use the linear congruential generator formula with specific constants. The generators produce a sequence of integers, starting from a seed value, that is not cryptographically secure but can be used for simple tasks. The BSD generator outputs numbers in the range 0 to 2147483647, while the Microsoft generator outputs numbers in the range 0 to 32767.


// version 1.1.2

class Node<T: Number>(var data: T, var next: Node<T>? = null) {
    override fun toString(): String {
        val sb = StringBuilder(this.data.toString())
        var node = this.next
        while (node != null) {
            sb.append(" -> ", node.data.toString())
            node = node.next
        }
        return sb.toString()
    }
}

fun <T: Number> insertAfter(prev: Node<T>, new: Node<T>) {
    new.next = prev.next
    prev.next = new
}

fun main(args: Array<String>) {
    val b = Node(3)
    val a = Node(1, b)
    println("Before insertion : $a")
    val c = Node(2)
    insertAfter(a, c)
    println("After  insertion : $a")
}

"Defines a method to insert an element into a singly-linked list after a specified element. Specifically, it inserts element C into a list of elements A->B, after element A."


// version 1.1.2

fun halve(n: Int) = n / 2

fun double(n: Int) = n * 2

fun isEven(n: Int) = n % 2 == 0

fun ethiopianMultiply(x: Int, y: Int): Int {
    var xx = x
    var yy = y
    var sum = 0
    while (xx >= 1) {
       if (!isEven(xx)) sum += yy
       xx = halve(xx)
       yy = double(yy)
    }
    return sum
}

fun main(args: Array<String>) {
    println("17 x 34 = ${ethiopianMultiply(17, 34)}")
    println("99 x 99 = ${ethiopianMultiply(99, 99)}")
}

The code defines three functions for halving an integer, doubling an integer, and checking if an integer is even. These functions are used to implement Ethiopian multiplication, a method of multiplying integers using addition, doubling, and halving. The multiplication process involves creating a table, discarding rows with even numbers in the left column, and summing the remaining values in the right column.


Translation of: C
// version 1.1.3

import java.util.Random

const val N_CARDS = 4
const val SOLVE_GOAL = 24
const val MAX_DIGIT = 9

class Frac(val num: Int, val den: Int)

enum class OpType { NUM, ADD, SUB, MUL, DIV }

class Expr(
    var op:    OpType = OpType.NUM,
    var left:  Expr?  = null,
    var right: Expr?  = null,
    var value: Int    = 0
)

fun showExpr(e: Expr?, prec: OpType, isRight: Boolean) {
    if (e == null) return
    val op = when (e.op) {
        OpType.NUM -> { print(e.value); return }
        OpType.ADD -> " + "
        OpType.SUB -> " - "
        OpType.MUL -> " x "
        OpType.DIV -> " / "
    }

    if ((e.op == prec && isRight) || e.op < prec) print("(")
    showExpr(e.left, e.op, false)
    print(op)
    showExpr(e.right, e.op, true)
    if ((e.op == prec && isRight) || e.op < prec) print(")")
}

fun evalExpr(e: Expr?): Frac {
    if (e == null) return Frac(0, 1)
    if (e.op == OpType.NUM) return Frac(e.value, 1)
    val l = evalExpr(e.left)
    val r = evalExpr(e.right)
    return when (e.op) {
        OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den)
        OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den)
        OpType.MUL -> Frac(l.num * r.num, l.den * r.den)
        OpType.DIV -> Frac(l.num * r.den, l.den * r.num)
        else       -> throw IllegalArgumentException("Unknown op: ${e.op}")
    }
}

fun solve(ea: Array<Expr?>, len: Int): Boolean {
    if (len == 1) {
        val final = evalExpr(ea[0])
        if (final.num == final.den * SOLVE_GOAL && final.den != 0) {
            showExpr(ea[0], OpType.NUM, false)
            return true
        }
    }

    val ex = arrayOfNulls<Expr>(N_CARDS)
    for (i in 0 until len - 1) {
        for (j in i + 1 until len) ex[j - 1] = ea[j]
        val node = Expr()
        ex[i] = node
        for (j in i + 1 until len) {
            node.left = ea[i]
            node.right = ea[j]
            for (k in OpType.values().drop(1)) {
                node.op = k
                if (solve(ex, len - 1)) return true
            }
            node.left = ea[j]
            node.right = ea[i]
            node.op = OpType.SUB
            if (solve(ex, len - 1)) return true
            node.op = OpType.DIV
            if (solve(ex, len - 1)) return true
            ex[j] = ea[j]
        }
        ex[i] = ea[i]
    }
    return false
}

fun solve24(n: IntArray) =
    solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS)

fun main(args: Array<String>) {
    val r = Random()
    val n = IntArray(N_CARDS)
    for (j in 0..9) {
        for (i in 0 until N_CARDS) {
            n[i] = 1 + r.nextInt(MAX_DIGIT)
            print(" ${n[i]}")
        }
        print(":  ")
        println(if (solve24(n)) "" else "No solution")
    }
}

 8 4 1 7:  (8 - 4) x (7 - 1)
 6 1 4 1:  ((6 + 1) - 1) x 4
 8 8 5 4:  (8 / 8 + 5) x 4
 9 6 9 8:  8 / ((9 - 6) / 9)
 6 6 9 6:  (6 x 6) / 9 x 6
 9 9 7 7:  No solution
 1 1 2 5:  No solution
 6 9 4 1:  6 x (9 - 4 - 1)
 7 7 6 4:  7 + 7 + 6 + 4
 4 8 8 4:  4 + 8 + 8 + 4

Code summarization: The code accepts or generates four digits and computes arithmetic expressions following the 24 game rules, also providing examples of the solutions.


fun facti(n: Int) = when {
    n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
    else  -> {
        var ans = 1L
        for (i in 2..n) ans *= i
        ans
    }
}

fun factr(n: Int): Long = when {
    n < 0 -> throw IllegalArgumentException("negative numbers not allowed")
    n < 2 -> 1L
    else  -> n * factr(n - 1)
}

fun main(args: Array<String>) {
    val n = 20
    println("$n! = " + facti(n))
    println("$n! = " + factr(n))
}

The code defines a function that calculates the factorial of a given number. The factorial is the product of all positive integers from the given number down to 1. The function can be implemented either iteratively or recursively. It optionally includes error handling for negative input numbers. It is related to the task of generating primorial numbers.


// version 1.1.2

import java.util.Random

const val MAX_GUESSES = 20  // say

fun main(args: Array<String>) {
    val r = Random()
    var num: String
    // generate a 4 digit random number from 1234 to 9876 with no zeros or repeated digits
    do {
        num = (1234 + r.nextInt(8643)).toString()
    } while ('0' in num || num.toSet().size < 4)

    println("All guesses should have exactly 4 distinct digits excluding zero.")
    println("Keep guessing until you guess the chosen number (maximum $MAX_GUESSES valid guesses).\n")
    var guesses = 0
    while (true) {
        print("Enter your guess : ")
        val guess = readLine()!!
        if (guess == num) {
            println("You've won with ${++guesses} valid guesses!")
            return
        }
        val n = guess.toIntOrNull()
        if (n == null)
            println("Not a valid number")
        else if ('-' in guess || '+' in guess)
            println("Can't contain a sign")
        else if ('0' in guess)
            println("Can't contain zero")
        else if (guess.length != 4)
            println("Must have exactly 4 digits")
        else if (guess.toSet().size < 4)
            println("All digits must be distinct")
        else {
            var bulls = 0
            var cows  = 0
            for ((i, c) in guess.withIndex()) {
                if (num[i] == c) bulls++
                else if (c in num) cows++
            }
            println("Your score for this guess:  Bulls = $bulls  Cows = $cows")
            guesses++
            if (guesses == MAX_GUESSES)
                println("You've now had $guesses valid guesses, the maximum allowed")
        }
    }
}

The code generates a random four-digit number from 1 to 9 without duplication. It prompts the user to guess this number, rejects malformed guesses, and calculates a score based on the guess. The score is determined by the number of 'bulls' and 'cows', where a 'bull' is a digit in the guess that matches the corresponding digit in the randomly chosen number, and a 'cow' is a digit in the guess that appears in the randomly chosen number but in a different position. The game ends when the guess matches the randomly chosen number.


// version 1.0.6

import java.util.Random

fun main(args: Array<String>) {
    val r = Random()
    val da = DoubleArray(1000)
    for (i in 0 until 1000)  da[i] = 1.0 + 0.5 * r.nextGaussian()
    // now check actual mean and SD
    val mean = da.average()
    val sd = Math.sqrt(da.map { (it - mean) * (it - mean) }.average())
    println("Mean is $mean")
    println("S.D. is $sd")
}

generate a collection of 1000 normally distributed pseudo-random numbers with a mean of 1.0 and a standard deviation of 0.5. If the library only supports uniformly distributed random numbers, it applies a specific algorithm to achieve the task.


Works with: Kotlin version 1.0+
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) }
}

Implement a function to calculate the dot product of two vectors of arbitrary length. The function multiplies corresponding elements from each vector and sums the products. The vectors must be of the same length. Example vectors used are [1, 3, -5] and [4, -2, -1].


// version 1.1

import java.util.*

fun main(args: Array<String>) {
    println("Keep entering text or the word 'quit' to end the program:")
    val sc = Scanner(System.`in`)
    val words = mutableListOf<String>()
    while (true) {
        val input: String = sc.next()
        if (input.trim().toLowerCase() == "quit") {
            if (words.size > 0) println("\nYou entered the following words:\n${words.joinToString("\n")}")
            return
        }
        words.add(input)
    }
}

"Reads data from a text stream either word-by-word or line-by-line until there is no more data left in the stream."


// version 1.1.3

import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.dom.DOMSource
import java.io.StringWriter
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.TransformerFactory

fun main(args: Array<String>) {
    val dbFactory = DocumentBuilderFactory.newInstance()
    val dBuilder  = dbFactory.newDocumentBuilder()
    val doc = dBuilder.newDocument()
    val root = doc.createElement("root")  // create root node
    doc.appendChild(root)
    val element = doc.createElement("element")  // create element node
    val text = doc.createTextNode("Some text here")  // create text node
    element.appendChild(text)
    root.appendChild(element)

    // serialize
    val source = DOMSource(doc)
    val sw = StringWriter()
    val result = StreamResult(sw)
    val tFactory = TransformerFactory.newInstance()
    tFactory.newTransformer().apply {
        setOutputProperty("indent", "yes")
        setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4")
        transform(source, result)
    }
    println(sw)
}

This code creates a simple Document Object Model (DOM) and serializes it into XML format. The XML output includes a root element with a child element containing text. However, the code does not prevent the default encoding and standalone attributes from appearing in the XML declaration. Setting the standalone attribute to true removes it from the declaration but does not add a carriage return before the root tag. Therefore, the code leaves the declaration as is.


// version 1.0.6

fun main(args: Array<String>) {
    println("%tc".format(System.currentTimeMillis()))
}

the system time in a specified unit. This can be used for debugging, network information, random number seeds, or program performance. The time is retrieved either by a system command or a built-in language function. It is related to the task of date formatting and retrieving system time.


// version 1.1.0

val weights = listOf(1, 3, 1, 7, 3, 9, 1)

fun sedol7(sedol6: String): String {
    if (sedol6.length != 6) throw IllegalArgumentException("Length of argument string must be 6")
    var sum = 0
    for (i in 0..5) {
        val c = sedol6[i]
        val v = when (c) {
            in '0'..'9' -> c.toInt() - 48
            in 'A'..'Z' -> c.toInt() - 55
            else        -> throw IllegalArgumentException("Argument string contains an invalid character")
        }
        sum += v * weights[i]
    }
    val check = (10 - (sum % 10)) % 10
    return sedol6 + (check + 48).toChar()
}

fun main(args: Array<String>) {
    val sedol6s = listOf("710889", "B0YBKJ", "406566", "B0YBLH", "228276", "B0YBKL",
                         "557910", "B0YBKR", "585284", "B0YBKT", "B00030")
    for (sedol6 in sedol6s) println("$sedol6 -> ${sedol7(sedol6)}")
}

The code takes a list of 6-digit SEDOLs as input, calculates the checksum digit for each SEDOL, and appends it to the end of the respective SEDOL. It also validates the input to ensure it contains only valid characters for a SEDOL string.


Translation of: C
// 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)
}

"Generates a graphical or ASCII art representation of a sphere, with either static or rotational projection."


fun Int.ordinalAbbrev() =
        if (this % 100 / 10 == 1) "th"
        else when (this % 10) { 1 -> "st" 2 -> "nd" 3 -> "rd" else -> "th" }

fun IntRange.ordinalAbbrev() = map { "$it" + it.ordinalAbbrev() }.joinToString(" ")

fun main(args: Array<String>) {
    listOf((0..25), (250..265), (1000..1025)).forEach { println(it.ordinalAbbrev()) }
}

The code defines a function that takes an integer input greater than or equal to zero and returns a string representation of the number with an ordinal suffix. The function is tested with ranges 0 to 25, 250 to 265, and 1000 to 1025. The use of apostrophes in the output is optional.


// version 1.0.6

fun stripChars(s: String, r: String) = s.replace(Regex("[$r]"), "")

fun main(args: Array<String>) {
    println(stripChars("She was a soul stripper. She took my heart!", "aei"))
}

"Function to remove specific characters from a given string"


fun main(args: Array<String>) {

    //Read the maximum number, set to 0 if it couldn't be read
    val max = readLine()?.toInt() ?: 0
    val words = mutableMapOf<Int, String>()

    //Read input three times for a factor and a word
    (1..3).forEach {
        readLine()?.let {
            val tokens = it.split(' ')
            words.put(tokens[0].toInt(), tokens[1])
        }
    }

    //Sort the words so they will be output in arithmetic order
    val sortedWords = words.toSortedMap()

    //Find the words with matching factors and print them, print the number if no factors match
    for (i in 1..max) {
        val wordsToPrint = sortedWords.filter { i % it.key == 0 }.map { it.value }
        if (wordsToPrint.isNotEmpty()) {
            wordsToPrint.forEach { print(it) }
            println()
        }
        else
            println(i)
    }
}

implement a generalized version of FizzBuzz that takes a maximum number and a list of factor-word pairs as inputs from the user. The code prints numbers from 1 to the maximum number, replacing multiples of each factor with the corresponding word. For numbers that are multiples of multiple factors, the associated words are printed in ascending order of their factors.


// version 1.0.6

fun main(args: Array<String>) {
    var s = "Obama"
    s = "Barack " + s
    println(s)

    // It's also possible to use this standard library function
    // though this is not what it's really intended for
    var t = "Trump"
    t = t.prependIndent("Donald ")
    println(t)
}

Creates a string variable with a specific text value, prepends another string literal to it, and displays the content of the variable. If possible, the operation is performed without referring to the variable twice in one expression.


Translation of: Java
// version 1.0.6

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

class DragonCurve(iter: Int) : JFrame("Dragon Curve") {
    private val turns: MutableList<Int>
    private val startingAngle: Double
    private val side: Double

    init {
        setBounds(100, 100, 800, 600)
        defaultCloseOperation = EXIT_ON_CLOSE
        turns = getSequence(iter)
        startingAngle = -iter * Math.PI / 4
        side = 400.0 / Math.pow(2.0, iter / 2.0)
    }

    fun getSequence(iterations: Int): MutableList<Int> {
        val turnSequence = mutableListOf<Int>()
        for (i in 0 until iterations) {
            val copy = mutableListOf<Int>()
            copy.addAll(turnSequence)
            copy.reverse()
            turnSequence.add(1)
            copy.mapTo(turnSequence) { -it }
        }
        return turnSequence
    }

    override fun paint(g: Graphics) {
        g.color = Color.BLUE
        var angle = startingAngle
        var x1 = 230
        var y1 = 350
        var x2 = x1 + (Math.cos(angle) * side).toInt()
        var y2 = y1 + (Math.sin(angle) * side).toInt()
        g.drawLine(x1, y1, x2, y2)
        x1 = x2
        y1 = y2
        for (turn in turns) {
            angle += turn * Math.PI / 2.0
            x2 = x1 + (Math.cos(angle) * side).toInt()
            y2 = y1 + (Math.sin(angle) * side).toInt()
            g.drawLine(x1, y1, x2, y2)
            x1 = x2
            y1 = y2
        }
    }
}

fun main(args: Array<String>) {
    DragonCurve(14).isVisible = true
}

generate a dragon curve fractal either directly or by writing it to an image file. The fractal is created using various algorithms such as recursive, successive approximation, iterative, and Lindenmayer system of expansions. The algorithms consider curl direction, bit transitions, and absolute X, Y coordinates. The code also includes functionality to test whether a given X,Y point or segment is on the curve. The code is adaptable to different programming languages and drawing methods.


// version 1.0.5-2

fun main(args: Array<String>) {
	val n = (1 + java.util.Random().nextInt(10)).toString()
	println("Guess which number I've chosen in the range 1 to 10\n")
	do { print(" Your guess : ") } while (n != readLine())
	println("\nWell guessed!")
}

"Implements a number guessing game where the computer selects a number between 1 and 10, and prompts the user to guess until the correct number is guessed, upon which it outputs a 'Well guessed!' message and terminates."


// version 1.3.72

fun main() {
    val alphabet = CharArray(26) { (it + 97).toChar() }.joinToString("")

    println(alphabet)
}

generate a sequence of all lower case ASCII characters from a to z. This is done in a reliable coding style suitable for large programs, using strong typing if available. The code avoids manual enumeration of characters to prevent bugs. It also demonstrates how to access a similar sequence from the standard library if it exists.


fun main() {
    val numbers = intArrayOf(5, 50, 9000)
    numbers.forEach { println("$it -> ${it.toString(2)}") }
}

generate a sequence of binary digits for a given non-negative integer. The output displays only the binary digits of each number, followed by a newline, without any whitespace, radix, sign markers, or leading zeros. The conversion can be achieved using built-in radix functions or a user-defined function.


// Version 1.2.41

import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage

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

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

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

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

fun main(args: Array<String>) {
    val bbs = BasicBitmapStorage(320, 240)
    with (bbs) {
        fill(Color.white) // say
        setPixel(100, 100, Color.red)
        // check it worked
        val c = getPixel(100, 100)
        print("The color of the pixel at (100, 100) is ")
        println(if (c == Color.red) "red" else "white")
    }
}

create a 320x240 window and draw a red pixel at position (100,100).


Works with: Kotlin version 1.0.6

import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths

data class Configuration(val map: Map<String, Any?>) {
    val fullName: String by map
    val favoriteFruit: String by map
    val needsPeeling: Boolean by map
    val otherFamily: List<String> by map
}

fun main(args: Array<String>) {
    val lines = Files.readAllLines(Paths.get("src/configuration.txt"), StandardCharsets.UTF_8)
    val keyValuePairs = lines.map{ it.trim() }
            .filterNot { it.isEmpty() }
            .filterNot(::commentedOut)
            .map(::toKeyValuePair)

    val configurationMap = hashMapOf<String, Any>("needsPeeling" to false)
    for (pair in keyValuePairs) {
        val (key, value) = pair
        when (key) {
            "FULLNAME"       -> configurationMap.put("fullName", value)
            "FAVOURITEFRUIT" -> configurationMap.put("favoriteFruit", value)
            "NEEDSPEELING"   -> configurationMap.put("needsPeeling", true)
            "OTHERFAMILY"    -> configurationMap.put("otherFamily", value.split(" , ").map { it.trim() })
            else             -> println("Encountered unexpected key $key=$value")
        }
    }
    println(Configuration(configurationMap))
}

private fun commentedOut(line: String) = line.startsWith("#") || line.startsWith(";")

private fun toKeyValuePair(line: String) = line.split(Regex(" "), 2).let {
    Pair(it[0], if (it.size == 1) "" else it[1])
}

read and parse a configuration file, set variables based on the file's entries, ignore lines starting with a hash or semicolon, and handle options with multiple parameters by storing them in an array. It also provides immutability to the configuration class.


Translation of: Groovy

import java.lang.Math.*

const val R = 6372.8 // in kilometers

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

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

Implement the Haversine formula to calculate the great-circle distance between Nashville International Airport (BNA) and Los Angeles International Airport (LAX) using their respective longitudes and latitudes. The code uses the recommended earth radius value of 6372.8 km for calculations. The code also supports Unicode characters.


// version 1.1.2

import java.net.URL
import java.io.InputStreamReader
import java.util.Scanner

fun main(args: Array<String>) {
    val url = URL("http://www.puzzlers.org/pub/wordlists/unixdict.txt")
    val isr = InputStreamReader(url.openStream())
    val sc = Scanner(isr)
    while (sc.hasNextLine()) println(sc.nextLine())
    sc.close()
}

Print the content of a specified URL to the console using HTTP request.


// version 1.0

fun checkLuhn(number: String): Boolean {
    var isOdd = true
    var sum = 0

    for (index in number.indices.reversed()) {
        val digit = number[index] - '0'
        sum += if (isOdd) digit else (digit * 2).let { (it / 10) + (it % 10) }
        isOdd = !isOdd
    }

    return (sum % 10) == 0
}

fun main(args: Array<String>) {
    val numbers = arrayOf("49927398716", "49927398717", "1234567812345678", "1234567812345670")
    for (number in numbers)
        println("${number.padEnd(16)} is ${if(checkLuhn(number)) "valid" else "invalid"}")
}

The code validates credit card numbers using the Luhn test. It reverses the input number, calculates the sum of odd and even positioned digits (with even digits being doubled and if the result is greater than nine, the digits of the result are summed). If the total sum ends in zero, the number is deemed valid. The code tests this functionality on four given numbers.


// version 1.1.3

fun josephus(n: Int, k: Int, m: Int): Pair<List<Int>, List<Int>> {
    require(k > 0 && m > 0 && n > k && n > m)
    val killed = mutableListOf<Int>()
    val survived = MutableList(n) { it }
    var start = k - 1
    outer@ while (true) {
        val end = survived.size - 1
        var i = start
        var deleted = 0
        while (i <= end) {
            killed.add(survived.removeAt(i - deleted))
            if (survived.size == m) break@outer
            deleted++
            i += k
        }
        start = i - end - 1
    }
    return Pair(survived, killed)
}

fun main(args: Array<String>) {
    val triples = listOf(Triple(5, 2, 1), Triple(41, 3, 1), Triple(41, 3, 3))
    for (triple in triples) {
        val(n, k, m) = triple
        println("Prisoners = $n, Step = $m, Survivors = $m")
        val (survived, killed)  = josephus(n, k, m)
        println("Survived   : $survived")
        println("Kill order : $killed")
        println()
    }
}

- Determine the final survivor in the Josephus problem given any number of prisoners (n) and a step count (k).
- Calculate the position of any prisoner in the killing sequence.
- Provide an option to save a certain number of prisoners (m).
- The numbering of prisoners can start from either 0 or 1.
- The complexity of the solution is O(kn) for the complete killing sequence and O(m) for finding the m-th prisoner to die.


fun main(args: Array<String>) {
    println("ha".repeat(5))
}

operator fun String.times(n: Int) = this.repeat(n)

fun main(args: Array<String>) = println("ha" * 5)

Code summarization: The following codes output a string repeated a certain number of times. It also includes a function for repeating a single character to create a new string.


// version 1.0.6

fun main(args: Array<String>) {
    val s1 = "I am the original string"
    val r1 = Regex("^.*string$")
    if (s1.matches(r1)) println("`$s1` matches `$r1`")
    val r2 = Regex("original")
    val s3 = "replacement"
    val s2 = s1.replace(r2, s3)
    if (s2 != s1) println("`$s2` replaces `$r2` with `$s3`")
}

"Matches a string with a regular expression and performs substitution on a part of the string using the same regular expression."


import kotlin.math.pow // not an operator but in the standard library

fun main() {
    val r = Regex("""-?[0-9]+\s+-?[0-9]+""")
    print("Enter two integers separated by space(s): ")
    val input: String = readLine()!!.trim()
    val index = input.lastIndexOf(' ')
    val a = input.substring(0, index).trimEnd().toLong()
    val b = input.substring(index + 1).toLong()
    println("$a + $b = ${a + b}")
    println("$a - $b = ${a - b}")
    println("$a * $b = ${a * b}")
    println("$a / $b = ${a / b}")  // rounds towards zero
    println("$a % $b = ${a % b}")  // if non-zero, matches sign of first operand
    println("$a ^ $b = ${a.toDouble().pow(b.toDouble())}")
}
}

take two integers as input from the user and display their sum, difference, product, integer quotient, remainder, and exponentiation. The code also indicates the rounding direction for the quotient and the sign of the remainder. It does not include error handling. A bonus feature is the inclusion of the `divmod` operator example.


// version 1.0.6

fun countSubstring(s: String, sub: String): Int = s.split(sub).size - 1

fun main(args: Array<String>) {
    println(countSubstring("the three truths","th"))
    println(countSubstring("ababababab","abab"))
    println(countSubstring("",""))
}

The code defines a function to count the number of non-overlapping occurrences of a given substring within a larger string. The function takes two arguments: the main string and the substring to search for. It returns an integer representing the count of non-overlapping occurrences. The function prioritizes the highest number of non-overlapping matches, typically matching from left-to-right or right-to-left.


// version 1.1.0

class Hanoi(disks: Int) {
    private var moves = 0

    init {
        println("Towers of Hanoi with $disks disks:\n")
        move(disks, 'L', 'C', 'R')
        println("\nCompleted in $moves moves\n")
    }

    private fun move(n: Int, from: Char, to: Char, via: Char) {
        if (n > 0) {
            move(n - 1, from, via, to)
            moves++
            println("Move disk $n from $from to $to")
            move(n - 1, via, to, from)
        }
    }
}

fun main(args: Array<String>) {
    Hanoi(3)
    Hanoi(4)
}

"Implement a recursive solution to solve the Towers of Hanoi problem."


// version 2.0

fun binomial(n: Int, k: Int) = when {
    n < 0 || k < 0 -> throw IllegalArgumentException("negative numbers not allowed")
    n == k         -> 1L
    else           -> {
        val kReduced = min(k, n - k)    // minimize number of steps
        var result = 1L
        var numerator = n
        var denominator = 1
        while (denominator <= kReduced)
            result = result * numerator-- / denominator++
        result
    }
}

fun main(args: Array<String>) {
    for (n in 0..14) {
        for (k in 0..n)
            print("%4d ".format(binomial(n, k)))
        println()
    }
}

The code calculates any binomial coefficient using the provided formula. It is specifically designed to output the binomial coefficient of 5 choose 3, which is 10. It also includes tasks for generating combinations and permutations, both with and without replacement.


// version 1.1.0

val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1)  // Marcin Ciura's gap sequence

fun shellSort(a: IntArray) {
    for (gap in gaps) {
        for (i in gap until a.size) {
            val temp = a[i]
            var j = i
            while (j >= gap && a[j - gap] > temp) {
                a[j] = a[j - gap]
                j -= gap
            }
            a[j] = temp
        }
    }
}

fun main(args: Array<String>) {
    val aa = arrayOf(
        intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199),
        intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1),
        intArrayOf(62, 83, 18, 53, 7, 17, 95, 86, 47, 69, 25, 28)
    )
    for (a in aa) {
        shellSort(a)
        println(a.joinToString(", "))
    }
}

implement the Shell sort algorithm to sort an array of elements. This algorithm, invented by Donald Shell, uses a diminishing increment sort and interleaved insertion sorts based on an increment sequence. The increment size reduces after each pass until it reaches 1, turning the sort into a basic insertion sort. The data is almost sorted at this point, providing the best case for insertion sort. The increment sequence can vary but should always end in 1. Sequences with a geometric increment ratio of about 2.2 have been found to work well.


// version 1.2.10

import java.io.File
import java.awt.image.BufferedImage
import javax.imageio.ImageIO

fun BufferedImage.toGrayScale() {
    for (x in 0 until width) {
        for (y in 0 until height) {
            var argb  = getRGB(x, y)
            val alpha = (argb shr 24) and 0xFF
            val red   = (argb shr 16) and 0xFF
            val green = (argb shr  8) and 0xFF
            val blue  =  argb and 0xFF
            val lumin = (0.2126 * red + 0.7152 * green + 0.0722 * blue).toInt()
            argb = (alpha shl 24) or (lumin shl 16) or (lumin shl 8) or lumin
            setRGB(x, y, argb)
        }
    }
}

fun main(args: Array<String>) {
    val image = ImageIO.read(File("bbc.jpg")) // using BBC BASIC image
    image.toGrayScale()
    val grayFile = File("bbc_gray.jpg")
    ImageIO.write(image, "jpg", grayFile)
}

extend the data storage type to support grayscale images. It includes two operations: one to convert a color image to a grayscale image using the CIE recommended formula for luminance, and one for the backward conversion. The code ensures that rounding errors in floating-point arithmetic do not cause run-time problems or distorted results. However, the reverse operation is not fully accurate due to the loss of original color information in the conversion process.


Translation of: Java
// version 1.1.0

import java.awt.Dimension
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.util.*
import javax.swing.JFrame
import javax.swing.JLabel

class Rotate : JFrame() {
    val text = "Hello World! "
    val label = JLabel(text)
    var rotRight = true
    var startIdx = 0

    init {
        preferredSize = Dimension(96, 64)
        label.addMouseListener(object: MouseAdapter() {
            override fun mouseClicked(evt: MouseEvent) {
                rotRight = !rotRight
            }
        })
        add(label)
        pack()
        defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        isVisible = true
    }
}

fun getRotatedText(text: String, startIdx: Int): String {
    val ret = StringBuilder()
    var i = startIdx
    do {
        ret.append(text[i++])
        i %= text.length
    }
    while (i != startIdx)
    return ret.toString()
}

fun main(args: Array<String>) {
    val rot = Rotate()
    val task = object : TimerTask() {
        override fun run() {
            if (rot.rotRight) {
                if (--rot.startIdx < 0) rot.startIdx += rot.text.length
            }
            else {
                if (++rot.startIdx >= rot.text.length) rot.startIdx -= rot.text.length
            }
            rot.label.text = getRotatedText(rot.text, rot.startIdx)
        }
    }
    Timer(false).schedule(task, 0, 500)
}

Create a GUI animation where the string "Hello World! " appears to rotate right by periodically moving the last letter to the front. The direction of rotation reverses when the user clicks on the text.


// version 1.0.6

fun main(args: Array<String>) {
    var value = 0
    do {
        println(++value)
    }
    while (value % 6 != 0)
}

The code initializes a value to 0, then enters a do-while loop where it increments the value by 1 and prints it, continuing as long as the value modulo 6 is not 0. The loop is guaranteed to execute at least once.


fun main() {
    val s = "José"
    println("The char length is ${s.length}")
    println("The byte length is ${Char.SIZE_BYTES * s.length}")
}

The code calculates the character and byte length of a string, considering UTF-8 and UTF-16 encodings. It correctly handles Unicode code points, including non-BMP ones, and provides the actual character counts in code points, not in code unit counts. It also provides the string length in graphemes if possible. For Kotlin strings, it considers them as a sequence of UTF-16 encoded characters and calculates the byte length as twice the character length.


// version 1.1.2

import java.security.SecureRandom

fun main(args: Array<String>) {
    val rng = SecureRandom()
    val rn1 = rng.nextInt()
    val rn2 = rng.nextInt()
    val newSeed = rn1.toLong() * rn2
    rng.setSeed(newSeed)    // reseed using the previous 2 random numbers
    println(rng.nextInt())  // get random 32-bit number and print it
}

demonstrate how to generate a random 32-bit number using the system's built-in mechanism, not just a software algorithm.


// version 1.0.6
fun main(args: Array<String>) {
    val s = "Rosetta"
    println(s.drop(1))
    println(s.dropLast(1))
    println(s.drop(1).dropLast(1))
}

The code demonstrates how to remove the first, last, and both the first and last characters from a string. It works with any valid Unicode code point in UTF-8 or UTF-16, referencing logical characters, not code units. It doesn't necessarily support all Unicode characters for other encodings like 8-bit ASCII or EUC-JP.


// version 1.0.6

import java.io.IOException
import java.net.*

object SingleInstance {
    private var ss: ServerSocket? = null

    fun alreadyRunning(): Boolean {
        try {
            ss = ServerSocket(65000, 10, InetAddress.getLocalHost()) // using private port 65000
        }
        catch (e: IOException) {
            // port already in use so an instance is already running
            return true
        }
        return false
    }

    fun close() {
        if (ss == null || ss?.isClosed() == true) return
        ss?.close()
    }
}

fun main(args: Array<String>) {
    if (SingleInstance.alreadyRunning()) {
        println("Application is already running, so terminating this instance")
        System.exit(0)
    }
    else {
        println("OK, only this instance is running but will terminate in 10 seconds")
        Thread.sleep(10000)
        SingleInstance.close()
    }
}

"Checks if an application instance is already running, displays a message if so, and exits the program."


Translation of: Java
// version 1.1

import java.awt.Toolkit
import javax.swing.JFrame

class Test : JFrame() {
    init {
        val r = Regex("""\[.*\]""")
        val toolkit = Toolkit.getDefaultToolkit()
        val screenSize = toolkit.screenSize
        println("Physical screen size : ${formatOutput(screenSize, r)}")
        val insets = toolkit.getScreenInsets(graphicsConfiguration)
        println("Insets               : ${formatOutput(insets, r)}")
        screenSize.width  -= (insets.left + insets.right)
        screenSize.height -= (insets.top + insets.bottom)
        println("Max available        : ${formatOutput(screenSize, r)}")
    }

    private fun formatOutput(output: Any, r: Regex) = r.find(output.toString())!!.value.replace(",", ", ")
}

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

"Determines the maximum height and width of a window that can fit within the physical display area of the screen, considering window decorations and menubars. It also handles scenarios with multiple monitors and tiling window managers."


Translation of: C++
// version 1.2.10

class Sudoku(rows: List<String>) {
    private val grid = IntArray(81)
    private var solved = false

    init {
        require(rows.size == 9 && rows.all { it.length == 9 }) {
            "Grid must be 9 x 9"
        }
        for (i in 0..8) {
            for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0'
        }
    }

    fun solve() {
        println("Starting grid:\n\n$this")
        placeNumber(0)
        println(if (solved) "Solution:\n\n$this" else "Unsolvable!")
    }

    private fun placeNumber(pos: Int) {
        if (solved) return
        if (pos == 81) {
            solved = true
            return
        }
        if (grid[pos] > 0) {
            placeNumber(pos + 1)
            return
        }
        for (n in 1..9) {
            if (checkValidity(n, pos % 9, pos / 9)) {
                grid[pos] = n
                placeNumber(pos + 1)
                if (solved) return
                grid[pos] = 0
            }
        }
    }

    private fun checkValidity(v: Int, x: Int, y: Int): Boolean {
        for (i in 0..8) {
            if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false
        }
        val startX = (x / 3) * 3
        val startY = (y / 3) * 3
        for (i in startY until startY + 3) {
            for (j in startX until startX + 3) {
                if (grid[i * 9 + j] == v) return false
            }
        }
        return true
    }

    override fun toString(): String {
        val sb = StringBuilder()
        for (i in 0..8) {
            for (j in 0..8) {
                sb.append(grid[i * 9 + j])
                sb.append(" ")
                if (j == 2 || j == 5) sb.append("| ")
            }
            sb.append("\n")
            if (i == 2 || i == 5) sb.append("------+-------+------\n")
        }
        return sb.toString()
    }
}

fun main(args: Array<String>) {
    val rows = listOf(
        "850002400",
        "720000009",
        "004000000",
        "000107002",
        "305000900",
        "040000000",
        "000080070",
        "017000000",
        "000036040"
    )
    Sudoku(rows).solve()
}

"Implement a Sudoku solver that takes a partially filled 9x9 grid as input and outputs the completed Sudoku grid in a human-readable format."


object Knuth {
    internal val gen = java.util.Random()
}

fun <T> Array<T>.shuffle(): Array<T> {
    val a = clone()
    var n = a.size
    while (n > 1) {
        val k = Knuth.gen.nextInt(n--)
        val t = a[n]
        a[n] = a[k]
        a[k] = t
    }
    return a
}

fun main(args: Array<String>) {
    val str = "abcdefghijklmnopqrstuvwxyz".toCharArray()
    (1..10).forEach {
        val s = str.toTypedArray().shuffle().toCharArray()
        println(s)
        require(s.toSortedSet() == str.toSortedSet())
    }

    val ia = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    (1..10).forEach {
        val s = ia.shuffle()
        println(s.distinct())
        require(s.toSortedSet() == ia.toSet())
    }
}

implement the Knuth shuffle (also known as the Fisher-Yates shuffle) algorithm. This algorithm randomly shuffles the elements of an array in-place. The shuffling process involves iterating from the last index of the array down to 1, and for each index, swapping the element at that index with an element at a random index within the range of 0 to the current index. If in-place modification of the array is not possible in the used programming language, the algorithm can be adjusted to return a new shuffled array. The algorithm can also be modified to iterate from left to right if needed.


// version 1.0.6

import java.util.*

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

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

The code takes a year as input and outputs the dates of the last Friday of each month for that given year.


Translation of: Java
fun main(args: Array<String>) = print("Goodbye, World!")

"Display the string 'Goodbye, World!' without appending a newline at the end."


// version 1.1

import javax.swing.JOptionPane

fun main(args: Array<String>) {
    do {
        val number = JOptionPane.showInputDialog("Enter 75000").toInt()
    } while (number != 75000)
}

"Implement functionality to accept a string and the integer 75000 as inputs from a graphical user interface."


// version 1.0.5-2

object Caesar {
    fun encrypt(s: String, key: Int): String {
        val offset = key % 26
        if (offset == 0) return s
        var d: Char
        val chars = CharArray(s.length)
        for ((index, c) in s.withIndex()) {
            if (c in 'A'..'Z') {
                d = c + offset
                if (d > 'Z') d -= 26
            }
            else if (c in 'a'..'z') {
                d = c + offset
                if (d > 'z') d -= 26
            }
            else
                d = c
            chars[index] = d
        }
        return chars.joinToString("")
    }

    fun decrypt(s: String, key: Int): String {
        return encrypt(s, 26 - key)
    }
}

fun main(args: Array<String>) {
    val encoded = Caesar.encrypt("Bright vixens jump; dozy fowl quack.", 8)
    println(encoded)
    val decoded = Caesar.decrypt(encoded, 8)
    println(decoded)
}

implement both encoding and decoding functions of a Caesar cipher. The cipher rotates the alphabet letters based on a key ranging from 1 to 25, replacing each letter with the corresponding next letter in the alphabet. The codes also handle cases of wrapping from Z to A. The codes illustrate that Caesar cipher provides minimal security as it is vulnerable to frequency analysis and brute force attacks. The codes also demonstrate that Caesar cipher is identical to Vigenère cipher with a key length of 1 and to Rot-13 with a key of 13.


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

calculate the least common multiple (LCM) of two integers m and n. The LCM is the smallest positive integer that has both m and n as factors. If either m or n is zero, the LCM is zero. The LCM can be calculated by iterating all the multiples of m until finding one that is also a multiple of n, or by using the formula lcm(m, n) = |m × n| / gcd(m, n), where gcd is the greatest common divisor. The LCM can also be found by merging the prime decompositions of both m and n.


// version 1.1.0

fun isCusip(s: String): Boolean {
    if (s.length != 9) return false
    var sum = 0
    for (i in 0..7) {
        val c = s[i]
        var v = when (c) {
            in '0'..'9'  -> c.toInt() - 48
            in 'A'..'Z'  -> c.toInt() - 55  // lower case letters apparently invalid
            '*'          -> 36
            '@'          -> 37
            '#'          -> 38
            else         -> return false
        }
        if (i % 2 == 1) v *= 2  // check if odd as using 0-based indexing
        sum += v / 10 + v % 10
    }
    return s[8].toInt() - 48  == (10 - (sum % 10)) % 10
}

fun main(args: Array<String>) {
    val candidates = listOf(
        "037833100",
        "17275R102",
        "38259P508",
        "594918104",
        "68389X106",
        "68389X105"
    )
    for (candidate in candidates)
        println("$candidate -> ${if(isCusip(candidate)) "correct" else "incorrect"}")
}

The code validates the last digit (check digit) of a given CUSIP code, which is a nine-character alphanumeric code used to identify North American financial securities. The validation is performed according to a specific algorithm that considers the numeric value of digits, the ordinal position of letters in the alphabet, and specific values for special characters. The code also handles the doubling of values for even-positioned characters. The final check digit is calculated as (10 - (sum of calculated values mod 10)) mod 10.


// version 1.0.6

fun main(args: Array<String>) {
    println("Word size : ${System.getProperty("sun.arch.data.model")} bits")
    println("Endianness: ${System.getProperty("sun.cpu.endian")}-endian")
}

Code summarization: The code outputs the word size and endianness of the host machine. It may not work on all JVMs but has been tested on a x64 Windows 10 machine.


Translation of: Java
import java.net.URL
import java.io.*

object Popularity {
    /** Gets language data. */
    fun ofLanguages(): List<String> {
        val languages = mutableListOf<String>()
        var gcm = ""
        do {
            val path = url + (if (gcm == "") "" else "&gcmcontinue=" + gcm) + "&prop=categoryinfo" + "&format=txt"
            try {
                val rc = URL(path).openConnection() // URL completed, connection opened
                // Rosetta Code objects to the default Java user agent so use a blank one
                rc.setRequestProperty("User-Agent", "")
                val bfr = BufferedReader(InputStreamReader(rc.inputStream))
                try {
                    gcm = ""
                    var languageName = "?"
                    var line: String? = bfr.readLine()
                    while (line != null) {
                        line = line.trim { it <= ' ' }
                        if (line.startsWith("[title]")) {
                            // have a programming language - should look like "[title] => Category:languageName"
                            languageName = line[':']
                        } else if (line.startsWith("[pages]")) {
                            // number of pages the language has (probably)
                            val pageCount = line['>']
                            if (pageCount != "Array") {
                                // haven't got "[pages] => Array" - must be a number of pages
                                languages += pageCount.toInt().toChar() + languageName
                                languageName = "?"
                            }
                        } else if (line.startsWith("[gcmcontinue]"))
                            gcm = line['>']  // have an indication of whether there is more data or not
                        line = bfr.readLine()
                    }
                } finally {
                    bfr.close()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        } while (gcm != "")

        return languages.sortedWith(LanguageComparator)
    }

    /** Custom sort Comparator for sorting the language list.
     * Assumes the first character is the page count and the rest is the language name. */
    internal object LanguageComparator : java.util.Comparator<String> {
        override fun compare(a: String, b: String): Int {
            // as we "know" we will be comparing languages, we will assume the Strings have the appropriate format
            var r = b.first() - a.first()
            return if (r == 0) a.compareTo(b) else r
            // r == 0: the counts are the same - compare the names
        }
    }

    /** Gets the string following marker in text. */
    private operator fun String.get(c: Char) = substringAfter(c).trim { it <= ' ' }

    private val url = "http://www.rosettacode.org/mw/api.php?action=query" +
            "&generator=categorymembers" + "&gcmtitle=Category:Programming%20Languages" +
            "&gcmlimit=500"
}

fun main(args: Array<String>) {
    // read/sort/print the languages (CSV format):
    var lastTie = -1
    var lastCount = -1
    Popularity.ofLanguages().forEachIndexed { i, lang ->
        val count = lang.first().toInt()
        if (count == lastCount)
            println("%12s%s".format("", lang.substring(1)))
        else {
            println("%4d, %4d, %s".format(1 + if (count == lastCount) lastTie else i, count, lang.substring(1)))
            lastTie = i
            lastCount = count
        }
    }
}

sort the most popular computer programming languages based on the number of members in Rosetta Code categories. It fetches data either through web scraping or using the API method. The code also has the functionality to filter incorrect results. The final output is a ranked list of all programming languages.


// version 1.0.6

fun main(args: Array<String>) {
    val greek = arrayOf("alpha", "beta", "gamma", "delta")
    for (letter in greek) print("$letter ")
    println()
    // or alternatively
    greek.forEach { print("$it ") }
    println()
}

Iterates through each element in a collection in order and prints it, using a "for each" loop or another loop if "for each" is not available in the language.


Works with: Kotlin version 1.0b4
fun main(args: Array<String>) {
    val input = "Hello,How,Are,You,Today"
    println(input.split(',').joinToString("."))
}

"Tokenizes a string by commas into an array, and displays the words to the user separated by a period, including a trailing period."


tailrec fun gcd(a: Int, b: Int): Int = if (b == 0) kotlin.math.abs(a) else gcd(b, a % b)

find the greatest common divisor (GCD) or greatest common factor (GCF) of two integers using a recursive one-line solution. It also relates to the task of finding the least common multiple.


Translation of: Java
import java.net.ServerSocket
import java.net.Socket

fun main() {

    fun handleClient(conn: Socket) {
        conn.use {
            val input = conn.inputStream.bufferedReader()
            val output = conn.outputStream.bufferedWriter()

            input.forEachLine { line ->
                output.write(line)
                output.newLine()
                output.flush()
            }
        }
    }

    ServerSocket(12321).use { listener ->
        while (true) {
            val conn = listener.accept()
            Thread { handleClient(conn) }.start()
        }
    }
}

implement an echo server that runs on TCP port 12321. It accepts and echoes complete lines from multiple client connections simultaneously. The server only supports connections from localhost and logs connection information to standard output. It continues to respond to other clients even if one client sends a partial line or stops reading responses. A quick test can be performed using netcat.


// version 1.1

fun isNumeric(input: String): Boolean =
    try {
        input.toDouble()
        true
    } catch(e: NumberFormatException) {
        false
    }

fun main(args: Array<String>) {
    val inputs = arrayOf("152", "-3.1415926", "Foo123", "-0", "456bar", "1.0E10")
    for (input in inputs) println("$input is ${if (isNumeric(input)) "numeric" else "not numeric"}")
}

"Output: Function to check if a given string can be interpreted as a numeric value, including floating point and negative numbers, in the language's syntax."


// version 1.1.2
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import java.io.InputStreamReader
import java.util.Scanner

fun main(args: Array<String>) {
    val url = URL("https://en.wikipedia.org/wiki/Main_Page")
    val connection = url.openConnection() as HttpsURLConnection
    val isr = InputStreamReader(connection.inputStream)
    val sc = Scanner(isr)
    while (sc.hasNextLine()) println(sc.nextLine())
    sc.close()
}

import java.net.URL

fun main(args: Array<String>){
    println(URL("https://sourceforge.net").readText())
}

sends a GET request to the URL "https://www.w3.org/" without authentication, checks the host certificate for validity, and prints the obtained resource to the console. It uses features available in Kotlin 1.2 and above.


Translation of: Java
// version 1.1.2

import java.awt.*
import java.awt.geom.Line2D
import javax.swing.*

class SutherlandHodgman : JPanel() {
    private val subject = listOf(
        doubleArrayOf( 50.0, 150.0), doubleArrayOf(200.0,  50.0), doubleArrayOf(350.0, 150.0),
        doubleArrayOf(350.0, 300.0), doubleArrayOf(250.0, 300.0), doubleArrayOf(200.0, 250.0),
        doubleArrayOf(150.0, 350.0), doubleArrayOf(100.0, 250.0), doubleArrayOf(100.0, 200.0)
    )

    private val clipper = listOf(
        doubleArrayOf(100.0, 100.0), doubleArrayOf(300.0, 100.0),
        doubleArrayOf(300.0, 300.0), doubleArrayOf(100.0, 300.0)
    )

    private var result = subject.toMutableList()

    init {
        preferredSize = Dimension(600, 500)
        clipPolygon()
    }

    private fun clipPolygon() {
        val len = clipper.size
        for (i in 0 until len) {
            val len2 = result.size
            val input = result
            result = mutableListOf<DoubleArray>()
            val a = clipper[(i + len - 1) % len]
            val b = clipper[i]

            for (j in 0 until len2) {
                val p = input[(j + len2 - 1) % len2]
                val q = input[j]

                if (isInside(a, b, q)) {
                    if (!isInside(a, b, p)) result.add(intersection(a, b, p, q))
                    result.add(q)
                }
                else if (isInside(a, b, p)) result.add(intersection(a, b, p, q))
            }
        }
    }

    private fun isInside(a: DoubleArray, b: DoubleArray, c: DoubleArray) =
        (a[0] - c[0]) * (b[1] - c[1]) > (a[1] - c[1]) * (b[0] - c[0])

    private fun intersection(a: DoubleArray, b: DoubleArray,
                             p: DoubleArray, q: DoubleArray): DoubleArray {
        val a1 = b[1] - a[1]
        val b1 = a[0] - b[0]
        val c1 = a1 * a[0] + b1 * a[1]

        val a2 = q[1] - p[1]
        val b2 = p[0] - q[0]
        val c2 = a2 * p[0] + b2 * p[1]

        val d = a1 * b2 - a2 * b1
        val x = (b2 * c1 - b1 * c2) / d
        val y = (a1 * c2 - a2 * c1) / d

        return doubleArrayOf(x, y)
    }

    override fun paintComponent(g: Graphics) {
        super.paintComponent(g)
        val g2 = g as Graphics2D
        g2.translate(80, 60)
        g2.stroke = BasicStroke(3.0f)
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON)
        drawPolygon(g2, subject, Color.blue)
        drawPolygon(g2, clipper, Color.red)
        drawPolygon(g2, result, Color.green)
    }

    private fun drawPolygon(g2: Graphics2D, points: List<DoubleArray>, color: Color) {
        g2.color = color
        val len = points.size
        val line = Line2D.Double()
        for (i in 0 until len) {
            val p1 = points[i]
            val p2 = points[(i + 1) % len]
            line.setLine(p1[0], p1[1], p2[0], p2[1])
            g2.draw(line)
        }
    }
}

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

implement the Sutherland-Hodgman polygon clipping algorithm. The code takes a closed polygon and a rectangle as inputs, clips the polygon by the rectangle, and outputs the sequence of points that define the resulting clipped polygon. For extra credit, the code also displays all three polygons on a graphical surface, using different colors for each polygon and filling the resulting polygon. The orientation of the display can be either north-west or south-west.


// version 1.0.6

/* all ranking functions assume the array of Pairs is non-empty and already sorted by decreasing order of scores
   and then, if the scores are equal, by reverse alphabetic order of names
*/

fun standardRanking(scores: Array<Pair<Int, String>>): IntArray {
    val rankings = IntArray(scores.size)
    rankings[0] = 1
    for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) rankings[i - 1] else i + 1
    return rankings
}

fun modifiedRanking(scores: Array<Pair<Int, String>>): IntArray {
    val rankings = IntArray(scores.size)
    rankings[0] = 1
    for (i in 1 until scores.size) {
        rankings[i] = i + 1
        val currScore = scores[i].first
        for (j in i - 1 downTo 0) {
            if (currScore != scores[j].first) break
            rankings[j] = i + 1
        }
    }
    return rankings
}

fun denseRanking(scores: Array<Pair<Int, String>>): IntArray {
    val rankings = IntArray(scores.size)
    rankings[0] = 1
    var prevRanking = 1
    for (i in 1 until scores.size) rankings[i] = if (scores[i].first == scores[i - 1].first) prevRanking else ++prevRanking
    return rankings
}

fun ordinalRanking(scores: Array<Pair<Int, String>>) = IntArray(scores.size) { it + 1 }

fun fractionalRanking(scores: Array<Pair<Int, String>>): DoubleArray {
    val rankings = DoubleArray(scores.size)
    rankings[0] = 1.0
    for (i in 1 until scores.size) {
        var k = i
        val currScore = scores[i].first
        for (j in i - 1 downTo 0) {
            if (currScore != scores[j].first) break
            k = j
        }
        val avg = (k..i).average() + 1.0
        for (m in k..i) rankings[m] = avg
    }
    return rankings
}

fun printRankings(title: String, rankings: IntArray, scores: Array<Pair<Int, String>>) {
    println(title + ":")
    for (i in 0 until rankings.size) {
        print ("${rankings[i]}  ")
        println(scores[i].toString().removeSurrounding("(", ")").replace(",", ""))
    }
    println()
}

fun printFractionalRankings(title: String, rankings: DoubleArray, scores: Array<Pair<Int, String>>) {
    println(title + ":")
    for (i in 0 until rankings.size) {
        print ("${"%3.2f".format(rankings[i])}  ")
        println(scores[i].toString().removeSurrounding("(", ")").replace(",", ""))
    }
    println()
}

fun main(args: Array<String>) {
    val scores = arrayOf(44 to "Solomon",  42 to "Jason", 42 to "Errol",  41 to "Garry",
                         41 to "Bernard",  41 to "Barry", 39 to "Stephen")
    printRankings("Standard ranking", standardRanking(scores), scores)
    printRankings("Modified ranking", modifiedRanking(scores), scores)
    printRankings("Dense ranking", denseRanking(scores), scores)
    printRankings("Ordinal ranking", ordinalRanking(scores), scores)
    printFractionalRankings("Fractional ranking", fractionalRanking(scores), scores)
}

"Implement functions for five different ranking methods: Standard, Modified, Dense, Ordinal, and Fractional. Each function takes an ordered list of competition scores and applies the respective ranking method. The Standard method shares the first ordinal number for ties, the Modified method shares the last ordinal number for ties, the Dense method shares the next available integer for ties, the Ordinal method assigns the next available integer without special treatment for ties, and the Fractional method shares the mean of the ordinal numbers for ties."


import kotlin.math.*

fun main() {
    fun Double.toDegrees() = this * 180 / PI
    val angle = PI / 4

    println("angle = $angle rad = ${angle.toDegrees()}°")
    val sine = sin(angle)
    println("sin(angle) = $sine")
    val cosine = cos(angle)
    println("cos(angle) = $cosine")
    val tangent = tan(angle)
    println("tan(angle) = $tangent")
    println()

    val asin = asin(sine)
    println("asin(sin(angle)) = $asin rad = ${asin.toDegrees()}°")
    val acos = acos(cosine)
    println("acos(cos(angle)) = $acos rad = ${acos.toDegrees()}°")
    val atan = atan(tangent)
    println("atan(tan(angle)) = $atan rad = ${atan.toDegrees()}°")
}

demonstrate the usage of trigonometric functions (sine, cosine, tangent, and their inverses) with the same angle in both radians and degrees. It also includes the conversion of the results of inverse functions to radians and degrees. If the language lacks these functions, the code calculates them using known approximations or identities.


Translation of: C
// version 1.1.2

data class Item(val name: String, val weight: Int, val value: Int, val count: Int)

val items = listOf(
    Item("map", 9, 150, 1),
    Item("compass", 13, 35, 1),
    Item("water", 153, 200, 2),
    Item("sandwich", 50, 60, 2),
    Item("glucose", 15, 60, 2),
    Item("tin", 68, 45, 3),
    Item("banana", 27, 60, 3),
    Item("apple", 39, 40, 3),
    Item("cheese", 23, 30, 1),
    Item("beer", 52, 10, 3),
    Item("suntan cream", 11, 70, 1),
    Item("camera", 32, 30, 1),
    Item("T-shirt", 24, 15, 2),
    Item("trousers", 48, 10, 2),
    Item("umbrella", 73, 40, 1),
    Item("waterproof trousers", 42, 70, 1),
    Item("waterproof overclothes", 43, 75, 1),
    Item("note-case", 22, 80, 1),
    Item("sunglasses", 7, 20, 1),
    Item("towel", 18, 12, 2),
    Item("socks", 4, 50, 1),
    Item("book", 30, 10, 2)
)

val n = items.size

const val MAX_WEIGHT = 400

fun knapsack(w: Int): IntArray {
    val m  = Array(n + 1) { IntArray(w + 1) }
    for (i in 1..n) {
        for (j in 0..w) {
            m[i][j] = m[i - 1][j]
            for (k in 1..items[i - 1].count) {
                if (k * items[i - 1].weight > j) break
                val v = m[i - 1][j - k * items[i - 1].weight] + k * items[i - 1].value
                if (v > m[i][j]) m[i][j] = v
            }
        }
    }
    val s = IntArray(n)
    var j = w
    for (i in n downTo 1) {
        val v = m[i][j]
        var k = 0
        while (v != m[i - 1][j] + k * items[i - 1].value) {
            s[i - 1]++
            j -= items[i - 1].weight
            k++
        }
    }
    return s
}

fun main(args: Array<String>) {
   val s = knapsack(MAX_WEIGHT)
   println("Item Chosen             Weight Value  Number")
   println("---------------------   ------ -----  ------")
   var itemCount = 0
   var sumWeight = 0
   var sumValue  = 0
   var sumNumber = 0
   for (i in 0 until n) {
       if (s[i] == 0) continue
       itemCount++
       val name   = items[i].name
       val number = s[i]
       val weight = items[i].weight * number
       val value  = items[i].value  * number
       sumNumber += number
       sumWeight += weight
       sumValue  += value
       println("${name.padEnd(22)}    ${"%3d".format(weight)}   ${"%4d".format(value)}    ${"%2d".format(number)}")
   }
   println("---------------------   ------ -----  ------")
   println("Items chosen $itemCount           ${"%3d".format(sumWeight)}   ${"%4d".format(sumValue)}    ${"%2d".format(sumNumber)}")
}

The code determines the optimal combination of items a tourist can carry in his knapsack, given a maximum weight limit of 4 kg. It selects items based on their importance value and weight, ensuring the total weight does not exceed the limit and the total value is maximized. The code considers the quantity available of each item and only allows whole units to be selected.


// version 1.1.3

import sun.misc.Signal
import sun.misc.SignalHandler

fun main(args: Array<String>) {
    val startTime = System.currentTimeMillis()

    Signal.handle(Signal("INT"), object : SignalHandler {
        override fun handle(sig: Signal) {
            val elapsedTime = (System.currentTimeMillis() - startTime) / 1000.0
            println("\nThe program has run for $elapsedTime seconds")
            System.exit(0)
        }
    })

    var i = 0
    while(true) {
        println(i++)
        Thread.sleep(500)
    }
}

0
1
2
3
4
5
6
7
8
9
10
^C
The program has run for 5.087 seconds

The code outputs an integer every half second. It handles SIGINT or SIGQUIT signals, upon which it stops outputting integers, displays the runtime in seconds, and then terminates.


// version 1.0.5-2

/** overload ++ operator to increment a numeric string */
operator fun String.inc(): String =
    try {
        val num = this.toInt()
        (num + 1).toString()
    }
    catch(e: NumberFormatException) {
        this  // return string unaltered
    }

fun main(args: Array<String>) {
    var ns = "12345"
    println(++ns)
    ns = "ghijk"  // not numeric, so won't be changed by increment operator
    println(++ns)
}


// version 1.1.51

fun findCommonDirPath(paths: List<String>, separator: Char): String {
    if (paths.isEmpty()) return ""
    if (paths.size == 1) return paths[0]
    val splits = paths[0].split(separator)
    val n = splits.size
    val paths2 = paths.drop(1)
    var k = 0
    var common = ""
    while (true) {
        val prevCommon = common
        common += if (k == 0) splits[0] else separator + splits[k]
        if (!paths2.all { it.startsWith(common + separator) || it == common } ) return prevCommon
        if (++k == n) return common
    }
}

fun main(args: Array<String>) {
    val paths = listOf(
        "/home/user1/tmp/coverage/test",
        "/home/user1/tmp/covert/operator",
        "/home/user1/tmp/coven/members"
    )
    val pathsToPrint = paths.map { "   '$it'" }.joinToString("\n")
    println("The common directory path of:\n\n$pathsToPrint\n")
    println("is '${findCommonDirPath(paths, '/')}'")
}

The code finds the common directory path from a given set of directory paths using a specified directory separator character. It tests the functionality using '/' as the directory separator and three specific strings as input paths. The code ensures the returned path is a valid directory, not just the longest common string.


// version 1.0.6

fun <T> sattolo(items: Array<T>) {
    for (i in items.size - 1 downTo 1) {
        val j = (Math.random() * i).toInt()
        val t = items[i]
        items[i] = items[j]
        items[j] = t
    }
}

fun main(args: Array<String>) {
    val items = arrayOf(11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22)
    println(items.joinToString())
    sattolo(items)
    println(items.joinToString())
}

implement the Sattolo cycle algorithm which shuffles an array ensuring each element ends up in a new position. The algorithm modifies the input array in-place or returns a new shuffled array. It can also be adjusted to iterate from left to right. The difference from the Knuth shuffle is in the range of j. The functionality is tested with various input arrays.


Translation of: C
Library: libcurl
Works with: Ubuntu 14.04

// libcurl.def
headers = /usr/include/curl/curl.h
linkerOpts.linux = -L/usr/lib/x86_64-linux-gnu -lcurl

// Kotlin Native v0.6

import kotlinx.cinterop.*
import platform.posix.*
import libcurl.*

fun writeData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)
    = fwrite(ptr, size, nmeb, stream?.reinterpret<FILE>())

fun readData(ptr: COpaquePointer?, size: size_t, nmeb: size_t, stream: COpaquePointer?)
    = fread(ptr, size, nmeb, stream?.reinterpret<FILE>())

fun callSOAP(url: String, inFile: String, outFile: String) {
    val rfp = fopen(inFile, "r")
    if (rfp == null) {
        perror("Read File Open: ")
        exit(1)
    }
    val wfp = fopen(outFile, "w+")
    if (wfp == null) {
        perror("Write File Open: ")
        fclose(rfp)
        exit(1)
    }

    var header: CPointer<curl_slist>? = null
    header = curl_slist_append (header, "Content-Type:text/xml")
    header = curl_slist_append (header, "SOAPAction: rsc")
    header = curl_slist_append (header, "Transfer-Encoding: chunked")
    header = curl_slist_append (header, "Expect:")

    val curl = curl_easy_init()
    if (curl != null) {
        curl_easy_setopt(curl, CURLOPT_URL, url)
        curl_easy_setopt(curl, CURLOPT_POST, 1L)
        curl_easy_setopt(curl, CURLOPT_READFUNCTION, staticCFunction(::readData))
        curl_easy_setopt(curl, CURLOPT_READDATA, rfp)
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, staticCFunction(::writeData))
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp)
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header)
        curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, -1L)
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L)
        curl_easy_perform(curl)
        curl_easy_cleanup(curl)
    }

    curl_slist_free_all(header)
    fclose(rfp)
    fclose(wfp)
}

fun main(args: Array<String>) {
    if (args.size != 3) {
        println("You need to pass exactly 3 command line arguments, namely :-")
        println("    <URL of WSDL> <Input file path> <Output File Path>")
        return
    }
    callSOAP(args[0], args[1], args[2])
}

create a SOAP client that accesses and calls functions soapFunc() and anotherSoapFunc() from http://example.com/soap/wsdl. It involves building libcurl.klib using a .def file and cinterop tool, compiling a Kotlin program linked against libcurl.klib, and executing the resulting .kexe file with command line arguments similar to the C entry.


Works with: Kotlin version 1.0+
fun median(l: List<Double>) = l.sorted().let { (it[it.size / 2] + it[(it.size - 1) / 2]) / 2 }

fun main(args: Array<String>) {
    median(listOf(5.0, 3.0, 4.0)).let { println(it) }  // 4
    median(listOf(5.0, 4.0, 2.0, 3.0)).let { println(it) }  // 3.5
    median(listOf(3.0, 4.0, 1.0, -8.4, 7.2, 4.0, 1.0, 1.2)).let { println(it) }  // 2.1
}

"Calculates the median value of a vector of floating-point numbers, handling even number of elements by returning the average of the two middle values. Implements the selection algorithm for optimal time complexity. Also includes tasks for calculating various statistical measures such as mean, mode, and standard deviation."


Imperative solution[edit]
fun fizzBuzz() {
    for (number in 1..100) {
        println(
            when {
                number % 15 == 0 -> "FizzBuzz"
                number % 3 == 0 -> "Fizz"
                number % 5 == 0 -> "Buzz"
                else -> number
            }
        )
    }
}
Functional solution 1[edit]
fun fizzBuzz1() {
    fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString()
    fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x
    fun buzz(x: Any) = if (x is Int && x.toInt() % 5 == 0) "Fizz" else x

    (1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }
}
Functional solution 2[edit]
fun fizzBuzz2() {
    fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x
    fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x
    fun none(x: Pair<Int, StringBuilder>) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second

    (1..100).map { Pair(it, StringBuilder()) }
            .map { fizz(it) }
            .map { buzz(it) }
            .map { none(it) }
            .forEach { println(it) }
}
Short version with mapOf[edit]
fun fizzBuzz() {
    (1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) }
}

print numbers from 1 to 100, replacing multiples of three with 'Fizz', multiples of five with 'Buzz', and multiples of both three and five with 'FizzBuzz'.