{"title": "100 doors", "language": "Kotlin", "task": "There are 100 doors in a row that are all initially closed. \n\nYou make 100 passes by the doors. \n\nThe first time through, visit every door and ''toggle'' the door (if the door is closed, open it; if it is open, close it). \n\nThe second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. \n\nThe third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door.\n\n\n;Task:\nAnswer the question: what state are the doors in after the last pass? Which are open, which are closed?\n\n\n'''Alternate:''' \nAs noted in this page's discussion page, the only doors that remain open are those whose numbers are perfect squares.\n\nOpening only those doors is an optimization that may also be expressed; \nhowever, as should be obvious, this defeats the intent of comparing implementations across programming languages.\n\n", "solution": "fun oneHundredDoors(): List {\n val doors = BooleanArray(100) { false }\n\n repeat(doors.size) { i ->\n for (j in i until doors.size step (i + 1)) {\n doors[j] = !doors[j]\n }\n }\n\n return doors\n .foldIndexed(emptyList()) { i, acc, door ->\n if (door) acc + (i + 1) else acc\n }\n}\n"} {"title": "100 prisoners", "language": "Kotlin", "task": "The Problem:\n* 100 prisoners are individually numbered 1 to 100\n* A room having a cupboard of 100 opaque drawers numbered 1 to 100, that cannot be seen from outside.\n* Cards numbered 1 to 100 are placed randomly, one to a drawer, and the drawers all closed; at the start.\n* Prisoners start outside the room\n:* They can decide some strategy before any enter the room.\n:* Prisoners enter the room one by one, can open a drawer, inspect the card number in the drawer, then close the drawer.\n:* A prisoner can open no more than 50 drawers.\n:* A prisoner tries to find his own number.\n:* A prisoner finding his own number is then held apart from the others.\n* If '''all''' 100 prisoners find their own numbers then they will all be pardoned. If ''any'' don't then ''all'' sentences stand. \n\n\n;The task:\n# Simulate several thousand instances of the game where the prisoners randomly open drawers\n# Simulate several thousand instances of the game where the prisoners use the optimal strategy mentioned in the Wikipedia article, of:\n:* First opening the drawer whose outside number is his prisoner number.\n:* If the card within has his number then he succeeds otherwise he opens the drawer with the same number as that of the revealed card. (until he opens his maximum).\n\n\nShow and compare the computed probabilities of success for the two strategies, here, on this page.\n\n\n;References:\n# The unbelievable solution to the 100 prisoner puzzle standupmaths (Video).\n# [[wp:100 prisoners problem]]\n# 100 Prisoners Escape Puzzle DataGenetics.\n# Random permutation statistics#One hundred prisoners on Wikipedia.\n\n", "solution": "val playOptimal: () -> Boolean = {\n val secrets = (0..99).toMutableList()\n var ret = true\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n var prev = i\n draw@ for(j in 0 until 50){\n if (secrets[prev] == i) continue@prisoner\n prev = secrets[prev]\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nval playRandom: ()->Boolean = {\n var ret = true\n val secrets = (0..99).toMutableList()\n secrets.shuffle()\n prisoner@ for(i in 0 until 100){\n val opened = mutableListOf()\n val genNum : () ->Int = {\n var r = (0..99).random()\n while (opened.contains(r)) {\n r = (0..99).random()\n }\n r\n }\n for(j in 0 until 50){\n val draw = genNum()\n if ( secrets[draw] == i) continue@prisoner\n opened.add(draw)\n }\n ret = false\n break@prisoner\n }\n ret\n}\n\nfun exec(n:Int, play:()->Boolean):Double{\n var succ = 0\n for (i in IntRange(0, n-1)){\n succ += if(play()) 1 else 0\n }\n return (succ*100.0)/n\n}\n\nfun main() {\n val N = 100_000\n println(\"# of executions: $N\")\n println(\"Optimal play success rate: ${exec(N, playOptimal)}%\")\n println(\"Random play success rate: ${exec(N, playRandom)}%\")\n}"} {"title": "15 puzzle game", "language": "Kotlin from Java", "task": "Implement the Fifteen Puzzle Game.\n\n\nThe '''15-puzzle''' is also known as: \n:::* '''Fifteen Puzzle'''\n:::* '''Gem Puzzle'''\n:::* '''Boss Puzzle'''\n:::* '''Game of Fifteen'''\n:::* '''Mystic Square'''\n:::* '''14-15 Puzzle'''\n:::* and some others.\n\n\n;Related Tasks:\n:* 15 Puzzle Solver\n:* [[16 Puzzle Game]]\n\n", "solution": "// version 1.1.3\n\nimport java.awt.BorderLayout\nimport java.awt.Color\nimport java.awt.Dimension\nimport java.awt.Font\nimport java.awt.Graphics\nimport java.awt.Graphics2D\nimport java.awt.RenderingHints\nimport java.awt.event.MouseAdapter\nimport java.awt.event.MouseEvent\nimport java.util.Random\nimport javax.swing.JFrame\nimport javax.swing.JPanel\nimport javax.swing.SwingUtilities\n\nclass FifteenPuzzle(dim: Int, val margin: Int) : JPanel() {\n\n private val rand = Random()\n private val tiles = IntArray(16)\n private val tileSize = (dim - 2 * margin) / 4\n private val gridSize = tileSize * 4\n private var blankPos = 0\n\n init {\n preferredSize = Dimension(dim, dim)\n background = Color.white\n val cornflowerBlue = 0x6495ED\n foreground = Color(cornflowerBlue)\n font = Font(\"SansSerif\", Font.BOLD, 60)\n\n addMouseListener(object : MouseAdapter() {\n override fun mousePressed(e: MouseEvent) {\n val ex = e.x - margin\n val ey = e.y - margin\n if (ex !in 0..gridSize || ey !in 0..gridSize) return\n\n val c1 = ex / tileSize\n val r1 = ey / tileSize\n val c2 = blankPos % 4\n val r2 = blankPos / 4\n if ((c1 == c2 && Math.abs(r1 - r2) == 1) ||\n (r1 == r2 && Math.abs(c1 - c2) == 1)) {\n val clickPos = r1 * 4 + c1\n tiles[blankPos] = tiles[clickPos]\n tiles[clickPos] = 0\n blankPos = clickPos\n }\n repaint()\n }\n })\n\n shuffle()\n }\n\n private fun shuffle() {\n do {\n reset()\n // don't include the blank space in the shuffle,\n // leave it in the home position\n var n = 15\n while (n > 1) {\n val r = rand.nextInt(n--)\n val tmp = tiles[r]\n tiles[r] = tiles[n]\n tiles[n] = tmp\n }\n } while (!isSolvable())\n }\n\n private fun reset() {\n for (i in 0 until tiles.size) {\n tiles[i] = (i + 1) % tiles.size\n }\n blankPos = 15\n }\n\n /* Only half the permutations of the puzzle are solvable.\n\n Whenever a tile is preceded by a tile with higher value it counts\n as an inversion. In our case, with the blank space in the home\n position, the number of inversions must be even for the puzzle\n to be solvable.\n */\n\n private fun isSolvable(): Boolean {\n var countInversions = 0\n for (i in 0 until 15) {\n (0 until i)\n .filter { tiles[it] > tiles[i] }\n .forEach { countInversions++ }\n }\n return countInversions % 2 == 0\n }\n\n private fun drawGrid(g: Graphics2D) {\n for (i in 0 until tiles.size) {\n if (tiles[i] == 0) continue\n\n val r = i / 4\n val c = i % 4\n val x = margin + c * tileSize\n val y = margin + r * tileSize\n\n with(g) {\n color = foreground\n fillRoundRect(x, y, tileSize, tileSize, 25, 25)\n color = Color.black\n drawRoundRect(x, y, tileSize, tileSize, 25, 25)\n color = Color.white\n }\n drawCenteredString(g, tiles[i].toString(), x, y)\n }\n }\n\n private fun drawCenteredString(g: Graphics2D, s: String, x: Int, y: Int) {\n val fm = g.fontMetrics\n val asc = fm.ascent\n val des = fm.descent\n\n val xx = x + (tileSize - fm.stringWidth(s)) / 2\n val yy = y + (asc + (tileSize - (asc + des)) / 2)\n\n g.drawString(s, xx, yy)\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n drawGrid(g)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with(f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Fifteen Puzzle\"\n isResizable = false\n add(FifteenPuzzle(640, 80), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "24 game", "language": "Kotlin", "task": "The 24 Game tests one's mental arithmetic. \n\n\n;Task\nWrite a program that displays four digits, each from 1 --> 9 (inclusive) with repetitions allowed.\n\nThe program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then evaluate the expression. \n\nThe goal is for the player to enter an expression that (numerically) evaluates to '''24'''.\n* Only the following operators/functions are allowed: multiplication, division, addition, subtraction\n* Division should use floating point or rational arithmetic, etc, to preserve remainders.\n* Brackets are allowed, if using an infix expression evaluator.\n* Forming multiple digit numbers from the supplied digits is ''disallowed''. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong).\n* The order of the digits when given does not have to be preserved.\n\n\n;Notes\n* The type of expression evaluator used is not mandated. An RPN evaluator is equally acceptable for example.\n* The task is not for the program to generate the expression, or test whether an expression is even possible.\n\n\n;Related tasks\n* [[24 game/Solve]]\n\n\n;Reference\n* The 24 Game on h2g2.\n\n", "solution": "import java.util.Random\nimport java.util.Scanner\nimport java.util.Stack\n\ninternal object Game24 {\n fun run() {\n val r = Random()\n val digits = IntArray(4).map { r.nextInt(9) + 1 }\n println(\"Make 24 using these digits: $digits\")\n print(\"> \")\n\n val s = Stack()\n var total = 0L\n val cin = Scanner(System.`in`)\n for (c in cin.nextLine()) {\n when (c) {\n in '0'..'9' -> {\n val d = c - '0'\n total += (1 shl (d * 5)).toLong()\n s += d.toFloat()\n }\n else ->\n if (\"+/-*\".indexOf(c) != -1) {\n s += c.applyOperator(s.pop(), s.pop())\n }\n }\n }\n\n when {\n tally(digits) != total ->\n print(\"Not the same digits. \")\n s.peek().compareTo(target) == 0 ->\n println(\"Correct!\")\n else ->\n print(\"Not correct.\")\n }\n }\n\n private fun Char.applyOperator(a: Float, b: Float) = when (this) {\n '+' -> a + b\n '-' -> b - a\n '*' -> a * b\n '/' -> b / a\n else -> Float.NaN\n }\n\n private fun tally(a: List): Long = a.reduce({ t, i -> t + (1 shl (i * 5)) }).toLong()\n\n private val target = 24\n}\n\nfun main(args: Array) = Game24.run()"} {"title": "24 game/Solve", "language": "Kotlin from C", "task": "Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]].\n\nShow examples of solutions generated by the program.\n\n\n;Related task:\n* [[Arithmetic Evaluator]]\n\n", "solution": "// version 1.1.3\n\nimport java.util.Random\n\nconst val N_CARDS = 4\nconst val SOLVE_GOAL = 24\nconst val MAX_DIGIT = 9\n\nclass Frac(val num: Int, val den: Int)\n\nenum class OpType { NUM, ADD, SUB, MUL, DIV }\n\nclass Expr(\n var op: OpType = OpType.NUM,\n var left: Expr? = null,\n var right: Expr? = null,\n var value: Int = 0\n)\n\nfun showExpr(e: Expr?, prec: OpType, isRight: Boolean) {\n if (e == null) return\n val op = when (e.op) {\n OpType.NUM -> { print(e.value); return }\n OpType.ADD -> \" + \"\n OpType.SUB -> \" - \"\n OpType.MUL -> \" x \"\n OpType.DIV -> \" / \"\n }\n\n if ((e.op == prec && isRight) || e.op < prec) print(\"(\")\n showExpr(e.left, e.op, false)\n print(op)\n showExpr(e.right, e.op, true)\n if ((e.op == prec && isRight) || e.op < prec) print(\")\")\n}\n\nfun evalExpr(e: Expr?): Frac {\n if (e == null) return Frac(0, 1)\n if (e.op == OpType.NUM) return Frac(e.value, 1)\n val l = evalExpr(e.left)\n val r = evalExpr(e.right)\n return when (e.op) {\n OpType.ADD -> Frac(l.num * r.den + l.den * r.num, l.den * r.den)\n OpType.SUB -> Frac(l.num * r.den - l.den * r.num, l.den * r.den)\n OpType.MUL -> Frac(l.num * r.num, l.den * r.den)\n OpType.DIV -> Frac(l.num * r.den, l.den * r.num)\n else -> throw IllegalArgumentException(\"Unknown op: ${e.op}\")\n }\n}\n\nfun solve(ea: Array, len: Int): Boolean {\n if (len == 1) {\n val final = evalExpr(ea[0])\n if (final.num == final.den * SOLVE_GOAL && final.den != 0) {\n showExpr(ea[0], OpType.NUM, false)\n return true\n }\n }\n\n val ex = arrayOfNulls(N_CARDS)\n for (i in 0 until len - 1) {\n for (j in i + 1 until len) ex[j - 1] = ea[j]\n val node = Expr()\n ex[i] = node\n for (j in i + 1 until len) {\n node.left = ea[i]\n node.right = ea[j]\n for (k in OpType.values().drop(1)) {\n node.op = k\n if (solve(ex, len - 1)) return true\n }\n node.left = ea[j]\n node.right = ea[i]\n node.op = OpType.SUB\n if (solve(ex, len - 1)) return true\n node.op = OpType.DIV\n if (solve(ex, len - 1)) return true\n ex[j] = ea[j]\n }\n ex[i] = ea[i]\n }\n return false\n}\n\nfun solve24(n: IntArray) =\n solve (Array(N_CARDS) { Expr(value = n[it]) }, N_CARDS)\n\nfun main(args: Array) {\n val r = Random()\n val n = IntArray(N_CARDS)\n for (j in 0..9) {\n for (i in 0 until N_CARDS) {\n n[i] = 1 + r.nextInt(MAX_DIGIT)\n print(\" ${n[i]}\")\n }\n print(\": \")\n println(if (solve24(n)) \"\" else \"No solution\")\n }\n}"} {"title": "4-rings or 4-squares puzzle", "language": "Kotlin from C", "task": "Replace '''a, b, c, d, e, f,''' and\n '''g ''' with the decimal\ndigits LOW ---> HIGH\nsuch that the sum of the letters inside of each of the four large squares add up to\nthe same sum.\n\n\n +--------------+ +--------------+\n | | | |\n | a | | e |\n | | | |\n | +---+------+---+ +---+---------+\n | | | | | | | |\n | | b | | d | | f | |\n | | | | | | | |\n | | | | | | | |\n +----------+---+ +---+------+---+ |\n | c | | g |\n | | | |\n | | | |\n +--------------+ +-------------+\n\n\nShow all output here.\n\n\n:* Show all solutions for each letter being unique with\n LOW=1 HIGH=7\n:* Show all solutions for each letter being unique with\n LOW=3 HIGH=9\n:* Show only the ''number'' of solutions when each letter can be non-unique\n LOW=0 HIGH=9\n\n\n;Related task:\n* [[Solve the no connection puzzle]]\n\n", "solution": "// version 1.1.2\n\nclass FourSquares(\n private val lo: Int,\n private val hi: Int,\n private val unique: Boolean,\n private val show: Boolean\n) {\n private var a = 0\n private var b = 0\n private var c = 0\n private var d = 0\n private var e = 0\n private var f = 0\n private var g = 0\n private var s = 0\n\n init {\n println()\n if (show) {\n println(\"a b c d e f g\")\n println(\"-------------\")\n }\n acd()\n println(\"\\n$s ${if (unique) \"unique\" else \"non-unique\"} solutions in $lo to $hi\")\n }\n\n private fun acd() {\n c = lo\n while (c <= hi) {\n d = lo\n while (d <= hi) {\n if (!unique || c != d) {\n a = c + d\n if ((a in lo..hi) && (!unique || (c != 0 && d!= 0))) ge()\n }\n d++\n }\n c++\n }\n }\n\n private fun bf() {\n f = lo\n while (f <= hi) {\n if (!unique || (f != a && f != c && f != d && f != e && f!= g)) {\n b = e + f - c\n if ((b in lo..hi) && (!unique || (b != a && b != c && b != d && b != e && b != f && b!= g))) {\n s++\n if (show) println(\"$a $b $c $d $e $f $g\")\n }\n }\n f++\n }\n }\n\n private fun ge() {\n e = lo\n while (e <= hi) {\n if (!unique || (e != a && e != c && e != d)) {\n g = d + e\n if ((g in lo..hi) && (!unique || (g != a && g != c && g != d && g != e))) bf()\n }\n e++\n }\n }\n}\n\nfun main(args: Array) {\n FourSquares(1, 7, true, true)\n FourSquares(3, 9, true, true)\n FourSquares(0, 9, false, false)\n}"} {"title": "99 bottles of beer", "language": "Kotlin", "task": "Display the complete lyrics for the song: '''99 Bottles of Beer on the Wall'''. \n\n\n;The beer song:\nThe lyrics follow this form:\n\n\n::: 99 bottles of beer on the wall\n::: 99 bottles of beer\n::: Take one down, pass it around\n::: 98 bottles of beer on the wall\n \n::: 98 bottles of beer on the wall\n::: 98 bottles of beer\n::: Take one down, pass it around\n::: 97 bottles of beer on the wall\n\n\n... and so on, until reaching '''0''' (zero).\n\nGrammatical support for ''1 bottle of beer'' is optional. \n\nAs with any puzzle, try to do it in as creative/concise/comical a way \nas possible (simple, obvious solutions allowed, too).\n\n\n\n\n;See also: \n* http://99-bottles-of-beer.net/\n* [[:Category:99_Bottles_of_Beer]]\n* [[:Category:Programming language families]]\n* Wikipedia 99 bottles of beer\n\n", "solution": "fun main(args: Array) {\n for (i in 99.downTo(1)) {\n println(\"$i bottles of beer on the wall\")\n println(\"$i bottles of beer\")\n println(\"Take one down, pass it around\")\n }\n println(\"No more bottles of beer on the wall!\")\n}"} {"title": "9 billion names of God the integer", "language": "Kotlin from Swift", "task": "This task is a variation of the short story by Arthur C. Clarke.\n \n(Solvers should be aware of the consequences of completing this task.)\n\nIn detail, to specify what is meant by a \"name\":\n:The integer 1 has 1 name \"1\".\n:The integer 2 has 2 names \"1+1\", and \"2\".\n:The integer 3 has 3 names \"1+1+1\", \"2+1\", and \"3\".\n:The integer 4 has 5 names \"1+1+1+1\", \"2+1+1\", \"2+2\", \"3+1\", \"4\".\n:The integer 5 has 7 names \"1+1+1+1+1\", \"2+1+1+1\", \"2+2+1\", \"3+1+1\", \"3+2\", \"4+1\", \"5\".\n\n\n;Task\nDisplay the first 25 rows of a number triangle which begins:\n\n 1\n 1 1\n 1 1 1 \n 1 2 1 1\n 1 2 2 1 1\n 1 3 3 2 1 1\n\n\nWhere row n corresponds to integer n, and each column C in row m from left to right corresponds to the number of names beginning with C.\n\nA function G(n) should return the sum of the n-th row. \n\nDemonstrate this function by displaying: G(23), G(123), G(1234), and G(12345). \n\nOptionally note that the sum of the n-th row P(n) is the integer partition function. \n\nDemonstrate this is equivalent to G(n) by displaying: P(23), P(123), P(1234), and P(12345).\n\n\n;Extra credit\n\nIf your environment is able, plot P(n) against n for n=1\\ldots 999.\n\n;Related tasks\n* [[Partition function P]]\n\n", "solution": "import java.lang.Math.min\nimport java.math.BigInteger\nimport java.util.ArrayList\nimport java.util.Arrays.asList\n\nfun namesOfGod(n: Int): List {\n val cache = ArrayList>()\n cache.add(asList(BigInteger.ONE))\n\n (cache.size..n).forEach { l ->\n val r = ArrayList()\n r.add(BigInteger.ZERO)\n\n (1..l).forEach { x ->\n r.add(r[r.size - 1] + cache[l - x][min(x, l - x)])\n }\n cache.add(r)\n }\n return cache[n]\n}\n\nfun row(n: Int) = namesOfGod(n).let { r -> (0 until n).map { r[it + 1] - r[it] } }\n\nfun main(args: Array) {\n println(\"Rows:\")\n (1..25).forEach {\n System.out.printf(\"%2d: %s%n\", it, row(it))\n }\n\n println(\"\\nSums:\")\n intArrayOf(23, 123, 1234, 1234).forEach {\n val c = namesOfGod(it)\n System.out.printf(\"%s %s%n\", it, c[c.size - 1])\n }\n}"} {"title": "A+B", "language": "Kotlin", "task": "'''A+B''' --- a classic problem in programming contests, it's given so contestants can gain familiarity with the online judging system being used.\n\n\n;Task:\nGiven two integers, '''A''' and '''B'''. \n\nTheir sum needs to be calculated.\n\n\n;Input data:\nTwo integers are written in the input stream, separated by space(s):\n: (-1000 \\le A,B \\le +1000)\n\n\n;Output data:\nThe required output is one integer: the sum of '''A''' and '''B'''.\n\n\n;Example:\n::{|class=\"standard\"\n ! input \n ! output \n |-\n | 2 2 \n | 4 \n |-\n | 3 2 \n | 5 \n |}\n\n", "solution": "// version 1.0.5-2\n\nfun main(args: Array) {\n val r = Regex(\"\"\"-?\\d+[ ]+-?\\d+\"\"\")\n while(true) {\n print(\"Enter two integers separated by space(s) or q to quit: \")\n val input: String = readLine()!!.trim()\n if (input == \"q\" || input == \"Q\") break\n if (!input.matches(r)) {\n println(\"Invalid input, try again\")\n continue\n }\n val index = input.lastIndexOf(' ')\n val a = input.substring(0, index).trimEnd().toInt()\n val b = input.substring(index + 1).toInt()\n if (Math.abs(a) > 1000 || Math.abs(b) > 1000) {\n println(\"Both numbers must be in the interval [-1000, 1000] - try again\")\n }\n else {\n println(\"Their sum is ${a + b}\\n\")\n }\n } \n}"} {"title": "ABC problem", "language": "Kotlin from Java", "task": "You are given a collection of ABC blocks (maybe like the ones you had when you were a kid). \n\nThere are twenty blocks with two letters on each block. \n\nA complete alphabet is guaranteed amongst all sides of the blocks. \n\nThe sample collection of blocks: \n (B O)\n (X K)\n (D Q)\n (C P)\n (N A)\n (G T)\n (R E)\n (T G)\n (Q D)\n (F S)\n (J W)\n (H U)\n (V I)\n (A N)\n (O B)\n (E R)\n (F S)\n (L Y)\n (P C)\n (Z M)\n\n\n;Task:\nWrite a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks. \n\n\nThe rules are simple:\n::# Once a letter on a block is used that block cannot be used again\n::# The function should be case-insensitive\n::# Show the output on this page for the following 7 words in the following example\n\n\n;Example:\n >>> can_make_word(\"A\")\n True\n >>> can_make_word(\"BARK\")\n True\n >>> can_make_word(\"BOOK\")\n False\n >>> can_make_word(\"TREAT\")\n True\n >>> can_make_word(\"COMMON\")\n False\n >>> can_make_word(\"SQUAD\")\n True\n >>> can_make_word(\"CONFUSE\")\n True\n\n", "solution": "object ABC_block_checker {\n fun run() {\n println(\"\\\"\\\": \" + blocks.canMakeWord(\"\"))\n for (w in words) println(\"$w: \" + blocks.canMakeWord(w))\n }\n\n private fun Array.swap(i: Int, j: Int) {\n val tmp = this[i]\n this[i] = this[j]\n this[j] = tmp\n }\n\n private fun Array.canMakeWord(word: String): Boolean {\n if (word.isEmpty())\n return true\n\n val c = word.first().toUpperCase()\n var i = 0\n forEach { b ->\n if (b.first().toUpperCase() == c || b[1].toUpperCase() == c) {\n swap(0, i)\n if (drop(1).toTypedArray().canMakeWord(word.substring(1)))\n return true\n swap(0, i)\n }\n i++\n }\n\n return false\n }\n\n private val blocks = arrayOf(\n \"BO\", \"XK\", \"DQ\", \"CP\", \"NA\", \"GT\", \"RE\", \"TG\", \"QD\", \"FS\",\n \"JW\", \"HU\", \"VI\", \"AN\", \"OB\", \"ER\", \"FS\", \"LY\", \"PC\", \"ZM\"\n )\n private val words = arrayOf(\"A\", \"BARK\", \"book\", \"treat\", \"COMMON\", \"SQuAd\", \"CONFUSE\")\n}\n\nfun main(args: Array) = ABC_block_checker.run()"} {"title": "AVL tree", "language": "Kotlin from Java", "task": "{{wikipedia|AVL tree}}\n\n\n\nIn computer science, an '''AVL tree''' is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; at no time do they differ by more than one because rebalancing is done ensure this is the case. Lookup, insertion, and deletion all take O(log ''n'') time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. Note the tree of nodes comprise a set, so duplicate node keys are not allowed.\n\nAVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log ''n'') time for the basic operations. Because AVL trees are more rigidly balanced, they are faster than red-black trees for lookup-intensive applications. Similar to red-black trees, AVL trees are height-balanced, but in general not weight-balanced nor m-balanced; that is, sibling nodes can have hugely differing numbers of descendants.\n\n\n;Task:\nImplement an AVL tree in the language of choice, and provide at least basic operations.\n\n;Related task\n[[Red_black_tree_sort]]\n\n", "solution": "class AvlTree {\n private var root: Node? = null\n\n private class Node(var key: Int, var parent: Node?) {\n var balance: Int = 0\n var left : Node? = null\n var right: Node? = null\n }\n\n fun insert(key: Int): Boolean {\n if (root == null)\n root = Node(key, null)\n else {\n var n: Node? = root\n var parent: Node\n while (true) {\n if (n!!.key == key) return false\n parent = n\n val goLeft = n.key > key\n n = if (goLeft) n.left else n.right\n if (n == null) {\n if (goLeft)\n parent.left = Node(key, parent)\n else\n parent.right = Node(key, parent)\n rebalance(parent)\n break\n }\n }\n }\n return true\n }\n\n fun delete(delKey: Int) {\n if (root == null) return\n var n: Node? = root\n var parent: Node? = root\n var delNode: Node? = null\n var child: Node? = root\n while (child != null) {\n parent = n\n n = child\n child = if (delKey >= n.key) n.right else n.left\n if (delKey == n.key) delNode = n\n }\n if (delNode != null) {\n delNode.key = n!!.key\n child = if (n.left != null) n.left else n.right\n if (0 == root!!.key.compareTo(delKey)) {\n root = child\n\n if (null != root) {\n root!!.parent = null\n }\n\n } else {\n if (parent!!.left == n)\n parent.left = child\n else\n parent.right = child\n\n if (null != child) {\n child.parent = parent\n }\n\n rebalance(parent)\n }\n }\n\n private fun rebalance(n: Node) {\n setBalance(n)\n var nn = n\n if (nn.balance == -2)\n if (height(nn.left!!.left) >= height(nn.left!!.right))\n nn = rotateRight(nn)\n else\n nn = rotateLeftThenRight(nn)\n else if (nn.balance == 2)\n if (height(nn.right!!.right) >= height(nn.right!!.left))\n nn = rotateLeft(nn)\n else\n nn = rotateRightThenLeft(nn)\n if (nn.parent != null) rebalance(nn.parent!!)\n else root = nn\n }\n\n private fun rotateLeft(a: Node): Node {\n val b: Node? = a.right\n b!!.parent = a.parent\n a.right = b.left\n if (a.right != null) a.right!!.parent = a\n b.left = a\n a.parent = b\n if (b.parent != null) {\n if (b.parent!!.right == a)\n b.parent!!.right = b\n else\n b.parent!!.left = b\n }\n setBalance(a, b)\n return b\n }\n\n private fun rotateRight(a: Node): Node {\n val b: Node? = a.left\n b!!.parent = a.parent\n a.left = b.right\n if (a.left != null) a.left!!.parent = a\n b.right = a\n a.parent = b\n if (b.parent != null) {\n if (b.parent!!.right == a)\n b.parent!!.right = b\n else\n b.parent!!.left = b\n }\n setBalance(a, b)\n return b\n }\n\n private fun rotateLeftThenRight(n: Node): Node {\n n.left = rotateLeft(n.left!!)\n return rotateRight(n)\n }\n\n private fun rotateRightThenLeft(n: Node): Node {\n n.right = rotateRight(n.right!!)\n return rotateLeft(n)\n }\n\n private fun height(n: Node?): Int {\n if (n == null) return -1\n return 1 + Math.max(height(n.left), height(n.right))\n }\n\n private fun setBalance(vararg nodes: Node) {\n for (n in nodes) n.balance = height(n.right) - height(n.left)\n }\n\n fun printKey() {\n printKey(root)\n println()\n }\n\n private fun printKey(n: Node?) {\n if (n != null) {\n printKey(n.left)\n print(\"${n.key} \")\n printKey(n.right)\n }\n }\n\n fun printBalance() {\n printBalance(root)\n println()\n }\n\n private fun printBalance(n: Node?) {\n if (n != null) {\n printBalance(n.left)\n print(\"${n.balance} \")\n printBalance(n.right)\n }\n }\n}\n\nfun main(args: Array) {\n val tree = AvlTree()\n println(\"Inserting values 1 to 10\")\n for (i in 1..10) tree.insert(i)\n print(\"Printing key : \")\n tree.printKey()\n print(\"Printing balance : \")\n tree.printBalance()\n}"} {"title": "Abbreviations, automatic", "language": "Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an\neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nIt would make a list of words easier to maintain (as words are added, changed, and/or deleted) if\nthe minimum abbreviation length of that list could be automatically (programmatically) determined.\n\n\nFor this task, use the list (below) of the days-of-the-week names that are expressed in about a hundred languages (note that there is a blank line in the list).\n\nSunday Monday Tuesday Wednesday Thursday Friday Saturday\nSondag Maandag Dinsdag Woensdag Donderdag Vrydag Saterdag\nE_djele E_hene E_marte E_merkure E_enjte E_premte E_shtune\nEhud Segno Maksegno Erob Hamus Arbe Kedame\nAl_Ahad Al_Ithinin Al_Tholatha'a Al_Arbia'a Al_Kamis Al_Gomia'a Al_Sabit\nGuiragui Yergou_shapti Yerek_shapti Tchorek_shapti Hink_shapti Ourpat Shapat\ndomingu llunes martes miercoles xueves vienres sabadu\nBazar_gUnU Birinci_gUn Ckinci_gUn UcUncU_gUn DOrdUncU_gUn Bes,inci_gUn Altonco_gUn\nIgande Astelehen Astearte Asteazken Ostegun Ostiral Larunbat\nRobi_bar Shom_bar Mongal_bar Budhh_bar BRihashpati_bar Shukro_bar Shoni_bar\nNedjelja Ponedeljak Utorak Srijeda Cxetvrtak Petak Subota\nDisul Dilun Dimeurzh Dimerc'her Diriaou Digwener Disadorn\nnedelia ponedelnik vtornik sriada chetvartak petak sabota\nsing_kei_yaht sing_kei_yat sing_kei_yee sing_kei_saam sing_kei_sie sing_kei_ng sing_kei_luk\nDiumenge Dilluns Dimarts Dimecres Dijous Divendres Dissabte\nDzeenkk-eh Dzeehn_kk-ehreh Dzeehn_kk-ehreh_nah_kay_dzeeneh Tah_neesee_dzeehn_neh Deehn_ghee_dzee-neh Tl-oowey_tts-el_dehlee Dzeentt-ahzee\ndy_Sul dy_Lun dy_Meurth dy_Mergher dy_You dy_Gwener dy_Sadorn\nDimanch Lendi Madi Mekredi Jedi Vandredi Samdi\nnedjelja ponedjeljak utorak srijeda cxetvrtak petak subota\nnede^le ponde^li utery str^eda c^tvrtek patek sobota\nSondee Mondee Tiisiday Walansedee TOOsedee Feraadee Satadee\ns0ndag mandag tirsdag onsdag torsdag fredag l0rdag\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nDiman^co Lundo Mardo Merkredo ^Jaudo Vendredo Sabato\npUhapaev esmaspaev teisipaev kolmapaev neljapaev reede laupaev\n\nDiu_prima Diu_sequima Diu_tritima Diu_quartima Diu_quintima Diu_sextima Diu_sabbata\nsunnudagur manadagur tysdaguy mikudagur hosdagur friggjadagur leygardagur\nYek_Sham'beh Do_Sham'beh Seh_Sham'beh Cha'har_Sham'beh Panj_Sham'beh Jom'eh Sham'beh\nsunnuntai maanantai tiistai keskiviiko torsktai perjantai lauantai\ndimanche lundi mardi mercredi jeudi vendredi samedi\nSnein Moandei Tiisdei Woansdei Tonersdei Freed Sneon\nDomingo Segunda_feira Martes Mercores Joves Venres Sabado\nk'vira orshabati samshabati otkhshabati khutshabati p'arask'evi shabati\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag\nKiriaki' Defte'ra Tri'ti Teta'rti Pe'mpti Paraskebi' Sa'bato\nravivaar somvaar mangalvaar budhvaar guruvaar shukravaar shanivaar\npopule po`akahi po`alua po`akolu po`aha po`alima po`aono\nYom_rishon Yom_sheni Yom_shlishi Yom_revi'i Yom_chamishi Yom_shishi Shabat\nravivara somavar mangalavar budhavara brahaspativar shukravara shanivar\nvasarnap hetfo kedd szerda csutortok pentek szombat\nSunnudagur Manudagur +ridjudagur Midvikudagar Fimmtudagur FOstudagur Laugardagur\nsundio lundio mardio merkurdio jovdio venerdio saturdio\nMinggu Senin Selasa Rabu Kamis Jumat Sabtu\nDominica Lunedi Martedi Mercuridi Jovedi Venerdi Sabbato\nDe_Domhnaigh De_Luain De_Mairt De_Ceadaoin De_ardaoin De_hAoine De_Sathairn\ndomenica lunedi martedi mercoledi giovedi venerdi sabato\nNichiyou_bi Getzuyou_bi Kayou_bi Suiyou_bi Mokuyou_bi Kin'you_bi Doyou_bi\nIl-yo-il Wol-yo-il Hwa-yo-il Su-yo-il Mok-yo-il Kum-yo-il To-yo-il\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nsve-tdien pirmdien otrdien tresvdien ceturtdien piektdien sestdien\nSekmadienis Pirmadienis Antradienis Trec^iadienis Ketvirtadienis Penktadienis S^es^tadienis\nWangu Kazooba Walumbe Mukasa Kiwanuka Nnagawonye Wamunyi\nxing-_qi-_ri xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\nJedoonee Jelune Jemayrt Jecrean Jardaim Jeheiney Jesam\nJabot Manre Juje Wonje Taije Balaire Jarere\ngeminrongo minomishi martes mierkoles misheushi bernashi mishabaro\nAhad Isnin Selasa Rabu Khamis Jumaat Sabtu\nsphndag mandag tirsdag onsdag torsdag fredag lphrdag\nlo_dimenge lo_diluns lo_dimarc lo_dimercres lo_dijous lo_divendres lo_dissabte\ndjadomingo djaluna djamars djarason djaweps djabierna djasabra\nNiedziela Poniedzial/ek Wtorek S,roda Czwartek Pia,tek Sobota\nDomingo segunda-feire terca-feire quarta-feire quinta-feire sexta-feira sabado\nDomingo Lunes martes Miercoles Jueves Viernes Sabado\nDuminica Luni Mart'i Miercuri Joi Vineri Sambata\nvoskresenie ponedelnik vtornik sreda chetverg pyatnitsa subbota\nSunday Di-luain Di-mairt Di-ciadain Di-ardaoin Di-haoine Di-sathurne\nnedjelja ponedjeljak utorak sreda cxetvrtak petak subota\nSontaha Mmantaha Labobedi Laboraro Labone Labohlano Moqebelo\nIridha- Sandhudha- Anga.haruwa-dha- Badha-dha- Brahaspa.thindha- Sikura-dha- Sena.sura-dha-\nnedel^a pondelok utorok streda s^tvrtok piatok sobota\nNedelja Ponedeljek Torek Sreda Cxetrtek Petek Sobota\ndomingo lunes martes miercoles jueves viernes sabado\nsonde mundey tude-wroko dride-wroko fode-wroko freyda Saturday\nJumapili Jumatatu Jumanne Jumatano Alhamisi Ijumaa Jumamosi\nsondag mandag tisdag onsdag torsdag fredag lordag\nLinggo Lunes Martes Miyerkoles Huwebes Biyernes Sabado\nLe-pai-jit Pai-it Pai-ji Pai-san Pai-si Pai-gO. Pai-lak\nwan-ar-tit wan-tjan wan-ang-kaan wan-phoet wan-pha-ru-hat-sa-boh-die wan-sook wan-sao\nTshipi Mosupologo Labobedi Laboraro Labone Labotlhano Matlhatso\nPazar Pazartesi Sali Car,samba Per,sembe Cuma Cumartesi\nnedilya ponedilok vivtorok sereda chetver pyatnytsya subota\nChu?_Nha.t Thu*_Hai Thu*_Ba Thu*_Tu* Thu*_Na'm Thu*_Sau Thu*_Ba?y\ndydd_Sul dyds_Llun dydd_Mawrth dyds_Mercher dydd_Iau dydd_Gwener dyds_Sadwrn\nDibeer Altine Talaata Allarba Al_xebes Aljuma Gaaw\niCawa uMvulo uLwesibini uLwesithathu uLuwesine uLwesihlanu uMgqibelo\nzuntik montik dinstik mitvokh donershtik fraytik shabes\niSonto uMsombuluko uLwesibili uLwesithathu uLwesine uLwesihlanu uMgqibelo\nDies_Dominica Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Saturni\nBazar_gUnU Bazar_aertaesi Caers,aenbae_axs,amo Caers,aenbae_gUnU CUmae_axs,amo CUmae_gUnU CUmae_Senbae\nSun Moon Mars Mercury Jove Venus Saturn\nzondag maandag dinsdag woensdag donderdag vrijdag zaterdag\nKoseEraa GyoOraa BenEraa Kuoraa YOwaaraa FeEraa Memenaa\nSonntag Montag Dienstag Mittwoch Donnerstag Freitag Sonnabend\nDomingo Luns Terza_feira Corta_feira Xoves Venres Sabado\nDies_Solis Dies_Lunae Dies_Martis Dies_Mercurii Dies_Iovis Dies_Veneris Dies_Sabbatum\nxing-_qi-_tian xing-_qi-_yi-. xing-_qi-_er xing-_qi-_san-. xing-_qi-_si xing-_qi-_wuv. xing-_qi-_liu\ndjadomingu djaluna djamars djarason djaweps djabierne djasabra\nKillachau Atichau Quoyllurchau Illapachau Chaskachau Kuychichau Intichau\n\n''Caveat: The list (above) most surely contains errors (or, at the least, differences) of what the actual (or true) names for the days-of-the-week.''\n\n\nTo make this Rosetta Code task page as small as possible, if processing the complete list, read the days-of-the-week from a file (that is created from the above list).\n\n\nNotes concerning the above list of words\n::* each line has a list of days-of-the-week for a language, separated by at least one blank\n::* the words on each line happen to be in order, from Sunday --> Saturday\n::* most lines have words in mixed case and some have all manner of accented words and other characters\n::* some words were translated to the nearest character that was available to ''code page'' '''437'''\n::* the characters in the words are not restricted except that they may not have imbedded blanks\n::* for this example, the use of an underscore ('''_''') was used to indicate a blank in a word\n\n\n;Task:\n::* The list of words (days of the week) needn't be verified/validated.\n::* Write a function to find the (numeric) minimum length abbreviation for each line that would make abbreviations unique.\n::* A blank line (or a null line) should return a null string.\n::* Process and show the output for at least the first '''five''' lines of the file.\n::* Show all output here.\n\n\n", "solution": "// version 1.1.4-3\n\nimport java.io.File\n\nval r = Regex(\"[ ]+\")\n\nfun main(args: Array) {\n val lines = File(\"days_of_week.txt\").readLines()\n for ((i, line) in lines.withIndex()) {\n if (line.trim().isEmpty()) {\n println()\n continue\n }\n val days = line.trim().split(r)\n if (days.size != 7) throw RuntimeException(\"There aren't 7 days in line ${i + 1}\")\n if (days.distinct().size < 7) { // implies some days have the same name\n println(\" \u221e $line\")\n continue\n }\n var len = 1\n while (true) {\n if (days.map { it.take(len) }.distinct().size == 7) {\n println(\"${\"%2d\".format(len)} $line\")\n break\n }\n len++\n }\n } \n}"} {"title": "Abbreviations, easy", "language": "Kotlin", "task": "This task is an easier (to code) variant of the Rosetta Code task: [[Abbreviations, simple]].\n\n\nFor this task, the following ''command table'' will be used:\n Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy\n COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find\n NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput\n Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO\n MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT\n READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT\n RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the number of capital letters of the word in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTer'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTer'''\n::::* The number of capital letters in '''ALTer''' indicates that any abbreviation for '''ALTer''' must be at least three letters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTer'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''Overlay'''\n::* if there isn't any lowercase letters in the word in the ''command table'', then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "// version 1.1.4-3\n\nval r = Regex(\"[ ]+\")\n\nval table = \n \"Add ALTer BAckup Bottom CAppend Change SCHANGE CInsert CLAst COMPress COpy \" +\n \"COUnt COVerlay CURsor DELete CDelete Down DUPlicate Xedit EXPand EXTract Find \" +\n \"NFind NFINDUp NFUp CFind FINdup FUp FOrward GET Help HEXType Input POWerinput \" +\n \"Join SPlit SPLTJOIN LOAD Locate CLocate LOWercase UPPercase LPrefix MACRO \" + \n \"MErge MODify MOve MSG Next Overlay PARSE PREServe PURge PUT PUTD Query QUIT \" +\n \"READ RECover REFRESH RENum REPeat Replace CReplace RESet RESTore RGTLEFT \" +\n \"RIght LEft SAVE SET SHift SI SORT SOS STAck STATus TOP TRAnsfer Type Up \"\n\nfun validate(commands: List, minLens: List, words: List): List {\n if (words.isEmpty()) return emptyList()\n val results = mutableListOf()\n for (word in words) {\n var matchFound = false\n for ((i, command) in commands.withIndex()) {\n if (minLens[i] == 0 || word.length !in minLens[i] .. command.length) continue \n if (command.startsWith(word, true)) {\n results.add(command.toUpperCase())\n matchFound = true\n break\n }\n }\n if (!matchFound) results.add(\"*error*\")\n }\n return results\n}\n \nfun main(args: Array) {\n val commands = table.trimEnd().split(r)\n val minLens = MutableList(commands.size) { commands[it].count { c -> c.isUpperCase() } }\n val sentence = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n val words = sentence.trim().split(r)\n val results = validate(commands, minLens, words) \n print(\"user words: \")\n for (j in 0 until words.size) print(\"${words[j].padEnd(results[j].length)} \")\n print(\"\\nfull words: \")\n for (j in 0 until results.size) print(\"${results[j]} \")\n println()\n}"} {"title": "Abbreviations, simple", "language": "Kotlin", "task": "The use of abbreviations (also sometimes called synonyms, nicknames, AKAs, or aliases) can be an \neasy way to add flexibility when specifying or using commands, sub-commands, options, etc.\n\n\n\nFor this task, the following ''command table'' will be used:\n add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3\n compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate\n 3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2\n forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load\n locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2\n msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3\n refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left\n 2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1\n\n\n\n\nNotes concerning the above ''command table'':\n::* it can be thought of as one long literal string (with blanks at end-of-lines)\n::* it may have superfluous blanks\n::* it may be in any case (lower/upper/mixed)\n::* the order of the words in the ''command table'' must be preserved as shown\n::* the user input(s) may be in any case (upper/lower/mixed)\n::* commands will be restricted to the Latin alphabet (A --> Z, a --> z)\n::* a command is followed by an optional number, which indicates the minimum abbreviation\n::* A valid abbreviation is a word that has:\n:::* at least the minimum length of the word's minimum number in the ''command table''\n:::* compares equal (regardless of case) to the leading characters of the word in the ''command table''\n:::* a length not longer than the word in the ''command table''\n::::* '''ALT''', '''aLt''', '''ALTE''', and '''ALTER''' are all abbreviations of '''ALTER 3'''\n::::* '''AL''', '''ALF''', '''ALTERS''', '''TER''', and '''A''' aren't valid abbreviations of '''ALTER 3'''\n::::* The '''3''' indicates that any abbreviation for '''ALTER''' must be at least three characters\n::::* Any word longer than five characters can't be an abbreviation for '''ALTER'''\n::::* '''o''', '''ov''', '''oVe''', '''over''', '''overL''', '''overla''' are all acceptable abbreviations for '''overlay 1'''\n::* if there isn't a number after the command, then there isn't an abbreviation permitted\n\n\n\n;Task:\n::* The command table needn't be verified/validated.\n::* Write a function to validate if the user \"words\" (given as input) are valid (in the ''command table'').\n::* If the word is valid, then return the full uppercase version of that \"word\".\n::* If the word isn't valid, then return the lowercase string: '''*error*''' (7 characters).\n::* A blank input (or a null input) should return a null string.\n::* Show all output here.\n\n\n;An example test case to be used for this task:\nFor a user string of:\n riG rePEAT copies put mo rest types fup. 6 poweRin\nthe computer program should return the string:\n RIGHT REPEAT *error* PUT MOVE RESTORE *error* *error* *error* POWERINPUT\n\n\n", "solution": "import java.util.Locale\n\nprivate const val table = \"\" +\n \"add 1 alter 3 backup 2 bottom 1 Cappend 2 change 1 Schange Cinsert 2 Clast 3 \" +\n \"compress 4 copy 2 count 3 Coverlay 3 cursor 3 delete 3 Cdelete 2 down 1 duplicate \" +\n \"3 xEdit 1 expand 3 extract 3 find 1 Nfind 2 Nfindup 6 NfUP 3 Cfind 2 findUP 3 fUP 2 \" +\n \"forward 2 get help 1 hexType 4 input 1 powerInput 3 join 1 split 2 spltJOIN load \" +\n \"locate 1 Clocate 2 lowerCase 3 upperCase 3 Lprefix 2 macro merge 2 modify 3 move 2 \" +\n \"msg next 1 overlay 1 parse preserve 4 purge 3 put putD query 1 quit read recover 3 \" +\n \"refresh renum 3 repeat 3 replace 1 Creplace 2 reset 3 restore 4 rgtLEFT right 2 left \" +\n \"2 save set shift 2 si sort sos stack 3 status 4 top transfer 3 type 1 up 1 \"\n\nprivate data class Command(val name: String, val minLen: Int)\n\nprivate fun parse(commandList: String): List {\n val commands = mutableListOf()\n val fields = commandList.trim().split(\" \")\n var i = 0\n while (i < fields.size) {\n val name = fields[i++]\n var minLen = name.length\n if (i < fields.size) {\n val num = fields[i].toIntOrNull()\n if (num != null && num in 1..minLen) {\n minLen = num\n i++\n }\n }\n commands.add(Command(name, minLen))\n }\n return commands\n}\n\nprivate fun get(commands: List, word: String): String? {\n for ((name, minLen) in commands) {\n if (word.length in minLen..name.length && name.startsWith(word, true)) {\n return name.toUpperCase(Locale.ROOT)\n }\n }\n return null\n}\n\nfun main(args: Array) {\n val commands = parse(table)\n val sentence = \"riG rePEAT copies put mo rest types fup. 6 poweRin\"\n val words = sentence.trim().split(\" \")\n\n val results = words.map { word -> get(commands, word) ?: \"*error*\" }\n\n val paddedUserWords = words.mapIndexed { i, word -> word.padEnd(results[i].length) }\n println(\"user words: ${paddedUserWords.joinToString(\" \")}\")\n println(\"full words: ${results.joinToString(\" \")}\")\n}\n"} {"title": "Abundant odd numbers", "language": "Kotlin from D", "task": "An Abundant number is a number '''n''' for which the ''sum of divisors'' '''s(n) > 2n''',\nor, equivalently, the ''sum of proper divisors'' (or aliquot sum) '''s(n) > n'''.\n\n\n;E.G.:\n'''12''' is abundant, it has the proper divisors '''1,2,3,4 & 6''' which sum to '''16''' ( > '''12''' or '''n'''); \n or alternately, has the sigma sum of '''1,2,3,4,6 & 12''' which sum to '''28''' ( > '''24''' or '''2n''').\n\n\nAbundant numbers are common, though '''even''' abundant numbers seem to be much more common than '''odd''' abundant numbers. \n\nTo make things more interesting, this task is specifically about finding ''odd abundant numbers''.\n\n\n;Task\n*Find and display here: at least the first 25 abundant odd numbers and either their proper divisor sum or sigma sum.\n*Find and display here: the one thousandth abundant odd number and either its proper divisor sum or sigma sum.\n*Find and display here: the first abundant odd number greater than one billion (109) and either its proper divisor sum or sigma sum.\n\n\n;References:\n:* OEIS:A005231: Odd abundant numbers (odd numbers n whose sum of divisors exceeds 2n)\n:* American Journal of Mathematics, Vol. 35, No. 4 (Oct., 1913), pp. 413-422 - Finiteness of the Odd Perfect and Primitive Abundant Numbers with n Distinct Prime Factors (LE Dickson)\n\n", "solution": "fun divisors(n: Int): List {\n val divs = mutableListOf(1)\n val divs2 = mutableListOf()\n\n var i = 2\n while (i * i <= n) {\n if (n % i == 0) {\n val j = n / i\n divs.add(i)\n if (i != j) {\n divs2.add(j)\n }\n }\n i++\n }\n\n divs.addAll(divs2.reversed())\n\n return divs\n}\n\nfun abundantOdd(searchFrom: Int, countFrom: Int, countTo: Int, printOne: Boolean): Int {\n var count = countFrom\n var n = searchFrom\n\n while (count < countTo) {\n val divs = divisors(n)\n val tot = divs.sum()\n if (tot > n) {\n count++\n if (!printOne || count >= countTo) {\n val s = divs.joinToString(\" + \")\n if (printOne) {\n println(\"$n < $s = $tot\")\n } else {\n println(\"%2d. %5d < %s = %d\".format(count, n, s, tot))\n }\n }\n }\n\n n += 2\n }\n\n return n\n}\n\n\nfun main() {\n val max = 25\n println(\"The first $max abundant odd numbers are:\")\n val n = abundantOdd(1, 0, 25, false)\n\n println(\"\\nThe one thousandth abundant odd number is:\")\n abundantOdd(n, 25, 1000, true)\n\n println(\"\\nThe first abundant odd number above one billion is:\")\n abundantOdd((1e9 + 1).toInt(), 0, 1, true)\n}"} {"title": "Accumulator factory", "language": "Kotlin", "task": "{{requires|Mutable State}}\n\nA problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).\n\n\n;Rules:\nThe detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in ''small italic text'').\n:Before you submit an example, make sure the function\n\n:# Takes a number n and returns a function (lets call it g), that takes a number i, and returns n incremented by the accumulation of i from every call of function g(i).Although these exact function and parameter names need not be used\n:# Works for any numeric type-- i.e. can take both ints and floats and returns functions that can take both ints and floats. (It is not enough simply to convert all input to floats. An accumulator that has only seen integers must return integers.) ''(i.e., if the language doesn't allow for numeric polymorphism, you have to use overloading or something like that)''\n:# Generates functions that return the sum of every number ever passed to them, not just the most recent. ''(This requires a piece of state to hold the accumulated value, which in turn means that pure functional languages can't be used for this task.)''\n:# Returns a real function, meaning something that you can use wherever you could use a function you had defined in the ordinary way in the text of your program. ''(Follow your language's conventions here.)''\n:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. ''(No global variables or other such things.)''\n: E.g. if after the example, you added the following code (in a made-up language) ''where the factory function is called foo'':\n:: x = foo(1); \nx(5); \nfoo(3);\nprint x(2.3);\n: It should print 8.3. ''(There is no need to print the form of the accumulator function returned by foo(3); it's not part of the task at all.)''\n\n\n;Task:\nCreate a function that implements the described rules. \n\n\nIt need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them.\n\nWhere it is not possible to hold exactly to the constraints above, describe the deviations.\n\n", "solution": "// version 1.1\n\nfun foo(n: Double): (d: Double) -> Double {\n var nn = n\n return { nn += it; nn }\n}\n\nfun foo(n: Int): (i: Int) -> Int {\n var nn = n\n return { nn += it; nn }\n}\n\nfun main(args: Array) {\n val x = foo(1.0) // calls 'Double' overload\n x(5.0)\n foo(3.0)\n println(x(2.3))\n val y = foo(1) // calls 'Int' overload\n y(5)\n foo(5)\n println(y(2))\n}"} {"title": "Aliquot sequence classifications", "language": "Kotlin", "task": "An aliquot sequence of a positive integer K is defined recursively as the first member\nbeing K and subsequent members being the sum of the [[Proper divisors]] of the previous term.\n\n:* If the terms eventually reach 0 then the series for K is said to '''terminate'''.\n\n:There are several classifications for non termination:\n:* If the second term is K then all future terms are also K and so the sequence repeats from the first term with period 1 and K is called '''perfect'''.\n:* If the third term ''would'' be repeating K then the sequence repeats with period 2 and K is called '''amicable'''.\n:* If the Nth term ''would'' be repeating K for the first time, with N > 3 then the sequence repeats with period N - 1 and K is called '''sociable'''.\n:Perfect, amicable and sociable numbers eventually repeat the original number K; there are other repetitions...\n:* Some K have a sequence that eventually forms a periodic repetition of period 1 but of a number other than K, for example 95 which forms the sequence 95, 25, 6, 6, 6, ... such K are called '''aspiring'''.\n:* K that have a sequence that eventually forms a periodic repetition of period >= 2 but of a number other than K, for example 562 which forms the sequence 562, 284, 220, 284, 220, ... such K are called '''cyclic'''.\n\n:And finally:\n:* Some K form aliquot sequences that are not known to be either terminating or periodic; these K are to be called '''non-terminating'''. For the purposes of this task, K is to be classed as non-terminating if it has not been otherwise classed after generating '''16''' terms or if any term of the sequence is greater than 2**47 = 140,737,488,355,328. \n\n\n;Task:\n# Create routine(s) to generate the aliquot sequence of a positive integer enough to classify it according to the classifications given above.\n# Use it to display the classification and sequences of the numbers one to ten inclusive.\n# Use it to show the classification and sequences of the following integers, in order:\n:: 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488, and optionally 15355717786080.\n\nShow all output on this page.\n\n\n;Related tasks:\n* [[Abundant, deficient and perfect number classifications]]. (Classifications from only the first two members of the whole sequence).\n* [[Proper divisors]]\n* [[Amicable pairs]]\n\n", "solution": "// version 1.1.3\n\ndata class Classification(val sequence: List, val aliquot: String)\n\nconst val THRESHOLD = 1L shl 47\n\nfun sumProperDivisors(n: Long): Long {\n if (n < 2L) return 0L\n val sqrt = Math.sqrt(n.toDouble()).toLong()\n var sum = 1L + (2L..sqrt)\n .filter { n % it == 0L }\n .map { it + n / it }\n .sum()\n if (sqrt * sqrt == n) sum -= sqrt\n return sum\n}\n\nfun classifySequence(k: Long): Classification {\n require(k > 0)\n var last = k\n val seq = mutableListOf(k)\n while (true) {\n last = sumProperDivisors(last)\n seq.add(last)\n val n = seq.size\n val aliquot = when {\n last == 0L -> \"Terminating\"\n n == 2 && last == k -> \"Perfect\"\n n == 3 && last == k -> \"Amicable\"\n n >= 4 && last == k -> \"Sociable[${n - 1}]\"\n last == seq[n - 2] -> \"Aspiring\"\n last in seq.slice(1..n - 3) -> \"Cyclic[${n - 1 - seq.indexOf(last)}]\"\n n == 16 || last > THRESHOLD -> \"Non-Terminating\"\n else -> \"\"\n }\n if (aliquot != \"\") return Classification(seq, aliquot)\n }\n}\n\nfun main(args: Array) {\n println(\"Aliqot classifications - periods for Sociable/Cyclic in square brackets:\\n\")\n for (k in 1L..10) {\n val (seq, aliquot) = classifySequence(k)\n println(\"${\"%2d\".format(k)}: ${aliquot.padEnd(15)} $seq\")\n }\n\n val la = longArrayOf(\n 11, 12, 28, 496, 220, 1184, 12496, 1264460, 790, 909, 562, 1064, 1488\n )\n println()\n\n for (k in la) {\n val (seq, aliquot) = classifySequence(k)\n println(\"${\"%7d\".format(k)}: ${aliquot.padEnd(15)} $seq\")\n }\n\n println()\n\n val k = 15355717786080L\n val (seq, aliquot) = classifySequence(k)\n println(\"$k: ${aliquot.padEnd(15)} $seq\")\n}"} {"title": "Amb", "language": "Kotlin", "task": "Define and give an example of the Amb operator.\n\nThe Amb operator (short for \"ambiguous\") expresses nondeterminism. This doesn't refer to randomness (as in \"nondeterministic universe\") but is closely related to the term as it is used in automata theory (\"non-deterministic finite automaton\").\n\nThe Amb operator takes a variable number of expressions (or values if that's simpler in the language) and yields a correct one which will satisfy a constraint in some future computation, thereby avoiding failure.\n\nProblems whose solution the Amb operator naturally expresses can be approached with other tools, such as explicit nested iterations over data sets, or with pattern matching. By contrast, the Amb operator appears integrated into the language. Invocations of Amb are not wrapped in any visible loops or other search patterns; they appear to be independent. \n\nEssentially Amb(x, y, z) splits the computation into three possible futures: a future in which the value x is yielded, a future in which the value y is yielded and a future in which the value z is yielded. The future which leads to a successful subsequent computation is chosen. The other \"parallel universes\" somehow go away. Amb called with no arguments fails.\n\nFor simplicity, one of the domain values usable with Amb may denote failure, if that is convenient. For instance, it is convenient if a Boolean false denotes failure, so that Amb(false) fails, and thus constraints can be expressed using Boolean expressions like Amb(x * y == 8) which unless x and y add to four.\n\nA pseudo-code program which satisfies this constraint might look like:\n\nlet x = Amb(1, 2, 3)\nlet y = Amb(7, 6, 4, 5)\nAmb(x * y = 8)\nprint x, y\n\nThe output is 2 4 because Amb(1, 2, 3) correctly chooses the future in which x has value 2, Amb(7, 6, 4, 5) chooses 4 and consequently Amb(x * y = 8) produces a success.\n\nAlternatively, failure could be represented using strictly Amb():\n\nunless x * y = 8 do Amb()\n\nOr else Amb could take the form of two operators or functions: one for producing values and one for enforcing constraints:\n\nlet x = Ambsel(1, 2, 3)\nlet y = Ambsel(4, 5, 6)\nAmbassert(x * y = 8)\nprint x, y\n\nwhere Ambassert behaves like Amb() if the Boolean expression is false, otherwise it allows the future computation to take place, without yielding any value.\n\nThe task is to somehow implement Amb, and demonstrate it with a program which chooses one word from each of the following four sets of character strings to generate a four-word sentence:\n\n#\"the\" \"that\" \"a\"\n#\"frog\" \"elephant\" \"thing\"\n#\"walked\" \"treaded\" \"grows\"\n#\"slowly\" \"quickly\"\n\nThe constraint to be satisfied is that the last character of each word (other than the last) is the same as the first character of its successor.\n\nThe only successful sentence is \"that thing grows slowly\"; other combinations do not satisfy the constraint and thus fail.\n\nThe goal of this task isn't to simply process the four lists of words with explicit, deterministic program flow such as nested iteration, to trivially demonstrate the correct output. The goal is to implement the Amb operator, or a facsimile thereof that is possible within the language limitations.\n\n", "solution": "// version 1.2.41\nimport kotlin.coroutines.experimental.*\nimport kotlin.coroutines.experimental.intrinsics.*\n\nfun main(args: Array) = amb {\n val a = amb(\"the\", \"that\", \"a\")\n val b = amb(\"frog\", \"elephant\", \"thing\")\n val c = amb(\"walked\", \"treaded\", \"grows\")\n val d = amb(\"slowly\", \"quickly\")\n \n if (a[a.lastIndex] != b[0]) amb()\n if (b[b.lastIndex] != c[0]) amb()\n if (c[c.lastIndex] != d[0]) amb()\n \n println(listOf(a, b, c, d))\n \n \n val x = amb(1, 2, 3)\n val y = amb(7, 6, 4, 5)\n if (x * y != 8) amb()\n println(listOf(x, y))\n}\n\n\nclass AmbException(): Exception(\"Refusing to execute\")\ndata class AmbPair(val cont: Continuation, val valuesLeft: MutableList)\n\n@RestrictsSuspension\nclass AmbEnvironment {\n val ambList = mutableListOf>()\n \n suspend fun amb(value: T, vararg rest: T): T = suspendCoroutineOrReturn { cont -> \n if (rest.size > 0) {\n ambList.add(AmbPair(clone(cont), mutableListOf(*rest)))\n }\n \n value\n }\n \n suspend fun amb(): Nothing = suspendCoroutine { }\n}\n\n@Suppress(\"UNCHECKED_CAST\")\nfun amb(block: suspend AmbEnvironment.() -> R): R {\n var result: R? = null\n var toThrow: Throwable? = null\n \n val dist = AmbEnvironment()\n block.startCoroutine(receiver = dist, completion = object : Continuation {\n override val context: CoroutineContext get() = EmptyCoroutineContext\n override fun resume(value: R) { result = value }\n override fun resumeWithException(exception: Throwable) { toThrow = exception }\n })\n \n while (result == null && toThrow == null && !dist.ambList.isEmpty()) {\n val last = dist.ambList.run { this[lastIndex] }\n \n if (last.valuesLeft.size == 1) {\n dist.ambList.removeAt(dist.ambList.lastIndex)\n last.apply {\n (cont as Continuation).resume(valuesLeft[0])\n }\n } else {\n val value = last.valuesLeft.removeAt(last.valuesLeft.lastIndex)\n (clone(last.cont) as Continuation).resume(value)\n }\n }\n \n if (toThrow != null)\n {\n throw toThrow!!\n }\n else if (result != null)\n {\n return result!!\n }\n else \n {\n throw AmbException()\n }\n}\n\nval UNSAFE = Class.forName(\"sun.misc.Unsafe\")\n .getDeclaredField(\"theUnsafe\")\n .apply { isAccessible = true }\n .get(null) as sun.misc.Unsafe\n\n@Suppress(\"UNCHECKED_CAST\")\nfun clone(obj: T): T {\n val clazz = obj::class.java\n val copy = UNSAFE.allocateInstance(clazz) as T\n copyDeclaredFields(obj, copy, clazz)\n return copy\n}\n\ntailrec fun copyDeclaredFields(obj: T, copy: T, clazz: Class) {\n for (field in clazz.declaredFields) {\n field.isAccessible = true\n val v = field.get(obj)\n field.set(copy, if (v === obj) copy else v)\n }\n val superclass = clazz.superclass\n if (superclass != null) copyDeclaredFields(obj, copy, superclass)\n}"} {"title": "Anagrams/Deranged anagrams", "language": "Kotlin", "task": "Two or more words are said to be anagrams if they have the same characters, but in a different order. \n\nBy analogy with derangements we define a ''deranged anagram'' as two words with the same characters, but in which the same character does ''not'' appear in the same position in both words.\n\n;Task\n\nUse the word list at unixdict to find and display the longest deranged anagram. \n\n\n;Related\n* [[Permutations/Derangements]]\n* Best shuffle\n\n{{Related tasks/Word plays}}\n\n\n\n", "solution": "// version 1.0.6\n\nimport java.io.BufferedReader\nimport java.io.InputStreamReader\nimport java.net.URL\n\nfun isDeranged(s1: String, s2: String): Boolean {\n return (0 until s1.length).none { s1[it] == s2[it] }\n}\n\nfun main(args: Array) {\n val url = URL(\"http://www.puzzlers.org/pub/wordlists/unixdict.txt\")\n val isr = InputStreamReader(url.openStream())\n val reader = BufferedReader(isr)\n val anagrams = mutableMapOf>()\n var count = 0\n var word = reader.readLine()\n while (word != null) {\n val chars = word.toCharArray()\n chars.sort()\n val key = chars.joinToString(\"\")\n if (!anagrams.containsKey(key)) {\n anagrams.put(key, mutableListOf())\n anagrams[key]!!.add(word)\n }\n else {\n val deranged = anagrams[key]!!.any { isDeranged(it, word) }\n if (deranged) {\n anagrams[key]!!.add(word)\n count = Math.max(count, word.length)\n }\n }\n word = reader.readLine()\n }\n reader.close()\n anagrams.values\n .filter { it.size > 1 && it[0].length == count }\n .forEach { println(it) }\n}"} {"title": "Angle difference between two bearings", "language": "Kotlin", "task": "Finding the angle between two bearings is often confusing.[https://stackoverflow.com/questions/16180595/find-the-angle-between-two-bearings]\n\n\n;Task:\nFind the angle which is the result of the subtraction '''b2 - b1''', where '''b1''' and '''b2''' are the bearings. \n\nInput bearings are expressed in the range '''-180''' to '''+180''' degrees. \nThe result is also expressed in the range '''-180''' to '''+180''' degrees. \n\n\nCompute the angle for the following pairs:\n* 20 degrees ('''b1''') and 45 degrees ('''b2''')\n* -45 and 45\n* -85 and 90\n* -95 and 90\n* -45 and 125\n* -45 and 145\n* 29.4803 and -88.6381\n* -78.3251 and -159.036\n\n\n;Optional extra: \nAllow the input bearings to be any (finite) value. \n\n\n;Test cases:\n* -70099.74233810938 and 29840.67437876723\n* -165313.6666297357 and 33693.9894517456\n* 1174.8380510598456 and -154146.66490124757\n* 60175.77306795546 and 42213.07192354373\n\n", "solution": "// version 1.1.2\n\nclass Angle(d: Double) {\n val value = when {\n d in -180.0 .. 180.0 -> d\n d > 180.0 -> (d - 180.0) % 360.0 - 180.0\n else -> (d + 180.0) % 360.0 + 180.0\n }\n\n operator fun minus(other: Angle) = Angle(this.value - other.value)\n}\n\nfun main(args: Array) {\n val anglePairs = arrayOf(\n 20.0 to 45.0,\n -45.0 to 45.0,\n -85.0 to 90.0,\n -95.0 to 90.0,\n -45.0 to 125.0,\n -45.0 to 145.0,\n 29.4803 to -88.6381,\n -78.3251 to -159.036,\n -70099.74233810938 to 29840.67437876723,\n -165313.6666297357 to 33693.9894517456,\n 1174.8380510598456 to -154146.66490124757,\n 60175.77306795546 to 42213.07192354373\n )\n println(\" b1 b2 diff\")\n val f = \"% 12.4f % 12.4f % 12.4f\"\n for (ap in anglePairs) {\n val diff = Angle(ap.second) - Angle(ap.first)\n println(f.format(ap.first, ap.second, diff.value))\n }\n}"} {"title": "Anti-primes", "language": "Kotlin from Go", "task": "The anti-primes \n(or highly composite numbers, sequence A002182 in the OEIS) \nare the natural numbers with more factors than any smaller than itself.\n\n\n;Task:\nGenerate and show here, the first twenty anti-primes.\n\n\n;Related tasks:\n:* [[Factors of an integer]]\n:* [[Sieve of Eratosthenes]]\n\n", "solution": "// Version 1.3.10\n\nfun countDivisors(n: Int): Int {\n if (n < 2) return 1;\n var count = 2 // 1 and n\n for (i in 2..n / 2) {\n if (n % i == 0) count++\n }\n return count;\n}\n\nfun main(args: Array) {\n println(\"The first 20 anti-primes are:\")\n var maxDiv = 0\n var count = 0\n var n = 1\n while (count < 20) {\n val d = countDivisors(n)\n if (d > maxDiv) {\n print(\"$n \")\n maxDiv = d\n count++\n }\n n++\n }\n println()\n}"} {"title": "Apply a digital filter (direct form II transposed)", "language": "Kotlin from C++", "task": "Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the \"direct form II transposed\" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [https://ccrma.stanford.edu/~jos/fp/Transposed_Direct_Forms.html]\n\n;Task:\n\nFilter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667]\n\nThe signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589]\n\n;See also:\n[Wikipedia on Butterworth filters]\n\n\n", "solution": "// version 1.1.3\n\nfun filter(a: DoubleArray, b: DoubleArray, signal: DoubleArray): DoubleArray {\n val result = DoubleArray(signal.size)\n for (i in 0 until signal.size) {\n var tmp = 0.0\n for (j in 0 until b.size) {\n if (i - j < 0) continue\n tmp += b[j] * signal[i - j]\n }\n for (j in 1 until a.size) {\n if (i - j < 0) continue\n tmp -= a[j] * result[i - j]\n }\n tmp /= a[0]\n result[i] = tmp\n }\n return result\n}\n\nfun main(args: Array) {\n val a = doubleArrayOf(1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17)\n val b = doubleArrayOf(0.16666667, 0.5, 0.5, 0.16666667)\n\n val signal = doubleArrayOf(\n -0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412,\n -0.662370894973, -1.00700480494, -0.404707073677, 0.800482325044,\n 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195,\n 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293,\n 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589\n )\n\n val result = filter(a, b, signal)\n for (i in 0 until result.size) {\n print(\"% .8f\".format(result[i]))\n print(if ((i + 1) % 5 != 0) \", \" else \"\\n\")\n }\n}"} {"title": "Approximate equality", "language": "Kotlin from C#", "task": "Sometimes, when testing whether the solution to a task (for example, here on Rosetta Code) is correct, the\ndifference in floating point calculations between different language implementations becomes significant. \n\nFor example, a difference between '''32''' bit and '''64''' bit floating point calculations may appear by \nabout the 8th significant digit in base 10 arithmetic.\n\n\n;Task:\nCreate a function which returns true if two floating point numbers are approximately equal. \n\n\nThe function should allow for differences in the magnitude of numbers, so that, for example, \n'''100000000000000.01''' may be approximately equal to '''100000000000000.011''', \neven though '''100.01''' is not approximately equal to '''100.011'''.\n\nIf the language has such a feature in its standard library, this may be used instead of a custom function.\n\nShow the function results with comparisons on the following pairs of values:\n:# 100000000000000.01, 100000000000000.011 (note: should return ''true'')\n:# 100.01, 100.011 (note: should return ''false'')\n:# 10000000000000.001 / 10000.0, 1000000000.0000001000\n:# 0.001, 0.0010000001\n:# 0.000000000000000000000101, 0.0\n:# sqrt(2) * sqrt(2), 2.0\n:# -sqrt(2) * sqrt(2), -2.0\n:# 3.14159265358979323846, 3.14159265358979324\n\nAnswers should be true for the first example and false in the second, so that just rounding the numbers to a fixed number of decimals should not be enough. Otherwise answers may vary and still be correct. See the Python code for one type of solution.\n\n\n__TOC__\n\n", "solution": "import kotlin.math.abs\nimport kotlin.math.sqrt\n\nfun approxEquals(value: Double, other: Double, epsilon: Double): Boolean {\n return abs(value - other) < epsilon\n}\n\nfun test(a: Double, b: Double) {\n val epsilon = 1e-18\n println(\"$a, $b => ${approxEquals(a, b, epsilon)}\")\n}\n\nfun main() {\n test(100000000000000.01, 100000000000000.011)\n test(100.01, 100.011)\n test(10000000000000.001 / 10000.0, 1000000000.0000001000)\n test(0.001, 0.0010000001)\n test(0.000000000000000000000101, 0.0)\n test(sqrt(2.0) * sqrt(2.0), 2.0)\n test(-sqrt(2.0) * sqrt(2.0), -2.0)\n test(3.14159265358979323846, 3.14159265358979324)\n}"} {"title": "Archimedean spiral", "language": "Kotlin from Java", "task": "The Archimedean spiral is a spiral named after the Greek mathematician Archimedes. \n\n\nAn Archimedean spiral can be described by the equation:\n\n:\\, r=a+b\\theta\n\nwith real numbers ''a'' and ''b''.\n\n\n;Task\nDraw an Archimedean spiral.\n\n", "solution": "// version 1.1.0\n\nimport java.awt.*\nimport javax.swing.*\n\nclass ArchimedeanSpiral : JPanel() {\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n }\n\n private fun drawGrid(g: Graphics2D) {\n g.color = Color(0xEEEEEE)\n g.stroke = BasicStroke(2f)\n val angle = Math.toRadians(45.0)\n val w = width\n val center = w / 2\n val margin = 10\n val numRings = 8\n val spacing = (w - 2 * margin) / (numRings * 2)\n\n for (i in 0 until numRings) {\n val pos = margin + i * spacing\n val size = w - (2 * margin + i * 2 * spacing)\n g.drawOval(pos, pos, size, size)\n val ia = i * angle\n val x2 = center + (Math.cos(ia) * (w - 2 * margin) / 2).toInt()\n val y2 = center - (Math.sin(ia) * (w - 2 * margin) / 2).toInt()\n g.drawLine(center, center, x2, y2)\n }\n }\n\n private fun drawSpiral(g: Graphics2D) {\n g.stroke = BasicStroke(2f)\n g.color = Color.magenta\n val degrees = Math.toRadians(0.1)\n val center = width / 2\n val end = 360 * 2 * 10 * degrees\n val a = 0.0\n val b = 20.0\n val c = 1.0\n var theta = 0.0\n while (theta < end) {\n val r = a + b * Math.pow(theta, 1.0 / c)\n val x = r * Math.cos(theta)\n val y = r * Math.sin(theta)\n plot(g, (center + x).toInt(), (center - y).toInt())\n theta += degrees\n }\n }\n\n private fun plot(g: Graphics2D, x: Int, y: Int) {\n g.drawOval(x, y, 1, 1)\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n drawGrid(g)\n drawSpiral(g)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Archimedean Spiral\"\n f.isResizable = false\n f.add(ArchimedeanSpiral(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}"} {"title": "Arena storage pool", "language": "Kotlin", "task": "Dynamically allocated objects take their memory from a [[heap]]. \n\nThe memory for an object is provided by an '''allocator''' which maintains the storage pool used for the [[heap]].\n\nOften a call to allocator is denoted as\nP := new T\nwhere '''T''' is the type of an allocated object, and '''P''' is a [[reference]] to the object.\n\nThe storage pool chosen by the allocator can be determined by either:\n* the object type '''T'''\n* the type of pointer '''P'''\n\n\nIn the former case objects can be allocated only in one storage pool. \n\nIn the latter case objects of the type can be allocated in any storage pool or on the [[stack]].\n\n\n;Task:\nThe task is to show how allocators and user-defined storage pools are supported by the language. \n\nIn particular:\n# define an arena storage pool. An arena is a pool in which objects are allocated individually, but freed by groups.\n# allocate some objects (e.g., integers) in the pool.\n\n\nExplain what controls the storage pool choice in the language.\n\n", "solution": "// Kotlin Native v0.5\n\nimport kotlinx.cinterop.*\n\nfun main(args: Array) {\n memScoped {\n val intVar1 = alloc()\n intVar1.value = 1\n val intVar2 = alloc()\n intVar2.value = 2\n println(\"${intVar1.value} + ${intVar2.value} = ${intVar1.value + intVar2.value}\")\n } \n // native memory used by intVar1 & intVar2 is automatically freed when memScoped block ends\n}"} {"title": "Arithmetic-geometric mean", "language": "Kotlin", "task": "{{wikipedia|Arithmetic-geometric mean}}\n\n\n;Task:\nWrite a function to compute the arithmetic-geometric mean of two numbers.\n\n\nThe arithmetic-geometric mean of two numbers can be (usefully) denoted as \\mathrm{agm}(a,g), and is equal to the limit of the sequence:\n: a_0 = a; \\qquad g_0 = g\n: a_{n+1} = \\tfrac{1}{2}(a_n + g_n); \\quad g_{n+1} = \\sqrt{a_n g_n}.\nSince the limit of a_n-g_n tends (rapidly) to zero with iterations, this is an efficient method.\n\nDemonstrate the function by calculating:\n:\\mathrm{agm}(1,1/\\sqrt{2})\n \n\n;Also see:\n* mathworld.wolfram.com/Arithmetic-Geometric Mean\n\n", "solution": "// version 1.0.5-2\n\nfun agm(a: Double, g: Double): Double {\n var aa = a // mutable 'a'\n var gg = g // mutable 'g'\n var ta: Double // temporary variable to hold next iteration of 'aa'\n val epsilon = 1.0e-16 // tolerance for checking if limit has been reached\n\n while (true) {\n ta = (aa + gg) / 2.0\n if (Math.abs(aa - ta) <= epsilon) return ta\n gg = Math.sqrt(aa * gg)\n aa = ta\n }\n}\n\nfun main(args: Array) {\n println(agm(1.0, 1.0 / Math.sqrt(2.0)))\n}"} {"title": "Arithmetic-geometric mean/Calculate Pi", "language": "Kotlin", "task": "Almkvist Berndt 1988 begins with an investigation of why the agm is such an efficient algorithm, and proves that it converges quadratically. This is an efficient method to calculate \\pi.\n\nWith the same notations used in [[Arithmetic-geometric mean]], we can summarize the paper by writing:\n\n\\pi =\n\\frac{4\\; \\mathrm{agm}(1, 1/\\sqrt{2})^2}\n{1 - \\sum\\limits_{n=1}^{\\infty} 2^{n+1}(a_n^2-g_n^2)}\n\n\nThis allows you to make the approximation, for any large '''N''':\n\n\\pi \\approx\n\\frac{4\\; a_N^2}\n{1 - \\sum\\limits_{k=1}^N 2^{k+1}(a_k^2-g_k^2)}\n\n\nThe purpose of this task is to demonstrate how to use this approximation in order to compute a large number of decimals of \\pi.\n\n", "solution": "import java.math.BigDecimal\nimport java.math.MathContext\n\nval con1024 = MathContext(1024)\nval bigTwo = BigDecimal(2)\nval bigFour = bigTwo * bigTwo\n\nfun bigSqrt(bd: BigDecimal, con: MathContext): BigDecimal {\n var x0 = BigDecimal.ZERO\n var x1 = BigDecimal.valueOf(Math.sqrt(bd.toDouble()))\n while (x0 != x1) {\n x0 = x1\n x1 = bd.divide(x0, con).add(x0).divide(bigTwo, con)\n }\n return x1\n}\n\nfun main(args: Array) {\n var a = BigDecimal.ONE\n var g = a.divide(bigSqrt(bigTwo, con1024), con1024)\n var t : BigDecimal\n var sum = BigDecimal.ZERO\n var pow = bigTwo\n while (a != g) {\n t = (a + g).divide(bigTwo, con1024)\n g = bigSqrt(a * g, con1024)\n a = t\n pow *= bigTwo\n sum += (a * a - g * g) * pow\n }\n val pi = (bigFour * a * a).divide(BigDecimal.ONE - sum, con1024)\n println(pi)\n}"} {"title": "Arithmetic evaluation", "language": "Kotlin from JavaScript", "task": "Create a program which parses and evaluates arithmetic expressions.\n;Requirements:\n* An abstract-syntax tree (AST) for the expression must be created from parsing the input. \n* The AST must be used in evaluation, also, so the input may not be directly evaluated (e.g. by calling eval or a similar language feature.) \n* The expression will be a string or list of symbols like \"(1+3)*7\". \n* The four symbols + - * / must be supported as binary operators with conventional precedence rules. \n* Precedence-control parentheses must also be supported.\n\n\n;Note:\nFor those who don't remember, mathematical precedence is as follows:\n* Parentheses\n* Multiplication/Division (left to right)\n* Addition/Subtraction (left to right)\n\n\n;C.f: \n* [[24 game Player]].\n* [[Parsing/RPN calculator algorithm]].\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "// version 1.2.10\n\n/* if string is empty, returns zero */\nfun String.toDoubleOrZero() = this.toDoubleOrNull() ?: 0.0\n\nfun multiply(s: String): String {\n val b = s.split('*').map { it.toDoubleOrZero() }\n return (b[0] * b[1]).toString()\n}\n\nfun divide(s: String): String {\n val b = s.split('/').map { it.toDoubleOrZero() }\n return (b[0] / b[1]).toString()\n}\n\nfun add(s: String): String {\n var t = s.replace(Regex(\"\"\"^\\+\"\"\"), \"\").replace(Regex(\"\"\"\\++\"\"\"), \"+\") \n val b = t.split('+').map { it.toDoubleOrZero() }\n return (b[0] + b[1]).toString()\n}\n\nfun subtract(s: String): String {\n var t = s.replace(Regex(\"\"\"(\\+-|-\\+)\"\"\"), \"-\")\n if (\"--\" in t) return add(t.replace(\"--\", \"+\"))\n val b = t.split('-').map { it.toDoubleOrZero() }\n return (if (b.size == 3) -b[1] - b[2] else b[0] - b[1]).toString()\n}\n\nfun evalExp(s: String): String {\n var t = s.replace(Regex(\"\"\"[()]\"\"\"), \"\")\n val reMD = Regex(\"\"\"\\d+\\.?\\d*\\s*[*/]\\s*[+-]?\\d+\\.?\\d*\"\"\")\n val reM = Regex( \"\"\"\\*\"\"\")\n val reAS = Regex(\"\"\"-?\\d+\\.?\\d*\\s*[+-]\\s*[+-]?\\d+\\.?\\d*\"\"\")\n val reA = Regex(\"\"\"\\d\\+\"\"\")\n\n while (true) {\n val match = reMD.find(t)\n if (match == null) break\n val exp = match.value\n val match2 = reM.find(exp)\n t = if (match2 != null)\n t.replace(exp, multiply(exp))\n else\n t.replace(exp, divide(exp))\n }\n\n while (true) {\n val match = reAS.find(t)\n if (match == null) break\n val exp = match.value\n val match2 = reA.find(exp)\n t = if (match2 != null)\n t.replace(exp, add(exp))\n else\n t.replace(exp, subtract(exp))\n }\n\n return t\n}\n\nfun evalArithmeticExp(s: String): Double {\n var t = s.replace(Regex(\"\"\"\\s\"\"\"), \"\").replace(\"\"\"^\\+\"\"\", \"\")\n val rePara = Regex(\"\"\"\\([^()]*\\)\"\"\")\n while(true) {\n val match = rePara.find(t)\n if (match == null) break\n val exp = match.value\n t = t.replace(exp, evalExp(exp))\n }\n return evalExp(t).toDoubleOrZero()\n}\n\nfun main(arsg: Array) {\n listOf(\n \"2+3\",\n \"2+3/4\",\n \"2*3-4\",\n \"2*(3+4)+5/6\",\n \"2 * (3 + (4 * 5 + (6 * 7) * 8) - 9) * 10\",\n \"2*-3--4+-0.25\",\n \"-4 - 3\",\n \"((((2))))+ 3 * 5\",\n \"1 + 2 * (3 + (4 * 5 + 6 * 7 * 8) - 9) / 10\",\n \"1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5 - 22/(7 + 2*(3 - 1)) - 1)) + 1\"\n ).forEach { println(\"$it = ${evalArithmeticExp(it)}\") }\n}"} {"title": "Array length", "language": "Kotlin", "task": "Determine the amount of elements in an array.\n\n\nAs an example use an array holding the strings 'apple' and 'orange'.\n\n\n\n", "solution": "fun main(args: Array) {\n println(arrayOf(\"apple\", \"orange\").size)\n}"} {"title": "Associative array/Merging", "language": "Kotlin", "task": "Define two associative arrays, where one represents the following \"base\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 12.75\n|-\n| \"color\" || \"yellow\"\n|}\n\nAnd the other represents \"update\" data:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\nMerge these into a new associative array that contains every key found in either of the source ones. Each key should map to the value in the second (update) table if that exists, or else to the value in the first (base) table. If possible, do this in a way that does not mutate the original two associative arrays. Obviously this should be done in a way that would work for any data, not just the specific data given here, but in this example the result should be:\n\n::::: {| class=\"wikitable\"\n|+\n| '''Key''' || '''Value'''\n|-\n| \"name\" || \"Rocket Skates\"\n|-\n| \"price\" || 15.25\n|-\n| \"color\" || \"red\"\n|-\n| \"year\" || 1974\n|}\n\n", "solution": "fun main() {\n val base = HashMap()\n val update = HashMap()\n\n base[\"name\"] = \"Rocket Skates\"\n base[\"price\"] = \"12.75\"\n base[\"color\"] = \"yellow\"\n\n update[\"price\"] = \"15.25\"\n update[\"color\"] = \"red\"\n update[\"year\"] = \"1974\"\n\n val merged = HashMap(base)\n merged.putAll(update)\n\n println(\"base: $base\")\n println(\"update: $update\")\n println(\"merged: $merged\")\n}\n"} {"title": "Attractive numbers", "language": "Kotlin from Go", "task": "A number is an ''attractive number'' if the number of its prime factors (whether distinct or not) is also prime.\n\n\n;Example:\nThe number '''20''', whose prime decomposition is '''2 x 2 x 5''', is an ''attractive number'' because the number of its prime factors ('''3''') is also prime.\n\n\n;Task:\nShow sequence items up to '''120'''.\n\n\n;Reference:\n:* The OEIS entry: A063989: Numbers with a prime number of prime divisors.\n\n", "solution": "// Version 1.3.21\n\nconst val MAX = 120\n\nfun isPrime(n: Int) : Boolean {\n if (n < 2) return false\n if (n % 2 == 0) return n == 2\n if (n % 3 == 0) return n == 3\n var d : Int = 5\n while (d * d <= n) {\n if (n % d == 0) return false\n d += 2\n if (n % d == 0) return false\n d += 4\n }\n return true\n}\n\nfun countPrimeFactors(n: Int) =\n when {\n n == 1 -> 0\n isPrime(n) -> 1\n else -> {\n var nn = n\n var count = 0\n var f = 2\n while (true) {\n if (nn % f == 0) {\n count++\n nn /= f\n if (nn == 1) break\n if (isPrime(nn)) f = nn\n } else if (f >= 3) {\n f += 2\n } else {\n f = 3\n }\n }\n count\n }\n }\n\nfun main() {\n println(\"The attractive numbers up to and including $MAX are:\")\n var count = 0\n for (i in 1..MAX) {\n val n = countPrimeFactors(i)\n if (isPrime(n)) {\n System.out.printf(\"%4d\", i)\n if (++count % 20 == 0) println()\n }\n }\n println()\n}"} {"title": "Average loop length", "language": "Kotlin from Go", "task": "Let f be a uniformly-randomly chosen mapping from the numbers 1..N to the numbers 1..N (note: not necessarily a permutation of 1..N; the mapping could produce a number in more than one way or not at all). At some point, the sequence 1, f(1), f(f(1))... will contain a repetition, a number that occurring for the second time in the sequence.\n\n\n;Task:\nWrite a program or a script that estimates, for each N, the average length until the first such repetition.\n\nAlso calculate this expected length using an analytical formula, and optionally compare the simulated result with the theoretical one.\n\n\nThis problem comes from the end of Donald Knuth's Christmas tree lecture 2011.\n\nExample of expected output:\n\n N average analytical (error)\n=== ========= ============ =========\n 1 1.0000 1.0000 ( 0.00%)\n 2 1.4992 1.5000 ( 0.05%)\n 3 1.8784 1.8889 ( 0.56%)\n 4 2.2316 2.2188 ( 0.58%)\n 5 2.4982 2.5104 ( 0.49%)\n 6 2.7897 2.7747 ( 0.54%)\n 7 3.0153 3.0181 ( 0.09%)\n 8 3.2429 3.2450 ( 0.07%)\n 9 3.4536 3.4583 ( 0.14%)\n 10 3.6649 3.6602 ( 0.13%)\n 11 3.8091 3.8524 ( 1.12%)\n 12 3.9986 4.0361 ( 0.93%)\n 13 4.2074 4.2123 ( 0.12%)\n 14 4.3711 4.3820 ( 0.25%)\n 15 4.5275 4.5458 ( 0.40%)\n 16 4.6755 4.7043 ( 0.61%)\n 17 4.8877 4.8579 ( 0.61%)\n 18 4.9951 5.0071 ( 0.24%)\n 19 5.1312 5.1522 ( 0.41%)\n 20 5.2699 5.2936 ( 0.45%)\n\n", "solution": "const val NMAX = 20\nconst val TESTS = 1000000\nval rand = java.util.Random()\n\nfun avg(n: Int): Double {\n var sum = 0\n for (t in 0 until TESTS) {\n val v = BooleanArray(NMAX)\n var x = 0\n while (!v[x]) {\n v[x] = true\n sum++\n x = rand.nextInt(n)\n }\n }\n return sum.toDouble() / TESTS\n}\n\nfun ana(n: Int): Double {\n val nn = n.toDouble()\n var term = 1.0\n var sum = 1.0\n for (i in n - 1 downTo 1) {\n term *= i / nn\n sum += term\n }\n return sum\n}\n\nfun main(args: Array) {\n println(\" N average analytical (error)\")\n println(\"=== ========= ============ =========\")\n for (n in 1..NMAX) {\n val a = avg(n)\n val b = ana(n)\n println(String.format(\"%3d %6.4f %10.4f (%4.2f%%)\", n, a, b, Math.abs(a - b) / b * 100.0))\n }\n}"} {"title": "Averages/Mean angle", "language": "Kotlin", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "// version 1.0.5-2\n\nfun meanAngle(angles: DoubleArray): Double {\n val sinSum = angles.sumByDouble { Math.sin(it * Math.PI / 180.0) }\n val cosSum = angles.sumByDouble { Math.cos(it * Math.PI / 180.0) }\n return Math.atan2(sinSum / angles.size, cosSum / angles.size) * 180.0 / Math.PI\n}\n\nfun main(args: Array) {\n val angles1 = doubleArrayOf(350.0, 10.0)\n val angles2 = doubleArrayOf(90.0, 180.0, 270.0, 360.0)\n val angles3 = doubleArrayOf(10.0, 20.0, 30.0)\n val fmt = \"%.2f degrees\" // format results to 2 decimal places\n println(\"Mean for angles 1 is ${fmt.format(meanAngle(angles1))}\")\n println(\"Mean for angles 2 is ${fmt.format(meanAngle(angles2))}\")\n println(\"Mean for angles 3 is ${fmt.format(meanAngle(angles3))}\")\n}"} {"title": "Averages/Pythagorean means", "language": "Kotlin", "task": "{{Related tasks/Statistical measures}}\n\n\n", "solution": "import kotlin.math.round\nimport kotlin.math.pow\n\nfun Collection.geometricMean() =\n if (isEmpty()) Double.NaN\n else (reduce { n1, n2 -> n1 * n2 }).pow(1.0 / size)\n \nfun Collection.harmonicMean() =\n if (isEmpty() || contains(0.0)) Double.NaN\n else size / fold(0.0) { n1, n2 -> n1 + 1.0 / n2 }\n\nfun Double.toFixed(len: Int = 6) =\n round(this * 10.0.pow(len)) / 10.0.pow(len)\n \nfun main() {\n val list = listOf(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)\n val a = list.average() // arithmetic mean\n val g = list.geometricMean()\n val h = list.harmonicMean()\n println(\"A = $a G = ${g.toFixed()} H = ${h.toFixed()}\")\n println(\"A >= G is ${a >= g}, G >= H is ${g >= h}\")\n require(g in h..a)\n}"} {"title": "Averages/Root mean square", "language": "Kotlin", "task": "Task\n\nCompute the Root mean square of the numbers 1..10.\n\n\nThe ''root mean square'' is also known by its initials RMS (or rms), and as the '''quadratic mean'''.\n\nThe RMS is calculated as the mean of the squares of the numbers, square-rooted:\n\n\n::: x_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. \n\n\n;See also\n\n{{Related tasks/Statistical measures}}\n\n\n", "solution": "// version 1.0.5-2\n\nfun quadraticMean(vector: Array) : Double {\n val sum = vector.sumByDouble { it * it }\n return Math.sqrt(sum / vector.size)\n}\n \nfun main(args: Array) {\n val vector = Array(10, { (it + 1).toDouble() })\n print(\"Quadratic mean of numbers 1 to 10 is ${quadraticMean(vector)}\")\n}"} {"title": "Babbage problem", "language": "Kotlin", "task": "Charles Babbage\nCharles Babbage's analytical engine.\n\nCharles Babbage, looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:\n{{quote\n | What is the smallest positive integer whose square ends in the digits 269,696?\n | Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, Electronic Computers, second edition, 1970, p. 125.\n}}\nHe thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.\n\n\n;Task\n\nThe task is to find out if Babbage had the right answer -- and to do so, as far as your language allows it, in code that Babbage himself would have been able to read and understand. \nAs Babbage evidently solved the task with pencil and paper, a similar efficient solution is preferred.\n\nFor these purposes, Charles Babbage may be taken to be an intelligent person, familiar with mathematics and with the idea of a computer; he has written the first drafts of simple computer programmes in tabular form. [Babbage Archive Series L].\n\n\n;Motivation\n\nThe aim of the task is to write a program that is sufficiently clear and well-documented for such a person to be able to read it and be confident that it does indeed solve the specified problem.\n\n", "solution": "fun main(args: Array) {\n var number = 520L\n var square = 520 * 520L\n\n while (true) {\n val last6 = square.toString().takeLast(6)\n if (last6 == \"269696\") {\n println(\"The smallest number is $number whose square is $square\")\n return\n }\n number += 2\n square = number * number\n }\n}"} {"title": "Balanced brackets", "language": "Kotlin from FreeBASIC", "task": "'''Task''': \n* Generate a string with '''N''' opening brackets '''[''' and with '''N''' closing brackets ''']''', in some arbitrary order. \n* Determine whether the generated string is ''balanced''; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.\n\n\n\n;Examples:\n (empty) OK\n [] OK \n [][] OK \n [[][]] OK \n ][ NOT OK\n ][][ NOT OK\n []][[] NOT OK\n\n", "solution": "import java.util.Random\n\nfun isBalanced(s: String): Boolean {\n if (s.isEmpty()) return true\n var countLeft = 0 // number of left brackets so far unmatched\n for (c in s) {\n if (c == '[') countLeft++\n else if (countLeft > 0) countLeft--\n else return false\n }\n return countLeft == 0\n}\n\nfun main(args: Array) {\n println(\"Checking examples in task description:\")\n val brackets = arrayOf(\"\", \"[]\", \"][\", \"[][]\", \"][][\", \"[[][]]\", \"[]][[]\")\n for (b in brackets) {\n print(if (b != \"\") b else \"(empty)\")\n println(\"\\t \" + if (isBalanced(b)) \"OK\" else \"NOT OK\")\n }\n println()\n\n println(\"Checking 7 random strings of brackets of length 8:\")\n val r = Random()\n (1..7).forEach {\n var s = \"\"\n for (j in 1..8) {\n s += if (r.nextInt(2) == 0) '[' else ']'\n }\n println(\"$s \" + if (isBalanced(s)) \"OK\" else \"NOT OK\")\n }\n}"} {"title": "Balanced ternary", "language": "Kotlin", "task": "Balanced ternary is a way of representing numbers. Unlike the prevailing binary representation, a balanced ternary integer is in base 3, and each digit can have the values 1, 0, or -1. \n\n\n;Examples:\nDecimal 11 = 32 + 31 - 30, thus it can be written as \"++-\"\n\nDecimal 6 = 32 - 31 + 0 x 30, thus it can be written as \"+-0\"\n\n\n;Task:\nImplement balanced ternary representation of integers with the following:\n# Support arbitrarily large integers, both positive and negative;\n# Provide ways to convert to and from text strings, using digits '+', '-' and '0' (unless you are already using strings to represent balanced ternary; but see requirement 5).\n# Provide ways to convert to and from native integer type (unless, improbably, your platform's native integer type ''is'' balanced ternary). If your native integers can't support arbitrary length, overflows during conversion must be indicated.\n# Provide ways to perform addition, negation and multiplication directly on balanced ternary integers; do ''not'' convert to native integers first.\n# Make your implementation efficient, with a reasonable definition of \"efficient\" (and with a reasonable definition of \"reasonable\").\n\n\n'''Test case''' With balanced ternaries ''a'' from string \"+-0++0+\", ''b'' from native integer -436, ''c'' \"+-++-\":\n* write out ''a'', ''b'' and ''c'' in decimal notation;\n* calculate ''a'' x (''b'' - ''c''), write out the result in both ternary and decimal notations.\n\n\n'''Note:''' The pages floating point balanced ternary.\n\n", "solution": "// version 1.1.3\n\nimport java.math.BigInteger\n\nval bigZero = BigInteger.ZERO\nval bigOne = BigInteger.ONE\nval bigThree = BigInteger.valueOf(3L)\n\ndata class BTernary(private var value: String) : Comparable {\n\n init {\n require(value.all { it in \"0+-\" })\n value = value.trimStart('0')\n }\n\n constructor(v: Int) : this(BigInteger.valueOf(v.toLong()))\n\n constructor(v: BigInteger) : this(\"\") {\n value = toBT(v)\n }\n\n private fun toBT(v: BigInteger): String {\n if (v < bigZero) return flip(toBT(-v))\n if (v == bigZero) return \"\"\n val rem = mod3(v)\n return when (rem) {\n bigZero -> toBT(v / bigThree) + \"0\"\n bigOne -> toBT(v / bigThree) + \"+\"\n else -> toBT((v + bigOne) / bigThree) + \"-\"\n }\n }\n\n private fun flip(s: String): String {\n val sb = StringBuilder()\n for (c in s) {\n sb.append(when (c) {\n '+' -> \"-\"\n '-' -> \"+\"\n else -> \"0\"\n })\n }\n return sb.toString()\n }\n\n private fun mod3(v: BigInteger): BigInteger {\n if (v > bigZero) return v % bigThree\n return ((v % bigThree) + bigThree) % bigThree\n }\n\n fun toBigInteger(): BigInteger {\n val len = value.length\n var sum = bigZero\n var pow = bigOne\n for (i in 0 until len) {\n val c = value[len - i - 1]\n val dig = when (c) {\n '+' -> bigOne\n '-' -> -bigOne\n else -> bigZero\n }\n if (dig != bigZero) sum += dig * pow\n pow *= bigThree\n }\n return sum\n }\n\n private fun addDigits(a: Char, b: Char, carry: Char): String {\n val sum1 = addDigits(a, b)\n val sum2 = addDigits(sum1.last(), carry)\n return when {\n sum1.length == 1 -> sum2\n sum2.length == 1 -> sum1.take(1) + sum2\n else -> sum1.take(1)\n }\n }\n\n private fun addDigits(a: Char, b: Char): String =\n when {\n a == '0' -> b.toString()\n b == '0' -> a.toString()\n a == '+' -> if (b == '+') \"+-\" else \"0\"\n else -> if (b == '+') \"0\" else \"-+\"\n }\n\n operator fun plus(other: BTernary): BTernary {\n var a = this.value\n var b = other.value\n val longer = if (a.length > b.length) a else b\n var shorter = if (a.length > b.length) b else a\n while (shorter.length < longer.length) shorter = \"0\" + shorter\n a = longer\n b = shorter\n var carry = '0'\n var sum = \"\"\n for (i in 0 until a.length) {\n val place = a.length - i - 1\n val digisum = addDigits(a[place], b[place], carry)\n carry = if (digisum.length != 1) digisum[0] else '0'\n sum = digisum.takeLast(1) + sum\n }\n sum = carry.toString() + sum\n return BTernary(sum)\n }\n\n operator fun unaryMinus() = BTernary(flip(this.value))\n\n operator fun minus(other: BTernary) = this + (-other)\n\n operator fun times(other: BTernary): BTernary {\n var that = other\n val one = BTernary(1)\n val zero = BTernary(0)\n var mul = zero\n var flipFlag = false\n if (that < zero) {\n that = -that\n flipFlag = true\n }\n var i = one\n while (i <= that) {\n mul += this\n i += one\n }\n if (flipFlag) mul = -mul\n return mul\n }\n\n override operator fun compareTo(other: BTernary) =\n this.toBigInteger().compareTo(other.toBigInteger())\n\n override fun toString() = value\n}\n\nfun main(args: Array) {\n val a = BTernary(\"+-0++0+\")\n val b = BTernary(-436)\n val c = BTernary(\"+-++-\")\n println(\"a = ${a.toBigInteger()}\")\n println(\"b = ${b.toBigInteger()}\")\n println(\"c = ${c.toBigInteger()}\")\n val bResult = a * (b - c)\n val iResult = bResult.toBigInteger()\n println(\"a * (b - c) = $bResult = $iResult\")\n}"} {"title": "Barnsley fern", "language": "Kotlin from Java", "task": "A Barnsley fern is a fractal named after British mathematician Michael Barnsley and can be created using an iterated function system (IFS).\n\n\n;Task:\nCreate this fractal fern, using the following transformations:\n* f1 (chosen 1% of the time)\n xn + 1 = 0\n yn + 1 = 0.16 yn\n\n* f2 (chosen 85% of the time)\n xn + 1 = 0.85 xn + 0.04 yn\n yn + 1 = -0.04 xn + 0.85 yn + 1.6\n\n* f3 (chosen 7% of the time)\n xn + 1 = 0.2 xn - 0.26 yn\n yn + 1 = 0.23 xn + 0.22 yn + 1.6\n\n* f4 (chosen 7% of the time)\n xn + 1 = -0.15 xn + 0.28 yn\n yn + 1 = 0.26 xn + 0.24 yn + 0.44.\n\nStarting position: x = 0, y = 0\n\n", "solution": "// version 1.1.0\n\nimport java.awt.*\nimport java.awt.image.BufferedImage\nimport javax.swing.*\n \nclass BarnsleyFern(private val dim: Int) : JPanel() {\n private val img: BufferedImage\n \n init {\n preferredSize = Dimension(dim, dim)\n background = Color.black\n img = BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB)\n createFern(dim, dim)\n }\n\n private fun createFern(w: Int, h: Int) {\n var x = 0.0\n var y = 0.0\n for (i in 0 until 200_000) {\n var tmpx: Double\n var tmpy: Double\n val r = Math.random()\n if (r <= 0.01) {\n tmpx = 0.0\n tmpy = 0.16 * y\n }\n else if (r <= 0.86) {\n tmpx = 0.85 * x + 0.04 * y\n tmpy = -0.04 * x + 0.85 * y + 1.6\n }\n else if (r <= 0.93) {\n tmpx = 0.2 * x - 0.26 * y\n tmpy = 0.23 * x + 0.22 * y + 1.6\n } \n else {\n tmpx = -0.15 * x + 0.28 * y\n tmpy = 0.26 * x + 0.24 * y + 0.44\n } \n x = tmpx\n y = tmpy\n img.setRGB(Math.round(w / 2.0 + x * w / 11.0).toInt(),\n Math.round(h - y * h / 11.0).toInt(), 0xFF32CD32.toInt())\n }\n }\n\n override protected fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) \n g.drawImage(img, 0, 0, null)\n } \n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Barnsley Fern\"\n f.setResizable(false)\n f.add(BarnsleyFern(640), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.setVisible(true)\n }\n}"} {"title": "Base64 decode data", "language": "Kotlin from D", "task": "See [[Base64 encode data]]. \n\nNow write a program that takes the output of the [[Base64 encode data]] task as input and regenerate the original file. \n\nWhen working on the VBA implementation I found several 'solutions' on the net, including one from the software maker himself, that showed output with incorrect padding. Obviously with incorrect padding in the output you can not decode correctly to the original file again.\n\n", "solution": "import java.util.Base64\n\nfun main() {\n val data =\n \"VG8gZXJyIGlzIGh1bWFuLCBidXQgdG8gcmVhbGx5IGZvdWwgdGhpbmdzIHVwIHlvdSBuZWVkIGEgY29tcHV0ZXIuCiAgICAtLSBQYXVsIFIuIEVocmxpY2g=\"\n val decoder = Base64.getDecoder()\n val decoded = decoder.decode(data)\n val decodedStr = String(decoded, Charsets.UTF_8)\n println(decodedStr)\n}"} {"title": "Bell numbers", "language": "Kotlin from C", "task": "Bell or exponential numbers are enumerations of the number of different ways to partition a set that has exactly '''n''' elements. Each element of the sequence '''Bn''' is the number of partitions of a set of size '''n''' where order of the elements and order of the partitions are non-significant. E.G.: '''{a b}''' is the same as '''{b a}''' and '''{a} {b}''' is the same as '''{b} {a}'''.\n\n\n;So:\n\n:'''B0 = 1''' trivially. There is only one way to partition a set with zero elements. '''{ }'''\n\n:'''B1 = 1''' There is only one way to partition a set with one element. '''{a}'''\n\n:'''B2 = 2''' Two elements may be partitioned in two ways. '''{a} {b}, {a b}'''\n\n:'''B3 = 5''' Three elements may be partitioned in five ways '''{a} {b} {c}, {a b} {c}, {a} {b c}, {a c} {b}, {a b c}'''\n\n: and so on.\n\n\nA simple way to find the Bell numbers is construct a '''Bell triangle''', also known as an '''Aitken's array''' or '''Peirce triangle''', and read off the numbers in the first column of each row. There are other generating algorithms though, and you are free to choose the best / most appropriate for your case.\n\n\n;Task:\n\nWrite a routine (function, generator, whatever) to generate the Bell number sequence and call the routine to show here, on this page at least the '''first 15''' and (if your language supports big Integers) '''50th''' elements of the sequence. \n\nIf you ''do'' use the Bell triangle method to generate the numbers, also show the '''first ten rows''' of the Bell triangle.\n\n\n;See also:\n\n:* '''OEIS:A000110 Bell or exponential numbers'''\n:* '''OEIS:A011971 Aitken's array'''\n\n", "solution": "class BellTriangle(n: Int) {\n private val arr: Array\n\n init {\n val length = n * (n + 1) / 2\n arr = Array(length) { 0 }\n\n set(1, 0, 1)\n for (i in 2..n) {\n set(i, 0, get(i - 1, i - 2))\n for (j in 1 until i) {\n val value = get(i, j - 1) + get(i - 1, j - 1)\n set(i, j, value)\n }\n }\n }\n\n private fun index(row: Int, col: Int): Int {\n require(row > 0)\n require(col >= 0)\n require(col < row)\n return row * (row - 1) / 2 + col\n }\n\n operator fun get(row: Int, col: Int): Int {\n val i = index(row, col)\n return arr[i]\n }\n\n private operator fun set(row: Int, col: Int, value: Int) {\n val i = index(row, col)\n arr[i] = value\n }\n}\n\nfun main() {\n val rows = 15\n val bt = BellTriangle(rows)\n\n println(\"First fifteen Bell numbers:\")\n for (i in 1..rows) {\n println(\"%2d: %d\".format(i, bt[i, 0]))\n }\n\n for (i in 1..10) {\n print(\"${bt[i, 0]}\")\n for (j in 1 until i) {\n print(\", ${bt[i, j]}\")\n }\n println()\n }\n}"} {"title": "Benford's law", "language": "Kotlin", "task": "{{Wikipedia|Benford's_law}}\n\n\n'''Benford's law''', also called the '''first-digit law''', refers to the frequency distribution of digits in many (but not all) real-life sources of data. \n\nIn this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. \n\nBenford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.\n\nThis result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.\n\nA set of numbers is said to satisfy Benford's law if the leading digit d (d \\in \\{1, \\ldots, 9\\}) occurs with probability\n\n:::: P(d) = \\log_{10}(d+1)-\\log_{10}(d) = \\log_{10}\\left(1+\\frac{1}{d}\\right)\n\nFor this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).\n\nUse the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. \n\nYou can generate them or load them from a file; whichever is easiest. \n\nDisplay your actual vs expected distribution.\n\n\n''For extra credit:'' Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.\n\n\n;See also:\n* numberphile.com.\n* A starting page on Wolfram Mathworld is {{Wolfram|Benfords|Law}}.\n\n", "solution": "import java.math.BigInteger\n\ninterface NumberGenerator {\n val numbers: Array\n}\n\nclass Benford(ng: NumberGenerator) {\n override fun toString() = str\n\n private val firstDigits = IntArray(9)\n private val count = ng.numbers.size.toDouble()\n private val str: String\n\n init {\n for (n in ng.numbers) {\n firstDigits[n.toString().substring(0, 1).toInt() - 1]++\n }\n\n str = with(StringBuilder()) {\n for (i in firstDigits.indices) {\n append(i + 1).append('\\t').append(firstDigits[i] / count)\n append('\\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\\n')\n }\n\n toString()\n }\n }\n}\n\nobject FibonacciGenerator : NumberGenerator {\n override val numbers: Array by lazy {\n val fib = Array(1000, { BigInteger.ONE })\n for (i in 2 until fib.size)\n fib[i] = fib[i - 2].add(fib[i - 1])\n fib\n }\n}\n\nfun main(a: Array) = println(Benford(FibonacciGenerator))"} {"title": "Best shuffle", "language": "Kotlin from Java", "task": "Shuffle the characters of a string in such a way that as many of the character values are in a different position as possible. \n\nA shuffle that produces a randomized result among the best choices is to be preferred. A deterministic approach that produces the same sequence every time is acceptable as an alternative.\n\nDisplay the result as follows: \n\n original string, shuffled string, (score) \n\nThe score gives the number of positions whose character value did ''not'' change. \n\n\n;Example:\n tree, eetr, (0)\n\n\n;Test cases:\n abracadabra\n seesaw\n elk\n grrrrrr\n up\n a\n\n\n;Related tasks\n* [[Anagrams/Deranged anagrams]]\n* [[Permutations/Derangements]]\n\n\n\n", "solution": "import java.util.Random\n\nobject BestShuffle {\n operator fun invoke(s1: String) : String {\n val s2 = s1.toCharArray()\n s2.shuffle()\n for (i in s2.indices)\n if (s2[i] == s1[i])\n for (j in s2.indices)\n if (s2[i] != s2[j] && s2[i] != s1[j] && s2[j] != s1[i]) {\n val tmp = s2[i]\n s2[i] = s2[j]\n s2[j] = tmp\n break\n }\n return s1 + ' ' + String(s2) + \" (\" + s2.count(s1) + ')'\n }\n\n private fun CharArray.shuffle() {\n val rand = Random()\n for (i in size - 1 downTo 1) {\n val r = rand.nextInt(i + 1)\n val tmp = this[i]\n this[i] = this[r]\n this[r] = tmp\n }\n }\n\n private fun CharArray.count(s1: String) : Int {\n var count = 0\n for (i in indices)\n if (s1[i] == this[i]) count++\n return count\n }\n}\n\nfun main(words: Array) = words.forEach { println(BestShuffle(it)) }"} {"title": "Bioinformatics/base count", "language": "Kotlin", "task": "Given this string representing ordered DNA bases:\n\nCGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATG\nCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTG\nAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGAT\nGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTT\nCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGG\nTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATA\nTTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTAT\nCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTG\nTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGAC\nGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\n\n\n\n;Task:\n:* \"Pretty print\" the sequence followed by a summary of the counts of each of the bases: ('''A''', '''C''', '''G''', and '''T''') in the sequence \n:* print the total count of each base in the string.\n\n\n\n", "solution": "fun printSequence(sequence: String, width: Int = 50) {\n fun printWithLabel(k: K, v: V) {\n val label = k.toString().padStart(5)\n println(\"$label: $v\")\n }\n\n println(\"SEQUENCE:\")\n sequence.chunked(width).withIndex().forEach { (i, line) ->\n printWithLabel(i*width + line.length, line)\n }\n println(\"BASE:\")\n sequence.groupingBy { it }.eachCount().forEach { (k, v) ->\n printWithLabel(k, v)\n }\n printWithLabel(\"TOTALS\", sequence.length)\n}\n\nconst val BASE_SEQUENCE = \"CGTAAAAAATTACAACGTCCTTTGGCTATCTCTTAAACTCCTGCTAAATGCTCGTGCTTTCCAATTATGTAAGCGTTCCGAGACGGGGTGGTCGATTCTGAGGACAAAGGTCAAGATGGAGCGCATCGAACGCAATAAGGATCATTTGATGGGACGTTTCGTCGACAAAGTCTTGTTTCGAGAGTAACGGCTACCGTCTTCGATTCTGCTTATAACACTATGTTCTTATGAAATGGATGTTCTGAGTTGGTCAGTCCCAATGTGCGGGGTTTCTTTTAGTACGTCGGGAGTGGTATTATATTTAATTTTTCTATATAGCGATCTGTATTTAAGCAATTCATTTAGGTTATCGCCGCGATGCTCGGTTCGGACCGCCAAGCATCTGGCTCCACTGCTAGTGTCCTAAATTTGAATGGCAAACACAAATAAGATTTAGCAATTCGTGTAGACGACCGGGGACTTGCATGATGGGAGCAGCTTTGTTAAACTACGAACGTAAT\"\n\nfun main() {\n printSequence(BASE_SEQUENCE)\n}"} {"title": "Bitcoin/address validation", "language": "Kotlin from Java", "task": "Write a program that takes a bitcoin address as argument, \nand checks whether or not this address is valid.\n\nA bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters:\n:::* 0 zero\n:::* O uppercase oh\n:::* I uppercase eye\n:::* l lowercase ell\n\n\nWith this encoding, a bitcoin address encodes 25 bytes:\n* the first byte is the version number, which will be zero for this task ;\n* the next twenty bytes are a [[RIPEMD-160]] digest, but you don't have to know that for this task: you can consider them a pure arbitrary data ;\n* the last four bytes are a checksum check. They are the first four bytes of a double [[SHA-256]] digest of the previous 21 bytes.\n\n\nTo check the bitcoin address, you must read the first twenty-one bytes, compute the checksum, and check that it corresponds to the last four bytes.\n\nThe program can either return a boolean value or throw an exception when not valid.\n\nYou can use a digest library for [[SHA-256]].\n\n\n;Example of a bitcoin address:\n\n 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\n\n\nIt doesn't belong to anyone and is part of the test suite of the bitcoin software. \nYou can change a few characters in this string and check that it'll fail the test.\n\n", "solution": "import java.security.MessageDigest\n\nobject Bitcoin {\n private const val ALPHABET = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n private fun ByteArray.contentEquals(other: ByteArray): Boolean {\n if (this.size != other.size) return false\n return (0 until this.size).none { this[it] != other[it] }\n }\n\n private fun decodeBase58(input: String): ByteArray? {\n val output = ByteArray(25)\n for (c in input) {\n var p = ALPHABET.indexOf(c)\n if (p == -1) return null\n for (j in 24 downTo 1) {\n p += 58 * (output[j].toInt() and 0xff)\n output[j] = (p % 256).toByte()\n p = p shr 8\n }\n if (p != 0) return null\n }\n return output\n }\n\n private fun sha256(data: ByteArray, start: Int, len: Int, recursion: Int): ByteArray {\n if (recursion == 0) return data\n val md = MessageDigest.getInstance(\"SHA-256\")\n md.update(data.sliceArray(start until start + len))\n return sha256(md.digest(), 0, 32, recursion - 1)\n }\n\n fun validateAddress(address: String): Boolean {\n if (address.length !in 26..35) return false\n val decoded = decodeBase58(address)\n if (decoded == null) return false\n val hash = sha256(decoded, 0, 21, 2)\n return hash.sliceArray(0..3).contentEquals(decoded.sliceArray(21..24))\n }\n}\n\nfun main(args: Array) {\n val addresses = arrayOf(\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62j\",\n \"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62X\",\n \"1ANNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\",\n \"1A Na15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i\",\n \"BZbvjr\",\n \"i55j\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62!\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62iz\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62izz\",\n \"1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nJ9\",\n \"1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62I\"\n )\n for (address in addresses)\n println(\"${address.padEnd(36)} -> ${if (Bitcoin.validateAddress(address)) \"valid\" else \"invalid\"}\")\n}"} {"title": "Bitwise IO", "language": "Kotlin from C", "task": "The aim of this task is to write functions (or create a class if yourlanguage is Object Oriented and you prefer) for reading and writing sequences of\nbits, most significant bit first. While the output of a asciiprint \"STRING\" is the ASCII byte sequence\n\"S\", \"T\", \"R\", \"I\", \"N\", \"G\", the output of a \"print\" of the bits sequence\n0101011101010 (13 bits) must be 0101011101010; real I/O is performed always\n''quantized'' by byte (avoiding endianness issues and relying on underlying\nbuffering for performance), therefore you must obtain as output the bytes\n0101 0111 0101 0'''000''' (bold bits are padding bits), i.e. in hexadecimal 57 50.\n\nAs test, you can implement a '''rough''' (e.g. don't care about error handling or\nother issues) compression/decompression program for ASCII sequences\nof bytes, i.e. bytes for which the most significant bit is always unused, so that you can write\nseven bits instead of eight (each 8 bytes of input, we write 7 bytes of output).\n\nThese bit oriented I/O functions can be used to implement compressors and\ndecompressors; e.g. Dynamic and Static Huffman encodings use variable length\nbits sequences, while LZW (see [[LZW compression]]) use fixed or variable ''words''\nnine (or more) bits long.\n\n* Limits in the maximum number of bits that can be written/read in a single read/write operation are allowed.\n* Errors handling is not mandatory\n\n", "solution": "// version 1.2.31\n\nimport java.io.File\n\nclass BitFilter(val f: File, var accu: Int = 0, var bits: Int = 0) {\n\n private val bw = f.bufferedWriter()\n private val br = f.bufferedReader()\n \n fun write(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) {\n var nBits = _nBits\n var index = start + _shift / 8\n var shift = _shift % 8\n\n while (nBits != 0 || bits >= 8) {\n while (bits >= 8) {\n bits -= 8\n bw.write(accu ushr bits)\n accu = accu and ((1 shl bits) - 1)\n }\n while (bits < 8 && nBits != 0) {\n val b = buf[index].toInt()\n accu = (accu shl 1) or (((128 ushr shift) and b) ushr (7 - shift))\n nBits--\n bits++\n if (++shift == 8) { shift = 0; index++ }\n }\n }\n }\n\n fun read(buf: ByteArray, start: Int, _nBits: Int, _shift: Int) {\n var nBits = _nBits\n var index = start + _shift / 8\n var shift = _shift % 8\n\n while (nBits != 0) {\n while (bits != 0 && nBits != 0) {\n val mask = 128 ushr shift\n if ((accu and (1 shl (bits - 1))) != 0)\n buf[index] = (buf[index].toInt() or mask).toByte()\n else\n buf[index] = (buf[index].toInt() and mask.inv()).toByte()\n nBits--\n bits--\n if (++shift >= 8) { shift = 0; index++ }\n }\n if (nBits == 0) break\n accu = (accu shl 8) or br.read()\n bits += 8\n }\n }\n\n fun closeWriter() {\n if (bits != 0) {\n accu = (accu shl (8 - bits))\n bw.write(accu)\n }\n bw.close()\n accu = 0\n bits = 0\n }\n\n fun closeReader() {\n br.close()\n accu = 0\n bits = 0\n }\n}\n\nfun main(args: Array) {\n val s = \"abcdefghijk\".toByteArray(Charsets.UTF_8)\n val f = File(\"test.bin\")\n val bf = BitFilter(f)\n\n /* for each byte in s, write 7 bits skipping 1 */\n for (i in 0 until s.size) bf.write(s, i, 7, 1)\n bf.closeWriter()\n\n /* read 7 bits and expand to each byte of s2 skipping 1 bit */\n val s2 = ByteArray(s.size)\n for (i in 0 until s2.size) bf.read(s2, i, 7, 1)\n bf.closeReader()\n println(String(s2, Charsets.UTF_8))\n}"} {"title": "Box the compass", "language": "Kotlin", "task": "Avast me hearties!\nThere be many a land lubber that knows naught of the pirate ways and gives direction by degree!\nThey know not how to box the compass! \n\n\n;Task description:\n# Create a function that takes a heading in degrees and returns the correct 32-point compass heading.\n# Use the function to print and display a table of Index, Compass point, and Degree; rather like the corresponding columns from, the first table of the wikipedia article, but use only the following 33 headings as input:\n:[0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]. (They should give the same order of points but are spread throughout the ranges of acceptance).\n\n\n;Notes;\n* The headings and indices can be calculated from this pseudocode:\nfor i in 0..32 inclusive:\n heading = i * 11.25\n case i %3:\n if 1: heading += 5.62; break\n if 2: heading -= 5.62; break\n end\n index = ( i mod 32) + 1\n* The column of indices can be thought of as an enumeration of the thirty two cardinal points (see talk page)..\n\n", "solution": "// version 1.1.2\n\nfun expand(cp: String): String {\n val sb = StringBuilder()\n for (c in cp) {\n sb.append(when (c) {\n 'N' -> \"north\" \n 'E' -> \"east\"\n 'S' -> \"south\"\n 'W' -> \"west\"\n 'b' -> \" by \"\n else -> \"-\"\n })\n }\n return sb.toString().capitalize()\n}\n\nfun main(args: Array) {\n val cp = arrayOf(\n \"N\", \"NbE\", \"N-NE\", \"NEbN\", \"NE\", \"NEbE\", \"E-NE\", \"EbN\",\n \"E\", \"EbS\", \"E-SE\", \"SEbE\", \"SE\", \"SEbS\", \"S-SE\", \"SbE\",\n \"S\", \"SbW\", \"S-SW\", \"SWbS\", \"SW\", \"SWbW\", \"W-SW\", \"WbS\",\n \"W\", \"WbN\", \"W-NW\", \"NWbW\", \"NW\", \"NWbN\", \"N-NW\", \"NbW\"\n )\n println(\"Index Degrees Compass point\")\n println(\"----- ------- -------------\")\n val f = \"%2d %6.2f %s\"\n for (i in 0..32) {\n val index = i % 32\n var heading = i * 11.25\n when (i % 3) {\n 1 -> heading += 5.62\n 2 -> heading -= 5.62\n }\n println(f.format(index + 1, heading, expand(cp[index])))\n }\n}"} {"title": "Brazilian numbers", "language": "Kotlin from C#", "task": "Brazilian numbers are so called as they were first formally presented at the 1994 math Olympiad ''Olimpiada Iberoamericana de Matematica'' in Fortaleza, Brazil.\n\nBrazilian numbers are defined as:\n\nThe set of positive integer numbers where each number '''N''' has at least one natural number '''B''' where '''1 < B < N-1''' where the representation of '''N''' in '''base B''' has all equal digits.\n\n\n;E.G.:\n\n:* '''1, 2 & 3''' can not be Brazilian; there is no base '''B''' that satisfies the condition '''1 < B < N-1'''.\n:* '''4''' is not Brazilian; '''4''' in '''base 2''' is '''100'''. The digits are not all the same.\n:* '''5''' is not Brazilian; '''5''' in '''base 2''' is '''101''', in '''base 3''' is '''12'''. There is no representation where the digits are the same.\n:* '''6''' is not Brazilian; '''6''' in '''base 2''' is '''110''', in '''base 3''' is '''20''', in '''base 4''' is '''12'''. There is no representation where the digits are the same.\n:* '''7''' ''is'' Brazilian; '''7''' in '''base 2''' is '''111'''. There is at least one representation where the digits are all the same.\n:* '''8''' ''is'' Brazilian; '''8''' in '''base 3''' is '''22'''. There is at least one representation where the digits are all the same.\n:* ''and so on...''\n\n\nAll even integers '''2P >= 8''' are Brazilian because '''2P = 2(P-1) + 2''', which is '''22''' in '''base P-1''' when '''P-1 > 2'''. That becomes true when '''P >= 4'''.\nMore common: for all all integers '''R''' and '''S''', where '''R > 1''' and also '''S-1 > R''', then '''R*S''' is Brazilian because '''R*S = R(S-1) + R''', which is '''RR''' in '''base S-1'''\nThe only problematic numbers are squares of primes, where R = S. Only 11^2 is brazilian to base 3. \nAll prime integers, that are brazilian, can only have the digit '''1'''. Otherwise one could factor out the digit, therefore it cannot be a prime number. Mostly in form of '''111''' to base Integer(sqrt(prime number)). Must be an odd count of '''1''' to stay odd like primes > 2\n\n;Task:\n\nWrite a routine (function, whatever) to determine if a number is Brazilian and use the routine to show here, on this page;\n\n:* the first '''20''' Brazilian numbers;\n:* the first '''20 odd''' Brazilian numbers;\n:* the first '''20 prime''' Brazilian numbers;\n\n\n;See also:\n\n:* '''OEIS:A125134 - Brazilian numbers'''\n:* '''OEIS:A257521 - Odd Brazilian numbers'''\n:* '''OEIS:A085104 - Prime Brazilian numbers'''\n\n", "solution": "fun sameDigits(n: Int, b: Int): Boolean {\n var n2 = n\n val f = n % b\n while (true) {\n n2 /= b\n if (n2 > 0) {\n if (n2 % b != f) {\n return false\n }\n } else {\n break\n }\n }\n return true\n}\n\nfun isBrazilian(n: Int): Boolean {\n if (n < 7) return false\n if (n % 2 == 0) return true\n for (b in 2 until n - 1) {\n if (sameDigits(n, b)) {\n return true\n }\n }\n return false\n}\n\nfun isPrime(n: Int): Boolean {\n if (n < 2) return false\n if (n % 2 == 0) return n == 2\n if (n % 3 == 0) return n == 3\n var d = 5\n while (d * d <= n) {\n if (n % d == 0) return false\n d += 2\n if (n % d == 0) return false\n d += 4\n }\n return true\n}\n\nfun main() {\n val bigLim = 99999\n val limit = 20\n for (kind in \",odd ,prime\".split(',')) {\n var quiet = false\n println(\"First $limit ${kind}Brazilian numbers:\")\n var c = 0\n var n = 7\n while (c < bigLim) {\n if (isBrazilian(n)) {\n if (!quiet) print(\"%,d \".format(n))\n if (++c == limit) {\n print(\"\\n\\n\")\n quiet = true\n }\n }\n if (quiet && kind != \"\") continue\n when (kind) {\n \"\" -> n++\n \"odd \" -> n += 2\n \"prime\" -> {\n while (true) {\n n += 2\n if (isPrime(n)) break\n }\n }\n }\n }\n if (kind == \"\") println(\"The %,dth Brazilian number is: %,d\".format(bigLim + 1, n))\n }\n}"} {"title": "Break OO privacy", "language": "Kotlin", "task": "Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. \nThe intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. \nThe intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory.\n\nNote that cheating on your type system is almost universally regarded \nas unidiomatic at best, and poor programming practice at worst. \nNonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off.\n", "solution": "import kotlin.reflect.full.declaredMemberProperties\nimport kotlin.reflect.jvm.isAccessible\n\nclass ToBeBroken {\n @Suppress(\"unused\")\n private val secret: Int = 42\n}\n\nfun main(args: Array) {\n val tbb = ToBeBroken()\n val props = ToBeBroken::class.declaredMemberProperties\n for (prop in props) {\n prop.isAccessible = true // make private properties accessible\n println(\"${prop.name} -> ${prop.get(tbb)}\")\n }\n}"} {"title": "Burrows\u2013Wheeler transform", "language": "Kotlin from Python", "task": "{{Wikipedia|Burrows-Wheeler_transform}}\n\n\nThe Burrows-Wheeler transform (BWT, also called block-sorting compression) rearranges a character string into runs of similar characters. \n\nThis is useful for compression, since it tends to be easy to compress a string that has runs of repeated characters by techniques such as move-to-front transform and run-length encoding. \n\nMore importantly, the transformation is reversible, without needing to store any additional data. \n\nThe BWT is thus a \"free\" method of improving the efficiency of text compression algorithms, costing only some extra computation.\n\n\nSource: Burrows-Wheeler transform\n\n", "solution": "// Version 1.2.60\n\nconst val STX = \"\\u0002\"\nconst val ETX = \"\\u0003\"\n\nfun bwt(s: String): String {\n if (s.contains(STX) || s.contains(ETX)) {\n throw RuntimeException(\"String can't contain STX or ETX\")\n }\n val ss = STX + s + ETX\n val table = Array(ss.length) { ss.substring(it) + ss.substring(0, it) }\n table.sort()\n return String(table.map { it[it.lastIndex] }.toCharArray())\n}\n\nfun ibwt(r: String): String {\n val len = r.length\n val table = Array(len) { \"\" }\n repeat(len) {\n for (i in 0 until len) {\n table[i] = r[i].toString() + table[i]\n }\n table.sort()\n }\n for (row in table) {\n if (row.endsWith(ETX)) {\n return row.substring(1, len - 1)\n }\n }\n return \"\"\n}\n\nfun makePrintable(s: String): String {\n // substitute ^ for STX and | for ETX to print results\n return s.replace(STX, \"^\").replace(ETX, \"|\")\n}\n\nfun main(args: Array) {\n val tests = listOf(\n \"banana\",\n \"appellee\",\n \"dogwood\",\n \"TO BE OR NOT TO BE OR WANT TO BE OR NOT?\",\n \"SIX.MIXED.PIXIES.SIFT.SIXTY.PIXIE.DUST.BOXES\",\n \"\\u0002ABC\\u0003\"\n )\n for (test in tests) {\n println(makePrintable(test))\n print(\" --> \")\n var t = \"\"\n try {\n t = bwt(test)\n println(makePrintable(t))\n }\n catch (ex: RuntimeException) {\n println(\"ERROR: \" + ex.message)\n }\n val r = ibwt(t)\n println(\" --> $r\\n\")\n }\n}"} {"title": "CSV data manipulation", "language": "Kotlin", "task": "CSV spreadsheet files are suitable for storing tabular data in a relatively portable way. \n\nThe CSV format is flexible but somewhat ill-defined. \n\nFor present purposes, authors may assume that the data fields contain no commas, backslashes, or quotation marks.\n\n\n;Task:\nRead a CSV file, change some values and save the changes back to a file.\n\nFor this task we will use the following CSV file:\n\n C1,C2,C3,C4,C5\n 1,5,9,13,17\n 2,6,10,14,18\n 3,7,11,15,19\n 4,8,12,16,20\n\nSuggestions\n\n Show how to add a column, headed 'SUM', of the sums of the rows.\n If possible, illustrate the use of built-in or standard functions, methods, or libraries, that handle generic CSV files.\n\n\n", "solution": "// version 1.1.3\n\nimport java.io.File\n\nfun main(args: Array) {\n val lines = File(\"example.csv\").readLines().toMutableList()\n lines[0] += \",SUM\"\n for (i in 1 until lines.size) {\n lines[i] += \",\" + lines[i].split(',').sumBy { it.toInt() }\n }\n val text = lines.joinToString(\"\\n\")\n File(\"example2.csv\").writeText(text) // write to new file\n println(text) // print to console\n}"} {"title": "CSV to HTML translation", "language": "Kotlin", "task": "Consider a simplified CSV format where all rows are separated by a newline \nand all columns are separated by commas. \n\nNo commas are allowed as field data, but the data may contain \nother characters and character sequences that would \nnormally be ''escaped'' when converted to HTML\n\n\n;Task:\nCreate a function that takes a string representation of the CSV data\nand returns a text string of an HTML table representing the CSV data. \n\nUse the following data as the CSV text to convert, and show your output.\n: Character,Speech\n: The multitude,The messiah! Show us the messiah!\n: Brians mother,Now you listen here! He's not the messiah; he's a very naughty boy! Now go away!\n: The multitude,Who are you?\n: Brians mother,I'm his mother; that's who!\n: The multitude,Behold his mother! Behold his mother!\n\n\n;Extra credit:\n''Optionally'' allow special formatting for the first row of the table as if it is the tables header row \n(via preferably; CSS if you must).\n\n", "solution": "// version 1.1.3\n\nval csv = \n \"Character,Speech\\n\" +\n \"The multitude,The messiah! Show us the messiah!\\n\" +\n \"Brians mother,Now you listen here! He's not the messiah; \" +\n \"he's a very naughty boy! Now go away!\\n\" +\n \"The multitude,Who are you?\\n\" +\n \"Brians mother,I'm his mother; that's who!\\n\" +\n \"The multitude,Behold his mother! Behold his mother!\"\n\nfun main(args: Array) {\n val i = \" \" // indent\n val sb = StringBuilder(\"\\n$i\\n$i$i\\n$i\\n$i\\n$i$i\\n$i$i\\n$i\\n
\")\n for (c in csv) {\n sb.append( when (c) {\n '\\n' -> \"
\"\n ',' -> \"\"\n '&' -> \"&\"\n '\\'' -> \"'\" \n '<' -> \"<\"\n '>' -> \">\" \n else -> c.toString()\n })\n }\n sb.append(\"
\")\n println(sb.toString())\n println()\n\n // now using first row as a table header\n sb.setLength(0)\n sb.append(\"\\n$i\\n$i$i\\n$i$i$i\\n$i$i\\n$i\\n$i\\n$i$i\\n$i$i$i\\n$i$i$i\\n$i$i\\n$i$i\\n$i$i$i\\n$i$i$i\\n$i$i\\n$i\\n
\")\n val hLength = csv.indexOf('\\n') + 1 // find length of first row including CR\n for (c in csv.take(hLength)) {\n sb.append( when (c) {\n '\\n' -> \"
\"\n ',' -> \"\"\n else -> c.toString()\n })\n }\n for (c in csv.drop(hLength)) {\n sb.append( when (c) {\n '\\n' -> \"
\"\n ',' -> \"\"\n '&' -> \"&\"\n '\\'' -> \"'\" \n '<' -> \"<\"\n '>' -> \">\" \n else -> c.toString()\n })\n }\n sb.append(\"
\")\n println(sb.toString()) \n}"} {"title": "Calculating the value of e", "language": "Kotlin", "task": "Calculate the value of ''e''.\n\n\n(''e'' is also known as ''Euler's number'' and ''Napier's constant''.)\n\n\nSee details: Calculating the value of e\n\n", "solution": "// Version 1.2.40\n\nimport kotlin.math.abs\n\nconst val EPSILON = 1.0e-15\n\nfun main(args: Array) {\n var fact = 1L\n var e = 2.0\n var n = 2\n do {\n val e0 = e\n fact *= n++\n e += 1.0 / fact\n }\n while (abs(e - e0) >= EPSILON)\n println(\"e = %.15f\".format(e))\n}"} {"title": "Call a function", "language": "Kotlin", "task": "Demonstrate the different syntax and semantics provided for calling a function. \n\n\nThis may include:\n:* Calling a function that requires no arguments\n:* Calling a function with a fixed number of arguments\n:* Calling a function with optional arguments\n:* Calling a function with a variable number of arguments\n:* Calling a function with named arguments\n:* Using a function in statement context\n:* Using a function in first-class context within an expression\n:* Obtaining the return value of a function\n:* Distinguishing built-in functions and user-defined functions\n:* Distinguishing subroutines and functions\n;* Stating whether arguments are passed by value or by reference\n;* Is partial application possible and how\n\n\nThis task is ''not'' about defining functions.\n\n", "solution": "fun fun1() = println(\"No arguments\")\n\nfun fun2(i: Int) = println(\"One argument = $i\")\n\nfun fun3(i: Int, j: Int = 0) = println(\"One required argument = $i, one optional argument = $j\")\n\nfun fun4(vararg v: Int) = println(\"Variable number of arguments = ${v.asList()}\")\n\nfun fun5(i: Int) = i * i\n\nfun fun6(i: Int, f: (Int) -> Int) = f(i)\n\nfun fun7(i: Int): Double = i / 2.0\n\nfun fun8(x: String) = { y: String -> x + \" \" + y }\n\nfun main() {\n fun1() // no arguments\n fun2(2) // fixed number of arguments, one here\n fun3(3) // optional argument, default value used here\n fun4(4, 5, 6) // variable number of arguments\n fun3(j = 8, i = 7) // using named arguments, order unimportant\n val b = false\n if (b) fun1() else fun2(9) // statement context\n println(1 + fun6(4, ::fun5) + 3) // first class context within an expression\n println(fun5(5)) // obtaining return value\n println(kotlin.math.round(2.5)) // no distinction between built-in and user-defined functions, though former usually have a receiver\n fun1() // calling sub-routine which has a Unit return type by default\n println(fun7(11)) // calling function with a return type of Double (here explicit but can be implicit)\n println(fun8(\"Hello\")(\"world\")) // partial application isn't supported though you can do this\n}"} {"title": "Cantor set", "language": "Kotlin", "task": "Draw a Cantor set.\n\n\nSee details at this Wikipedia webpage: Cantor set\n\n", "solution": "// Version 1.2.31\n\nconst val WIDTH = 81\nconst val HEIGHT = 5\n\nval lines = List(HEIGHT) { CharArray(WIDTH) { '*' } }\n\nfun cantor(start: Int, len: Int, index: Int) {\n val seg = len / 3\n if (seg == 0) return\n for (i in index until HEIGHT) {\n for (j in start + seg until start + seg * 2) lines[i][j] = ' '\n }\n cantor(start, seg, index + 1)\n cantor(start + seg * 2, seg, index + 1)\n}\n\nfun main(args: Array) {\n cantor(0, WIDTH, 1)\n lines.forEach { println(it) }\n}"} {"title": "Cartesian product of two or more lists", "language": "Kotlin", "task": "Show one or more idiomatic ways of generating the Cartesian product of two arbitrary lists in your language.\n\nDemonstrate that your function/method correctly returns:\n::{1, 2} x {3, 4} = {(1, 3), (1, 4), (2, 3), (2, 4)}\n\nand, in contrast:\n::{3, 4} x {1, 2} = {(3, 1), (3, 2), (4, 1), (4, 2)}\n\nAlso demonstrate, using your function/method, that the product of an empty list with any other list is empty.\n:: {1, 2} x {} = {}\n:: {} x {1, 2} = {}\n\nFor extra credit, show or write a function returning the n-ary product of an arbitrary number of lists, each of arbitrary length. Your function might, for example, accept a single argument which is itself a list of lists, and return the n-ary product of those lists.\n\nUse your n-ary Cartesian product function to show the following products:\n:: {1776, 1789} x {7, 12} x {4, 14, 23} x {0, 1}\n:: {1, 2, 3} x {30} x {500, 100}\n:: {1, 2, 3} x {} x {500, 100}\n\n\n", "solution": "// version 1.1.2\n\nfun flattenList(nestList: List): List {\n val flatList = mutableListOf()\n\n fun flatten(list: List) {\n for (e in list) {\n if (e !is List<*>)\n flatList.add(e)\n else\n @Suppress(\"UNCHECKED_CAST\")\n flatten(e as List)\n }\n }\n\n flatten(nestList)\n return flatList\n}\n\noperator fun List.times(other: List): List> {\n val prod = mutableListOf>()\n for (e in this) {\n for (f in other) {\n prod.add(listOf(e, f))\n }\n }\n return prod\n}\n\nfun nAryCartesianProduct(lists: List>): List> {\n require(lists.size >= 2)\n return lists.drop(2).fold(lists[0] * lists[1]) { cp, ls -> cp * ls }.map { flattenList(it) }\n}\n\nfun printNAryProduct(lists: List>) {\n println(\"${lists.joinToString(\" x \")} = \")\n println(\"[\")\n println(nAryCartesianProduct(lists).joinToString(\"\\n \", \" \"))\n println(\"]\\n\")\n}\n\nfun main(args: Array) {\n println(\"[1, 2] x [3, 4] = ${listOf(1, 2) * listOf(3, 4)}\")\n println(\"[3, 4] x [1, 2] = ${listOf(3, 4) * listOf(1, 2)}\")\n println(\"[1, 2] x [] = ${listOf(1, 2) * listOf()}\")\n println(\"[] x [1, 2] = ${listOf() * listOf(1, 2)}\")\n println(\"[1, a] x [2, b] = ${listOf(1, 'a') * listOf(2, 'b')}\")\n println()\n printNAryProduct(listOf(listOf(1776, 1789), listOf(7, 12), listOf(4, 14, 23), listOf(0, 1)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf(500, 100)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf(), listOf(500, 100)))\n printNAryProduct(listOf(listOf(1, 2, 3), listOf(30), listOf('a', 'b')))\n}"} {"title": "Casting out nines", "language": "Kotlin from D", "task": "Task (in three parts):\n\n\n;Part 1\nWrite a procedure (say \\mathit{co9}(x)) which implements Casting Out Nines as described by returning the checksum for x. Demonstrate the procedure using the examples given there, or others you may consider lucky.\n\nNote that this function does nothing more than calculate the least positive residue, modulo 9. Many of the solutions omit Part 1 for this reason. Many languages have a modulo operator, of which this is a trivial application.\n\nWith that understanding, solutions to Part 1, if given, are encouraged to follow the naive pencil-and-paper or mental arithmetic of repeated digit addition understood to be \"casting out nines\", or some approach other than just reducing modulo 9 using a built-in operator. Solutions for part 2 and 3 are not required to make use of the function presented in part 1.\n\n;Part 2\nNotwithstanding past Intel microcode errors, checking computer calculations like this would not be sensible. To find a computer use for your procedure:\n: Consider the statement \"318682 is 101558 + 217124 and squared is 101558217124\" (see: [[Kaprekar numbers#Casting Out Nines (fast)]]).\n: note that 318682 has the same checksum as (101558 + 217124);\n: note that 101558217124 has the same checksum as (101558 + 217124) because for a Kaprekar they are made up of the same digits (sometimes with extra zeroes);\n: note that this implies that for Kaprekar numbers the checksum of k equals the checksum of k^2.\n\nDemonstrate that your procedure can be used to generate or filter a range of numbers with the property \\mathit{co9}(k) = \\mathit{co9}(k^2) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;Part 3\nConsidering this MathWorld page, produce a efficient algorithm based on the more mathematical treatment of Casting Out Nines, and realizing:\n: \\mathit{co9}(x) is the residual of x mod 9;\n: the procedure can be extended to bases other than 9.\n\nDemonstrate your algorithm by generating or filtering a range of numbers with the property k%(\\mathit{Base}-1) == (k^2)%(\\mathit{Base}-1) and show that this subset is a small proportion of the range and contains all the Kaprekar in the range.\n\n;related tasks\n* [[First perfect square in base N with N unique digits]]\n* [[Kaprekar numbers]]\n\n", "solution": "// version 1.1.3\n\nfun castOut(base: Int, start: Int, end: Int): List {\n val b = base - 1\n val ran = (0 until b).filter { it % b == (it * it) % b }\n var x = start / b\n val result = mutableListOf()\n while (true) {\n for (n in ran) {\n val k = b * x + n\n if (k < start) continue\n if (k > end) return result\n result.add(k)\n }\n x++\n }\n} \n\nfun main(args: Array) {\n println(castOut(16, 1, 255))\n println()\n println(castOut(10, 1, 99))\n println()\n println(castOut(17, 1, 288))\n}"} {"title": "Catalan numbers/Pascal's triangle", "language": "Kotlin", "task": "Print out the first '''15''' Catalan numbers by extracting them from Pascal's triangle.\n\n\n;See:\n* Catalan Numbers and the Pascal Triangle. This method enables calculation of Catalan Numbers using only addition and subtraction.\n\n* Catalan's Triangle for a Number Triangle that generates Catalan Numbers using only addition.\n* Sequence A000108 on OEIS has a lot of information on Catalan Numbers.\n\n;Related Tasks:\n[[Pascal's triangle]]\n\n", "solution": "// version 1.1.2\n\nimport java.math.BigInteger\n\nval ONE = BigInteger.ONE\n\nfun pascal(n: Int, k: Int): BigInteger {\n if (n == 0 || k == 0) return ONE\n val num = (k + 1..n).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n val den = (2..n - k).fold(ONE) { acc, i -> acc * BigInteger.valueOf(i.toLong()) }\n return num / den\n}\n\nfun catalanFromPascal(n: Int) {\n for (i in 1 until n step 2) {\n val mi = i / 2 + 1\n val catalan = pascal(i, mi) - pascal(i, mi - 2) \n println(\"${\"%2d\".format(mi)} : $catalan\")\n }\n}\n \nfun main(args: Array) {\n val n = 15\n catalanFromPascal(n * 2)\n}"} {"title": "Catamorphism", "language": "Kotlin", "task": "''Reduce'' is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value. \n\n\n;Task:\nShow how ''reduce'' (or ''foldl'' or ''foldr'' etc), work (or would be implemented) in your language.\n\n\n;See also:\n* Wikipedia article: Fold\n* Wikipedia article: Catamorphism\n\n", "solution": "fun main(args: Array) {\n val a = intArrayOf(1, 2, 3, 4, 5)\n println(\"Array : ${a.joinToString(\", \")}\")\n println(\"Sum : ${a.reduce { x, y -> x + y }}\")\n println(\"Difference : ${a.reduce { x, y -> x - y }}\")\n println(\"Product : ${a.reduce { x, y -> x * y }}\")\n println(\"Minimum : ${a.reduce { x, y -> if (x < y) x else y }}\")\n println(\"Maximum : ${a.reduce { x, y -> if (x > y) x else y }}\")\n}"} {"title": "Chaocipher", "language": "Kotlin", "task": "Description:\nThe Chaocipher was invented by J.F.Byrne in 1918 and, although simple by modern cryptographic standards, does not appear to have been broken until the algorithm was finally disclosed by his family in 2010.\n\nThe algorithm is described in this paper by M.Rubin in 2010 and there is a C# implementation here.\n\n\n;Task:\nCode the algorithm in your language and to test that it works with the plaintext 'WELLDONEISBETTERTHANWELLSAID' used in the paper itself.\n\n", "solution": "// Version 1.2.40\n\nenum class Mode { ENCRYPT, DECRYPT }\n\nobject Chao {\n private val lAlphabet = \"HXUCZVAMDSLKPEFJRIGTWOBNYQ\"\n private val rAlphabet = \"PTLNBQDEOYSFAVZKGJRIHWXUMC\"\n\n fun exec(text: String, mode: Mode, showSteps: Boolean = false): String {\n var left = lAlphabet\n var right = rAlphabet\n val eText = CharArray(text.length)\n val temp = CharArray(26)\n\n for (i in 0 until text.length) {\n if (showSteps) println(\"$left $right\")\n var index: Int\n if (mode == Mode.ENCRYPT) {\n index = right.indexOf(text[i])\n eText[i] = left[index]\n }\n else {\n index = left.indexOf(text[i])\n eText[i] = right[index]\n }\n if (i == text.length - 1) break\n\n // permute left\n\n for (j in index..25) temp[j - index] = left[j]\n for (j in 0 until index) temp[26 - index + j] = left[j]\n var store = temp[1]\n for (j in 2..13) temp[j - 1] = temp[j]\n temp[13] = store\n left = String(temp)\n\n // permute right\n\n for (j in index..25) temp[j - index] = right[j]\n for (j in 0 until index) temp[26 - index + j] = right[j]\n store = temp[0]\n for (j in 1..25) temp[j - 1] = temp[j]\n temp[25] = store\n store = temp[2]\n for (j in 3..13) temp[j - 1] = temp[j]\n temp[13] = store\n right = String(temp)\n }\n\n return String(eText)\n }\n}\n\nfun main(args: Array) {\n val plainText = \"WELLDONEISBETTERTHANWELLSAID\"\n println(\"The original plaintext is : $plainText\")\n println(\"\\nThe left and right alphabets after each permutation\" +\n \" during encryption are :\\n\")\n val cipherText = Chao.exec(plainText, Mode.ENCRYPT, true)\n println(\"\\nThe ciphertext is : $cipherText\")\n val plainText2 = Chao.exec(cipherText, Mode.DECRYPT)\n println(\"\\nThe recovered plaintext is : $plainText2\")\n}"} {"title": "Chaos game", "language": "Kotlin from Java", "task": "The Chaos Game is a method of generating the attractor of an iterated function system (IFS). \n\nOne of the best-known and simplest examples creates a fractal, using a polygon and an initial point selected at random.\n\n\n;Task\nPlay the Chaos Game using the corners of an equilateral triangle as the reference points. Add a starting point at random (preferably inside the triangle). Then add the next point halfway between the starting point and one of the reference points. This reference point is chosen at random.\n\nAfter a sufficient number of iterations, the image of a Sierpinski Triangle should emerge.\n\n\n;See also\n* The Game of Chaos\n\n", "solution": "//Version 1.1.51\n\nimport java.awt.*\nimport java.util.Stack\nimport java.util.Random\nimport javax.swing.JPanel\nimport javax.swing.JFrame\nimport javax.swing.Timer\nimport javax.swing.SwingUtilities\n\nclass ChaosGame : JPanel() {\n\n class ColoredPoint(x: Int, y: Int, val colorIndex: Int) : Point(x, y)\n\n val stack = Stack()\n val points: List\n val colors = listOf(Color.red, Color.green, Color.blue)\n val r = Random()\n\n init {\n val dim = Dimension(640, 640)\n preferredSize = dim\n background = Color.white\n val margin = 60\n val size = dim.width - 2 * margin\n points = listOf(\n Point(dim.width / 2, margin),\n Point(margin, size),\n Point(margin + size, size)\n )\n stack.push(ColoredPoint(-1, -1, 0))\n\n Timer(10) {\n if (stack.size < 50_000) {\n for (i in 0 until 1000) addPoint()\n repaint()\n }\n }.start()\n }\n\n private fun addPoint() {\n val colorIndex = r.nextInt(3)\n val p1 = stack.peek()\n val p2 = points[colorIndex]\n stack.add(halfwayPoint(p1, p2, colorIndex))\n }\n\n fun drawPoints(g: Graphics2D) {\n for (cp in stack) {\n g.color = colors[cp.colorIndex]\n g.fillOval(cp.x, cp.y, 1, 1)\n }\n }\n\n fun halfwayPoint(a: Point, b: Point, idx: Int) =\n ColoredPoint((a.x + b.x) / 2, (a.y + b.y) / 2, idx)\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n drawPoints(g)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with (f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Chaos Game\"\n isResizable = false\n add(ChaosGame(), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "Check Machin-like formulas", "language": "Kotlin", "task": "Machin-like formulas are useful for efficiently computing numerical approximations for \\pi\n\n\n;Task:\nVerify the following Machin-like formulas are correct by calculating the value of '''tan''' (''right hand side)'' for each equation using exact arithmetic and showing they equal '''1''':\n\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over3} \n: {\\pi\\over4} = 2 \\arctan{1\\over3} + \\arctan{1\\over7}\n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over239}\n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 2 \\arctan{3\\over79}\n: {\\pi\\over4} = 5 \\arctan{29\\over278} + 7 \\arctan{3\\over79}\n: {\\pi\\over4} = \\arctan{1\\over2} + \\arctan{1\\over5} + \\arctan{1\\over8} \n: {\\pi\\over4} = 4 \\arctan{1\\over5} - \\arctan{1\\over70} + \\arctan{1\\over99} \n: {\\pi\\over4} = 5 \\arctan{1\\over7} + 4 \\arctan{1\\over53} + 2 \\arctan{1\\over4443}\n: {\\pi\\over4} = 6 \\arctan{1\\over8} + 2 \\arctan{1\\over57} + \\arctan{1\\over239}\n: {\\pi\\over4} = 8 \\arctan{1\\over10} - \\arctan{1\\over239} - 4 \\arctan{1\\over515}\n: {\\pi\\over4} = 12 \\arctan{1\\over18} + 8 \\arctan{1\\over57} - 5 \\arctan{1\\over239}\n: {\\pi\\over4} = 16 \\arctan{1\\over21} + 3 \\arctan{1\\over239} + 4 \\arctan{3\\over1042}\n: {\\pi\\over4} = 22 \\arctan{1\\over28} + 2 \\arctan{1\\over443} - 5 \\arctan{1\\over1393} - 10 \\arctan{1\\over11018}\n: {\\pi\\over4} = 22 \\arctan{1\\over38} + 17 \\arctan{7\\over601} + 10 \\arctan{7\\over8149}\n: {\\pi\\over4} = 44 \\arctan{1\\over57} + 7 \\arctan{1\\over239} - 12 \\arctan{1\\over682} + 24 \\arctan{1\\over12943}\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12943}\n\nand confirm that the following formula is ''incorrect'' by showing '''tan''' (''right hand side)'' is ''not'' '''1''':\n\n: {\\pi\\over4} = 88 \\arctan{1\\over172} + 51 \\arctan{1\\over239} + 32 \\arctan{1\\over682} + 44 \\arctan{1\\over5357} + 68 \\arctan{1\\over12944}\n\nThese identities are useful in calculating the values:\n: \\tan(a + b) = {\\tan(a) + \\tan(b) \\over 1 - \\tan(a) \\tan(b)}\n\n: \\tan\\left(\\arctan{a \\over b}\\right) = {a \\over b}\n\n: \\tan(-a) = -\\tan(a)\n\nYou can store the equations in any convenient data structure, but for extra credit parse them from human-readable text input.\n\nNote: to formally prove the formula correct, it would have to be shown that ''{-3 pi \\over 4} < right hand side < {5 pi \\over 4}'' due to ''\\tan()'' periodicity.\n\n\n", "solution": "// version 1.1.3\n\nimport java.math.BigInteger\n\nval bigZero = BigInteger.ZERO\nval bigOne = BigInteger.ONE\n\nclass BigRational : Comparable {\n\n val num: BigInteger\n val denom: BigInteger\n \n constructor(n: BigInteger, d: BigInteger) {\n require(d != bigZero)\n var nn = n\n var dd = d\n if (nn == bigZero) {\n dd = bigOne\n }\n else if (dd < bigZero) {\n nn = -nn\n dd = -dd\n } \n val g = nn.gcd(dd)\n if (g > bigOne) {\n nn /= g\n dd /= g\n }\n num = nn\n denom = dd\n }\n \n constructor(n: Long, d: Long) : this(BigInteger.valueOf(n), BigInteger.valueOf(d))\n \n operator fun plus(other: BigRational) = \n BigRational(num * other.denom + denom * other.num, other.denom * denom)\n \n operator fun unaryMinus() = BigRational(-num, denom)\n \n operator fun minus(other: BigRational) = this + (-other)\n \n operator fun times(other: BigRational) = BigRational(this.num * other.num, this.denom * other.denom)\n \n fun inverse(): BigRational {\n require(num != bigZero)\n return BigRational(denom, num)\n }\n \n operator fun div(other: BigRational) = this * other.inverse()\n \n override fun compareTo(other: BigRational): Int {\n val diff = this - other\n return when {\n diff.num < bigZero -> -1\n diff.num > bigZero -> +1\n else -> 0\n } \n }\n \n override fun equals(other: Any?): Boolean {\n if (other == null || other !is BigRational) return false \n return this.compareTo(other) == 0\n }\n \n override fun toString() = if (denom == bigOne) \"$num\" else \"$num/$denom\"\n\n companion object {\n val ZERO = BigRational(bigZero, bigOne)\n val ONE = BigRational(bigOne, bigOne)\n }\n}\n\n/** represents a term of the form: c * atan(n / d) */\nclass Term(val c: Long, val n: Long, val d: Long) {\n \n override fun toString() = when {\n c == 1L -> \" + \"\n c == -1L -> \" - \"\n c < 0L -> \" - ${-c}*\"\n else -> \" + $c*\"\n } + \"atan($n/$d)\" \n}\n\nval one = BigRational.ONE\n\nfun tanSum(terms: List): BigRational {\n if (terms.size == 1) return tanEval(terms[0].c, BigRational(terms[0].n, terms[0].d))\n val half = terms.size / 2\n val a = tanSum(terms.take(half))\n val b = tanSum(terms.drop(half))\n return (a + b) / (one - (a * b))\n}\n\nfun tanEval(c: Long, f: BigRational): BigRational {\n if (c == 1L) return f\n if (c < 0L) return -tanEval(-c, f)\n val ca = c / 2\n val cb = c - ca\n val a = tanEval(ca, f)\n val b = tanEval(cb, f)\n return (a + b) / (one - (a * b))\n} \n \nfun main(args: Array) {\n val termsList = listOf(\n listOf(Term(1, 1, 2), Term(1, 1, 3)),\n listOf(Term(2, 1, 3), Term(1, 1, 7)),\n listOf(Term(4, 1, 5), Term(-1, 1, 239)),\n listOf(Term(5, 1, 7), Term(2, 3, 79)),\n listOf(Term(5, 29, 278), Term(7, 3, 79)),\n listOf(Term(1, 1, 2), Term(1, 1, 5), Term(1, 1, 8)),\n listOf(Term(4, 1, 5), Term(-1, 1, 70), Term(1, 1, 99)),\n listOf(Term(5, 1, 7), Term(4, 1, 53), Term(2, 1, 4443)),\n listOf(Term(6, 1, 8), Term(2, 1, 57), Term(1, 1, 239)),\n listOf(Term(8, 1, 10), Term(-1, 1, 239), Term(-4, 1, 515)),\n listOf(Term(12, 1, 18), Term(8, 1, 57), Term(-5, 1, 239)),\n listOf(Term(16, 1, 21), Term(3, 1, 239), Term(4, 3, 1042)),\n listOf(Term(22, 1, 28), Term(2, 1, 443), Term(-5, 1, 1393), Term(-10, 1, 11018)),\n listOf(Term(22, 1, 38), Term(17, 7, 601), Term(10, 7, 8149)),\n listOf(Term(44, 1, 57), Term(7, 1, 239), Term(-12, 1, 682), Term(24, 1, 12943)),\n listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12943)),\n listOf(Term(88, 1, 172), Term(51, 1, 239), Term(32, 1, 682), Term(44, 1, 5357), Term(68, 1, 12944))\n )\n\n for (terms in termsList) {\n val f = String.format(\"%-5s << 1 == tan(\", tanSum(terms) == one)\n print(f)\n print(terms[0].toString().drop(3))\n for (i in 1 until terms.size) print(terms[i])\n println(\")\") \n }\n}"} {"title": "Cheryl's birthday", "language": "Kotlin from Go", "task": "Albert and Bernard just became friends with Cheryl, and they want to know when her birthday is.\n\nCheryl gave them a list of ten possible dates:\n May 15, May 16, May 19\n June 17, June 18\n July 14, July 16\n August 14, August 15, August 17\n\nCheryl then tells Albert the ''month'' of birth, and Bernard the ''day'' (of the month) of birth.\n 1) Albert: I don't know when Cheryl's birthday is, but I know that Bernard does not know too.\n 2) Bernard: At first I don't know when Cheryl's birthday is, but I know now.\n 3) Albert: Then I also know when Cheryl's birthday is.\n\n\n;Task\nWrite a computer program to deduce, by successive elimination, Cheryl's birthday.\n\n\n;Related task:\n* [[Sum and Product Puzzle]]\n\n\n;References\n* Wikipedia article of the same name.\n* Tuple Relational Calculus\n\n", "solution": "// Version 1.2.71\n\nval months = listOf(\n \"January\", \"February\", \"March\", \"April\", \"May\", \"June\",\n \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"\n)\n\nclass Birthday(val month: Int, val day: Int) {\n public override fun toString() = \"${months[month - 1]} $day\"\n\n public fun monthUniqueIn(bds: List): Boolean {\n return bds.count { this.month == it.month } == 1 \n }\n\n public fun dayUniqueIn(bds: List): Boolean {\n return bds.count { this.day == it.day } == 1\n }\n\n public fun monthWithUniqueDayIn(bds: List): Boolean {\n return bds.any { (this.month == it.month) && it.dayUniqueIn(bds) }\n }\n}\n\nfun main(args: Array) {\n val choices = listOf(\n Birthday(5, 15), Birthday(5, 16), Birthday(5, 19), Birthday(6, 17), \n Birthday(6, 18), Birthday(7, 14), Birthday(7, 16), Birthday(8, 14),\n Birthday(8, 15), Birthday(8, 17)\n )\n\n // Albert knows the month but doesn't know the day.\n // So the month can't be unique within the choices.\n var filtered = choices.filterNot { it.monthUniqueIn(choices) }\n\n // Albert also knows that Bernard doesn't know the answer.\n // So the month can't have a unique day.\n filtered = filtered.filterNot { it.monthWithUniqueDayIn(filtered) }\n\n // Bernard now knows the answer.\n // So the day must be unique within the remaining choices.\n filtered = filtered.filter { it.dayUniqueIn(filtered) }\n\n // Albert now knows the answer too.\n // So the month must be unique within the remaining choices.\n filtered = filtered.filter { it.monthUniqueIn(filtered) }\n\n if (filtered.size == 1)\n println(\"Cheryl's birthday is ${filtered[0]}\")\n else\n println(\"Something went wrong!\")\n}"} {"title": "Chinese remainder theorem", "language": "Kotlin from C", "task": "Suppose n_1, n_2, \\ldots, n_k are positive [[integer]]s that are pairwise co-prime. \n\nThen, for any given sequence of integers a_1, a_2, \\dots, a_k, there exists an integer x solving the following system of simultaneous congruences:\n\n::: \\begin{align}\n x &\\equiv a_1 \\pmod{n_1} \\\\\n x &\\equiv a_2 \\pmod{n_2} \\\\\n &{}\\ \\ \\vdots \\\\\n x &\\equiv a_k \\pmod{n_k}\n\\end{align}\n\nFurthermore, all solutions x of this system are congruent modulo the product, N=n_1n_2\\ldots n_k.\n\n\n;Task:\nWrite a program to solve a system of linear congruences by applying the Chinese Remainder Theorem. \n\nIf the system of equations cannot be solved, your program must somehow indicate this. \n\n(It may throw an exception or return a special false value.) \n\nSince there are infinitely many solutions, the program should return the unique solution s where 0 \\leq s \\leq n_1n_2\\ldots n_k.\n\n\n''Show the functionality of this program'' by printing the result such that the n's are [3,5,7] and the a's are [2,3,2].\n\n\n'''Algorithm''': The following algorithm only applies if the n_i's are pairwise co-prime. \n\nSuppose, as above, that a solution is required for the system of congruences:\n\n::: x \\equiv a_i \\pmod{n_i} \\quad\\mathrm{for}\\; i = 1, \\ldots, k\n\nAgain, to begin, the product N = n_1n_2 \\ldots n_k is defined. \n\nThen a solution x can be found as follows:\n\nFor each i, the integers n_i and N/n_i are co-prime. \n\nUsing the Extended Euclidean algorithm, we can find integers r_i and s_i such that r_i n_i + s_i N/n_i = 1. \n\nThen, one solution to the system of simultaneous congruences is:\n\n::: x = \\sum_{i=1}^k a_i s_i N/n_i\n\nand the minimal solution,\n\n::: x \\pmod{N}.\n\n", "solution": "// version 1.1.2\n\n/* returns x where (a * x) % b == 1 */\nfun multInv(a: Int, b: Int): Int {\n if (b == 1) return 1\n var aa = a\n var bb = b\n var x0 = 0\n var x1 = 1\n while (aa > 1) {\n val q = aa / bb\n var t = bb\n bb = aa % bb\n aa = t\n t = x0\n x0 = x1 - q * x0\n x1 = t\n }\n if (x1 < 0) x1 += b\n return x1\n} \n\nfun chineseRemainder(n: IntArray, a: IntArray): Int {\n val prod = n.fold(1) { acc, i -> acc * i }\n var sum = 0\n for (i in 0 until n.size) {\n val p = prod / n[i]\n sum += a[i] * multInv(p, n[i]) * p\n }\n return sum % prod\n}\n\nfun main(args: Array) {\n val n = intArrayOf(3, 5, 7)\n val a = intArrayOf(2, 3, 2)\n println(chineseRemainder(n, a))\n}"} {"title": "Chinese zodiac", "language": "Kotlin", "task": "Determine the Chinese zodiac sign and related associations for a given year.\nTraditionally, the Chinese have counted years using two lists of labels, one of length 10 (the \"celestial stems\") and one of length 12 (the \"terrestrial branches\"). The labels do not really have any meaning outside their positions in the two lists; they're simply a traditional enumeration device, used much as Westerners use letters and numbers. They were historically used for months and days as well as years, and the stems are still sometimes used for school grades.\n\nYears cycle through both lists concurrently, so that both stem and branch advance each year; if we used Roman letters for the stems and numbers for the branches, consecutive years would be labeled A1, B2, C3, etc. Since the two lists are different lengths, they cycle back to their beginning at different points: after J10 we get A11, and then after B12 we get C1. The result is a repeating 60-year pattern within which each pair of names occurs only once.\n\nMapping the branches to twelve traditional animal deities results in the well-known \"Chinese zodiac\", assigning each year to a given animal. For example, Sunday, January 22, 2023 CE (in the common Gregorian calendar) began the lunisolar Year of the Rabbit.\n\nThe celestial stems do not have a one-to-one mapping like that of the branches to animals; however, the five pairs of consecutive stems are each associated with one of the five traditional Chinese elements (Wood, Fire, Earth, Metal, and Water). Further, one of the two years within each element is assigned to yin, the other to yang.\n\nThus, the Chinese year beginning in 2023 CE is also the yin year of Water. Since 12 is an even number, the association between animals and yin/yang doesn't change; consecutive Years of the Rabbit will cycle through the five elements, but will always be yin.\n\n;Task: Create a subroutine or program that will return or output the animal, yin/yang association, and element for the lunisolar year that begins in a given CE year.\n\nYou may optionally provide more information in the form of the year's numerical position within the 60-year cycle and/or its actual Chinese stem-branch name (in Han characters or Pinyin transliteration).\n\n;Requisite information:\n* The animal cycle runs in this order: Rat, Ox, Tiger, Rabbit, Dragon, Snake, Horse, Goat, Monkey, Rooster, Dog, Pig.\n* The element cycle runs in this order: Wood, Fire, Earth, Metal, Water. \n* Each element gets two consecutive years; a yang followed by a yin.\n* The current 60-year cycle began in 1984; any multiple of 60 years from that point may be used to reckon from.\n\nThus, year 1 of a cycle is the year of the Wood Rat (yang), year 2 the Wood Ox (yin), and year 3 the Fire Tiger (yang). The year 2023 - which, as already noted, is the year of the Water Rabbit (yin) - is the 40th year of the current cycle. \n\n;Information for optional task:\n* The ten celestial stems are '''Jia ''' ''jia'', '''Yi ''' ''yi'', '''Bing ''' ''bing'', '''Ding ''' ''ding'', '''Wu ''' ''wu'', '''Ji ''' ''ji'', '''Geng ''' ''geng'', '''Xin ''' ''xin'', '''Ren ''' ''ren'', and '''Gui ''' ''gui''. With the ASCII version of Pinyin tones, the names are written \"jia3\", \"yi3\", \"bing3\", \"ding1\", \"wu4\", \"ji3\", \"geng1\", \"xin1\", \"ren2\", and \"gui3\".\n* The twelve terrestrial branches are '''Zi ''' ''zi'', '''Chou ''' ''chou'', '''Yin ''' ''yin'', '''Mao ''' ''mao'', '''Chen ''' ''chen'', '''Si ''' ''si'', '''Wu ''' ''wu'', '''Wei ''' ''wei'', '''Shen ''' ''shen'', '''You ''' ''you'', '''Xu ''' ''xu'', '''Hai ''' ''hai''. In ASCII Pinyin, those are \"zi3\", \"chou3\", \"yin2\", \"mao3\", \"chen2\", \"si4\", \"wu3\", \"wei4\", \"shen1\", \"you3\", \"xu1\", and \"hai4\".\n\nTherefore 1984 was '''Jia Zi ''' (''jia-zi'', or jia3-zi3). 2023 is '''Gui Mao ''' (''gui-mao'' or gui3-mao3).\n", "solution": "// version 1.1.2\n\nclass ChineseZodiac(val year: Int) {\n val stem : Char\n val branch : Char\n val sName : String\n val bName : String\n val element: String\n val animal : String\n val aspect : String\n val cycle : Int\n \n private companion object {\n val animals = listOf(\"Rat\", \"Ox\", \"Tiger\", \"Rabbit\", \"Dragon\", \"Snake\",\n \"Horse\", \"Goat\", \"Monkey\", \"Rooster\", \"Dog\", \"Pig\")\n val aspects = listOf(\"Yang\",\"Yin\")\n val elements = listOf(\"Wood\", \"Fire\", \"Earth\", \"Metal\", \"Water\")\n val stems = listOf('\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678')\n val branches = listOf('\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149', '\u620c', '\u4ea5')\n val sNames = listOf(\"ji\u0103\", \"y\u012d\", \"b\u012dng\", \"d\u012bng\", \"w\u00f9\", \"j\u012d\", \"g\u0113ng\", \"x\u012bn\", \"r\u00e9n\", \"g\u016di\")\n val bNames = listOf(\"z\u012d\", \"ch\u014fu\", \"y\u00edn\", \"m\u0103o\", \"ch\u00e9n\", \"s\u00ec\", \"w\u016d\", \"w\u00e8i\", \"sh\u0113n\", \"y\u014fu\", \"x\u016b\", \"h\u00e0i\")\n val fmt = \"%d %c%c %-9s %-7s %-7s %-6s %02d/60\"\n } \n\n init {\n val y = year - 4\n val s = y % 10\n val b = y % 12\n stem = stems[s]\n branch = branches[b]\n sName = sNames[s]\n bName = bNames[b]\n element = elements[s / 2]\n animal = animals[b]\n aspect = aspects[s % 2]\n cycle = y % 60 + 1 \n }\n\n override fun toString() = \n fmt.format(year, stem, branch, sName + \"-\" + bName, element, animal, aspect, cycle)\n}\n\nfun main(args: Array) {\n val years = intArrayOf(1935, 1938, 1968, 1972, 1976, 1984, 2017)\n println(\"Year Chinese Pinyin Element Animal Aspect Cycle\")\n println(\"---- ------- --------- ------- ------- ------ -----\") \n for (year in years) println(ChineseZodiac(year))\n}"} {"title": "Circles of given radius through two points", "language": "Kotlin", "task": "2 circles with a given radius through 2 points in 2D space.\n\nGiven two points on a plane and a radius, usually two circles of given radius can be drawn through the points. \n;Exceptions:\n# r==0.0 should be treated as never describing circles (except in the case where the points are coincident).\n# If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless r==0.0 as well which then collapses the circles to a point.\n# If the points form a diameter then return two identical circles ''or'' return a single circle, according to which is the most natural mechanism for the implementation language.\n# If the points are too far apart then no circles can be drawn.\n\n\n;Task detail:\n* Write a function/subroutine/method/... that takes two points and a radius and returns the two circles through those points, ''or some indication of special cases where two, possibly equal, circles cannot be returned''.\n* Show here the output for the following inputs:\n\n p1 p2 r\n0.1234, 0.9876 0.8765, 0.2345 2.0\n0.0000, 2.0000 0.0000, 0.0000 1.0\n0.1234, 0.9876 0.1234, 0.9876 2.0\n0.1234, 0.9876 0.8765, 0.2345 0.5\n0.1234, 0.9876 0.1234, 0.9876 0.0\n\n\n\n;Related task:\n* [[Total circles area]].\n\n\n;See also:\n* Finding the Center of a Circle from 2 Points and Radius from Math forum @ Drexel\n\n", "solution": "// version 1.1.51\n\ntypealias IAE = IllegalArgumentException\n\nclass Point(val x: Double, val y: Double) {\n fun distanceFrom(other: Point): Double {\n val dx = x - other.x\n val dy = y - other.y\n return Math.sqrt(dx * dx + dy * dy )\n }\n\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is Point) return false\n return (x == other.x && y == other.y)\n }\n\n override fun toString() = \"(%.4f, %.4f)\".format(x, y)\n}\n\nfun findCircles(p1: Point, p2: Point, r: Double): Pair {\n if (r < 0.0) throw IAE(\"the radius can't be negative\")\n if (r == 0.0 && p1 != p2) throw IAE(\"no circles can ever be drawn\")\n if (r == 0.0) return p1 to p1\n if (p1 == p2) throw IAE(\"an infinite number of circles can be drawn\")\n val distance = p1.distanceFrom(p2)\n val diameter = 2.0 * r\n if (distance > diameter) throw IAE(\"the points are too far apart to draw a circle\")\n val center = Point((p1.x + p2.x) / 2.0, (p1.y + p2.y) / 2.0)\n if (distance == diameter) return center to center\n val mirrorDistance = Math.sqrt(r * r - distance * distance / 4.0)\n val dx = (p2.x - p1.x) * mirrorDistance / distance\n val dy = (p2.y - p1.y) * mirrorDistance / distance\n return Point(center.x - dy, center.y + dx) to\n Point(center.x + dy, center.y - dx)\n}\n\nfun main(args: Array) {\n val p = arrayOf(\n Point(0.1234, 0.9876),\n Point(0.8765, 0.2345),\n Point(0.0000, 2.0000),\n Point(0.0000, 0.0000)\n )\n val points = arrayOf(\n p[0] to p[1], p[2] to p[3], p[0] to p[0], p[0] to p[1], p[0] to p[0]\n )\n val radii = doubleArrayOf(2.0, 1.0, 2.0, 0.5, 0.0)\n for (i in 0..4) {\n try {\n val (p1, p2) = points[i] \n val r = radii[i]\n println(\"For points $p1 and $p2 with radius $r\")\n val (c1, c2) = findCircles(p1, p2, r)\n if (c1 == c2)\n println(\"there is just one circle with center at $c1\")\n else\n println(\"there are two circles with centers at $c1 and $c2\")\n }\n catch(ex: IllegalArgumentException) {\n println(ex.message)\n }\n println()\n }\n}"} {"title": "Cistercian numerals", "language": "Kotlin from C++", "task": "Cistercian numerals were used across Europe by Cistercian monks during the Late Medieval Period as an alternative to Roman numerals. They were used to represent base 10 integers from '''0''' to '''9999'''.\n\n;How they work\nAll Cistercian numerals begin with a vertical line segment, which by itself represents the number '''0'''. Then, glyphs representing the digits '''1''' through '''9''' are optionally added to the four quadrants surrounding the vertical line segment. These glyphs are drawn with vertical and horizontal symmetry about the initial line segment. Each quadrant corresponds to a digit place in the number:\n\n:* The '''upper-right''' quadrant represents the '''ones''' place.\n:* The '''upper-left''' quadrant represents the '''tens''' place.\n:* The '''lower-right''' quadrant represents the '''hundreds''' place.\n:* The '''lower-left''' quadrant represents the '''thousands''' place.\n\nPlease consult the following image for examples of Cistercian numerals showing each glyph: [https://upload.wikimedia.org/wikipedia/commons/6/67/Cistercian_digits_%28vertical%29.svg]\n\n;Task\n\n:* Write a function/procedure/routine to display any given Cistercian numeral. This could be done by drawing to the display, creating an image, or even as text (as long as it is a reasonable facsimile).\n\n:* Use the routine to show the following Cistercian numerals:\n\n::* 0\n::* 1\n::* 20\n::* 300\n::* 4000\n::* 5555\n::* 6789\n::* And a number of your choice!\n\n;Notes\nDue to the inability to upload images to Rosetta Code as of this task's creation, showing output here on this page is not required. However, it is welcomed -- especially for text output.\n\n;See also\n\n:* '''Numberphile - The Forgotten Number System'''\n:* '''dcode.fr - Online Cistercian numeral converter'''\n", "solution": "import java.io.StringWriter\n\nclass Cistercian() {\n constructor(number: Int) : this() {\n draw(number)\n }\n\n private val size = 15\n private var canvas = Array(size) { Array(size) { ' ' } }\n\n init {\n initN()\n }\n\n private fun initN() {\n for (row in canvas) {\n row.fill(' ')\n row[5] = 'x'\n }\n }\n\n private fun horizontal(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r][c] = 'x'\n }\n }\n\n private fun vertical(r1: Int, r2: Int, c: Int) {\n for (r in r1..r2) {\n canvas[r][c] = 'x'\n }\n }\n\n private fun diagd(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r + c - c1][c] = 'x'\n }\n }\n\n private fun diagu(c1: Int, c2: Int, r: Int) {\n for (c in c1..c2) {\n canvas[r - c + c1][c] = 'x'\n }\n }\n\n private fun drawPart(v: Int) {\n when (v) {\n 1 -> {\n horizontal(6, 10, 0)\n }\n 2 -> {\n horizontal(6, 10, 4)\n }\n 3 -> {\n diagd(6, 10, 0)\n }\n 4 -> {\n diagu(6, 10, 4)\n }\n 5 -> {\n drawPart(1)\n drawPart(4)\n }\n 6 -> {\n vertical(0, 4, 10)\n }\n 7 -> {\n drawPart(1)\n drawPart(6)\n }\n 8 -> {\n drawPart(2)\n drawPart(6)\n }\n 9 -> {\n drawPart(1)\n drawPart(8)\n }\n\n 10 -> {\n horizontal(0, 4, 0)\n }\n 20 -> {\n horizontal(0, 4, 4)\n }\n 30 -> {\n diagu(0, 4, 4)\n }\n 40 -> {\n diagd(0, 4, 0)\n }\n 50 -> {\n drawPart(10)\n drawPart(40)\n }\n 60 -> {\n vertical(0, 4, 0)\n }\n 70 -> {\n drawPart(10)\n drawPart(60)\n }\n 80 -> {\n drawPart(20)\n drawPart(60)\n }\n 90 -> {\n drawPart(10)\n drawPart(80)\n }\n\n 100 -> {\n horizontal(6, 10, 14)\n }\n 200 -> {\n horizontal(6, 10, 10)\n }\n 300 -> {\n diagu(6, 10, 14)\n }\n 400 -> {\n diagd(6, 10, 10)\n }\n 500 -> {\n drawPart(100)\n drawPart(400)\n }\n 600 -> {\n vertical(10, 14, 10)\n }\n 700 -> {\n drawPart(100)\n drawPart(600)\n }\n 800 -> {\n drawPart(200)\n drawPart(600)\n }\n 900 -> {\n drawPart(100)\n drawPart(800)\n }\n\n 1000 -> {\n horizontal(0, 4, 14)\n }\n 2000 -> {\n horizontal(0, 4, 10)\n }\n 3000 -> {\n diagd(0, 4, 10)\n }\n 4000 -> {\n diagu(0, 4, 14)\n }\n 5000 -> {\n drawPart(1000)\n drawPart(4000)\n }\n 6000 -> {\n vertical(10, 14, 0)\n }\n 7000 -> {\n drawPart(1000)\n drawPart(6000)\n }\n 8000 -> {\n drawPart(2000)\n drawPart(6000)\n }\n 9000 -> {\n drawPart(1000)\n drawPart(8000)\n }\n }\n }\n\n private fun draw(v: Int) {\n var v2 = v\n\n val thousands = v2 / 1000\n v2 %= 1000\n\n val hundreds = v2 / 100\n v2 %= 100\n\n val tens = v2 / 10\n val ones = v % 10\n\n if (thousands > 0) {\n drawPart(1000 * thousands)\n }\n if (hundreds > 0) {\n drawPart(100 * hundreds)\n }\n if (tens > 0) {\n drawPart(10 * tens)\n }\n if (ones > 0) {\n drawPart(ones)\n }\n }\n\n override fun toString(): String {\n val sw = StringWriter()\n for (row in canvas) {\n for (cell in row) {\n sw.append(cell)\n }\n sw.appendLine()\n }\n return sw.toString()\n }\n}\n\nfun main() {\n for (number in arrayOf(0, 1, 20, 300, 4000, 5555, 6789, 9999)) {\n println(\"$number:\")\n\n val c = Cistercian(number)\n println(c)\n }\n\n}"} {"title": "Closures/Value capture", "language": "Kotlin", "task": "Create a list of ten functions, in the simplest manner possible (anonymous functions are encouraged), such that the function at index '' i '' (you may choose to start '' i '' from either '''0''' or '''1'''), when run, should return the square of the index, that is, '' i '' 2. \n\nDisplay the result of running any but the last function, to demonstrate that the function indeed remembers its value.\n\n\n;Goal:\nDemonstrate how to create a series of independent closures based on the same template but maintain separate copies of the variable closed over. \n\nIn imperative languages, one would generally use a loop with a mutable counter variable. \n\nFor each function to maintain the correct number, it has to capture the ''value'' of the variable at the time it was created, rather than just a reference to the variable, which would have a different value by the time the function was run.\n\nSee also: [[Multiple distinct objects]]\n", "solution": "// version 1.0.6\n\nfun main(args: Array) {\n // create an array of 10 anonymous functions which return the square of their index\n val funcs = Array(10){ fun(): Int = it * it }\n // call all but the last\n (0 .. 8).forEach { println(funcs[it]()) } \n}"} {"title": "Colour bars/Display", "language": "Kotlin from Java", "task": "Display a series of vertical color bars across the width of the display. \n\nThe color bars should either use:\n:::* the system palette, or \n:::* the sequence of colors: \n::::::* black\n::::::* red\n::::::* green\n::::::* blue\n::::::* magenta\n::::::* cyan\n::::::* yellow\n::::::* white\n\n", "solution": "import java.awt.Color\nimport java.awt.Graphics\nimport javax.swing.JFrame\n\nclass ColorFrame(width: Int, height: Int): JFrame() {\n init {\n defaultCloseOperation = EXIT_ON_CLOSE\n setSize(width, height)\n isVisible = true\n }\n\n override fun paint(g: Graphics) {\n val colors = listOf(Color.black, Color.red, Color.green, Color.blue,\n\t\t Color.pink, Color.cyan, Color.yellow, Color.white)\n val size = colors.size\n for (i in 0 until size) {\n g.color = colors[i]\n g.fillRect(width / size * i, 0, width / size, height)\n }\n }\n}\n\nfun main(args: Array) {\n ColorFrame(400, 400)\n}"} {"title": "Comma quibbling", "language": "Kotlin", "task": "Comma quibbling is a task originally set by Eric Lippert in his blog.\n\n\n;Task:\n\nWrite a function to generate a string output which is the concatenation of input words from a list/sequence where:\n# An input of no words produces the output string of just the two brace characters \"{}\".\n# An input of just one word, e.g. [\"ABC\"], produces the output string of the word inside the two braces, e.g. \"{ABC}\".\n# An input of two words, e.g. [\"ABC\", \"DEF\"], produces the output string of the two words inside the two braces with the words separated by the string \" and \", e.g. \"{ABC and DEF}\".\n# An input of three or more words, e.g. [\"ABC\", \"DEF\", \"G\", \"H\"], produces the output string of all but the last word separated by \", \" with the last word separated by \" and \" and all within braces; e.g. \"{ABC, DEF, G and H}\".\n\n\nTest your function with the following series of inputs showing your output here on this page:\n* [] # (No input words).\n* [\"ABC\"]\n* [\"ABC\", \"DEF\"]\n* [\"ABC\", \"DEF\", \"G\", \"H\"]\n\n\nNote: Assume words are non-empty strings of uppercase characters for this task.\n\n", "solution": "// version 1.0.6\n\nfun commaQuibble(s: String): String {\n val t = s.trim('[', ']').replace(\" \", \"\").replace(\"\\\"\", \"\") \n val words = t.split(',')\n val sb = StringBuilder(\"{\")\n for (i in 0 until words.size) {\n sb.append(when (i) {\n 0 -> \"\"\n words.lastIndex -> \" and \"\n else -> \", \" \n })\n sb.append(words[i])\n }\n return sb.append(\"}\").toString()\n}\n\nfun main(args: Array) {\n val inputs = arrayOf(\n \"\"\"[]\"\"\",\n \"\"\"[\"ABC\"]\"\"\",\n \"\"\"[\"ABC\", \"DEF\"]\"\"\",\n \"\"\"[\"ABC\", \"DEF\", \"G\", \"H\"]\"\"\"\n )\n for (input in inputs) println(\"${input.padEnd(24)} -> ${commaQuibble(input)}\")\n}"} {"title": "Command-line arguments", "language": "Kotlin from Java", "task": "{{selection|Short Circuit|Console Program Basics}} Retrieve the list of command-line arguments given to the program. For programs that only print the arguments when run directly, see [[Scripted main]].\nSee also [[Program name]].\n\nFor parsing command line arguments intelligently, see [[Parsing command-line arguments]].\n\nExample command line:\n\n myprogram -c \"alpha beta\" -h \"gamma\"\n\n", "solution": "fun main(args: Array) {\n println(\"There are \" + args.size + \" arguments given.\")\n args.forEachIndexed { i, a -> println(\"The argument #${i+1} is $a and is at index $i\") }\n}"} {"title": "Compare a list of strings", "language": "Kotlin", "task": "Given a list of arbitrarily many strings, show how to:\n\n* test if they are all lexically '''equal'''\n* test if every string is lexically '''less than''' the one after it ''(i.e. whether the list is in strict ascending order)''\n\n\nEach of those two tests should result in a single true or false value, which could be used as the condition of an if statement or similar. \n\nIf the input list has less than two elements, the tests should always return true.\n\nThere is ''no'' need to provide a complete program and output.\n \nAssume that the strings are already stored in an array/list/sequence/tuple variable (whatever is most idiomatic) with the name strings, and just show the expressions for performing those two tests on it (plus of course any includes and custom functions etc. that it needs), with as little distractions as possible.\n\nTry to write your solution in a way that does not modify the original list, but if it does then please add a note to make that clear to readers.\n\nIf you need further guidance/clarification, see [[#Perl]] and [[#Python]] for solutions that use implicit short-circuiting loops, and [[#Raku]] for a solution that gets away with simply using a built-in language feature. \n\n", "solution": "// version 1.0.6\n\nfun areEqual(strings: Array): Boolean {\n if (strings.size < 2) return true\n return (1 until strings.size).all { strings[it] == strings[it - 1] }\n}\n\nfun areAscending(strings: Array): Boolean {\n if (strings.size < 2) return true\n return (1 until strings.size).all { strings[it] > strings[it - 1] }\n}\n\n// The strings are given in the command line arguments\n\nfun main(args: Array) {\n println(\"The strings are : ${args.joinToString()}\")\n if (areEqual(args)) println(\"They are all equal\")\n else if (areAscending(args)) println(\"They are in strictly ascending order\")\n else println(\"They are neither equal nor in ascending order\")\n}"} {"title": "Compile-time calculation", "language": "Kotlin", "task": "Some programming languages allow calculation of values at compile time. \n\n\n;Task:\nCalculate 10! (ten factorial) at compile time. \n\nPrint the result when the program is run.\n\nDiscuss what limitations apply to compile-time calculations in your language.\n\n", "solution": "// version 1.0.6\nconst val TEN_FACTORIAL = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 \n\nfun main(args: Array) {\n println(\"10! = $TEN_FACTORIAL\")\n}"} {"title": "Compiler/lexical analyzer", "language": "kotlin from Java", "task": "The C and Python versions can be considered reference implementations.\n\n\n;Related Tasks\n* Syntax Analyzer task\n* Code Generator task\n* Virtual Machine Interpreter task\n* AST Interpreter task\n\n\n", "solution": "// Input: command line argument of file to process or console input. A two or\n// three character console input of digits followed by a new line will be\n// checked for an integer between zero and twenty-five to select a fixed test\n// case to run. Any other console input will be parsed.\n\n// Code based on the Java version found here:\n// https://rosettacode.org/mw/index.php?title=Compiler/lexical_analyzer&action=edit§ion=22\n\n// Class to halt the parsing with an exception.\nclass ParsingFailed(message: String): Exception(message)\n\n// Enumerate class of tokens supported by this scanner.\nenum class TokenType {\n Tk_End_of_input, Op_multiply, Op_divide, Op_mod, Op_add, Op_subtract,\n Op_negate, Op_not, Op_less, Op_lessequal, Op_greater, Op_greaterequal,\n Op_equal, Op_notequal, Op_assign, Op_and, Op_or, Kw_if,\n Kw_else, Kw_while, Kw_print, Kw_putc, Sy_LeftParen, Sy_RightParen,\n Sy_LeftBrace, Sy_RightBrace, Sy_Semicolon, Sy_Comma, Tk_Identifier,\n Tk_Integer, Tk_String;\n\n override fun toString() =\n listOf(\"End_of_input\", \"Op_multiply\", \"Op_divide\", \"Op_mod\", \"Op_add\",\n \"Op_subtract\", \"Op_negate\", \"Op_not\", \"Op_less\", \"Op_lessequal\",\n \"Op_greater\", \"Op_greaterequal\", \"Op_equal\", \"Op_notequal\",\n \"Op_assign\", \"Op_and\", \"Op_or\", \"Keyword_if\", \"Keyword_else\",\n \"Keyword_while\", \"Keyword_print\", \"Keyword_putc\", \"LeftParen\",\n \"RightParen\", \"LeftBrace\", \"RightBrace\", \"Semicolon\", \"Comma\",\n \"Identifier\", \"Integer\", \"String\")[this.ordinal]\n} // TokenType\n\n// Data class of tokens returned by the scanner.\ndata class Token(val token: TokenType, val value: String, val line: Int,\n val pos: Int) {\n\n // Overridden method to display the token.\n override fun toString() =\n \"%5d %5d %-15s %s\".format(line, pos, this.token,\n when (this.token) {\n TokenType.Tk_Integer, TokenType.Tk_Identifier ->\n \" %s\".format(this.value)\n TokenType.Tk_String ->\n this.value.toList().joinToString(\"\", \" \\\"\", \"\\\"\") {\n when (it) {\n '\\t' ->\n \"\\\\t\"\n '\\n' ->\n \"\\\\n\"\n '\\u000b' ->\n \"\\\\v\"\n '\\u000c' ->\n \"\\\\f\"\n '\\r' ->\n \"\\\\r\"\n '\"' ->\n \"\\\\\\\"\"\n '\\\\' ->\n \"\\\\\"\n in ' '..'~' ->\n \"$it\"\n else ->\n \"\\\\u%04x\".format(it.code) } }\n else ->\n \"\" } )\n} // Token\n\n// Function to display an error message and halt the scanner.\nfun error(line: Int, pos: Int, msg: String): Nothing =\n throw ParsingFailed(\"(%d, %d) %s\\n\".format(line, pos, msg))\n\n// Class to process the source into tokens with properties of the\n// source string, the line number, the column position, the index\n// within the source string, the current character being processed,\n// and map of the keyword strings to the corresponding token type.\nclass Lexer(private val s: String) {\n private var line = 1\n private var pos = 1\n private var position = 0\n private var chr =\n if (s.isEmpty())\n ' '\n else\n s[0]\n private val keywords = mapOf(\n \"if\" to TokenType.Kw_if,\n \"else\" to TokenType.Kw_else,\n \"print\" to TokenType.Kw_print,\n \"putc\" to TokenType.Kw_putc,\n \"while\" to TokenType.Kw_while)\n\n // Method to retrive the next character from the source. Use null after\n // the end of our source.\n private fun getNextChar() =\n if (++this.position >= this.s.length) {\n this.pos++\n this.chr = '\\u0000'\n this.chr\n } else {\n this.pos++\n this.chr = this.s[this.position]\n when (this.chr) {\n '\\n' -> {\n this.line++\n this.pos = 0\n } // line\n '\\t' ->\n while (this.pos%8 != 1)\n this.pos++\n } // when\n this.chr\n } // if\n\n // Method to return the division token, skip the comment, or handle the\n // error.\n private fun div_or_comment(line: Int, pos: Int): Token =\n if (getNextChar() != '*')\n Token(TokenType.Op_divide, \"\", line, pos);\n else {\n getNextChar() // Skip comment start\n outer@\n while (true)\n when (this.chr) {\n '\\u0000' ->\n error(line, pos, \"Lexer: EOF in comment\");\n '*' ->\n if (getNextChar() == '/') {\n getNextChar() // Skip comment end\n break@outer\n } // if\n else ->\n getNextChar()\n } // when\n getToken()\n } // if\n\n // Method to verify a character literal. Return the token or handle the\n // error.\n private fun char_lit(line: Int, pos: Int): Token {\n var c = getNextChar() // skip opening quote\n when (c) {\n '\\'' ->\n error(line, pos, \"Lexer: Empty character constant\");\n '\\\\' -> \n c = when (getNextChar()) {\n 'n' ->\n 10.toChar()\n '\\\\' ->\n '\\\\'\n '\\'' ->\n '\\''\n else ->\n error(line, pos, \"Lexer: Unknown escape sequence '\\\\%c'\".\n format(this.chr)) }\n } // when\n if (getNextChar() != '\\'')\n error(line, pos, \"Lexer: Multi-character constant\")\n getNextChar() // Skip closing quote\n return Token(TokenType.Tk_Integer, c.code.toString(), line, pos)\n } // char_lit\n\n // Method to check next character to see whether it belongs to the token\n // we might be in the middle of. Return the correct token or handle the\n // error.\n private fun follow(expect: Char, ifyes: TokenType, ifno: TokenType,\n line: Int, pos: Int): Token =\n when {\n getNextChar() == expect -> {\n getNextChar()\n Token(ifyes, \"\", line, pos)\n } // matches\n ifno == TokenType.Tk_End_of_input ->\n error(line, pos, \n \"Lexer: %c expected: (%d) '%c'\".format(expect,\n this.chr.code, this.chr))\n else ->\n Token(ifno, \"\", line, pos)\n } // when\n\n // Method to verify a character string. Return the token or handle the\n // error.\n private fun string_lit(start: Char, line: Int, pos: Int): Token {\n var result = \"\"\n while (getNextChar() != start)\n when (this.chr) {\n '\\u0000' ->\n error(line, pos, \"Lexer: EOF while scanning string literal\")\n '\\n' ->\n error(line, pos, \"Lexer: EOL while scanning string literal\")\n '\\\\' ->\n when (getNextChar()) {\n '\\\\' ->\n result += '\\\\'\n 'n' ->\n result += '\\n'\n '\"' ->\n result += '\"'\n else ->\n error(line, pos, \"Lexer: Escape sequence unknown '\\\\%c'\".\n format(this.chr))\n } // when\n else ->\n result += this.chr\n } // when\n getNextChar() // Toss closing quote\n return Token(TokenType.Tk_String, result, line, pos)\n } // string_lit\n\n // Method to retrive an identifier or integer. Return the keyword\n // token, if the string matches one. Return the integer token,\n // if the string is all digits. Return the identifer token, if the\n // string is valid. Otherwise, handle the error.\n private fun identifier_or_integer(line: Int, pos: Int): Token {\n var is_number = true\n var text = \"\"\n while (this.chr in listOf('_')+('0'..'9')+('a'..'z')+('A'..'Z')) {\n text += this.chr\n is_number = is_number && this.chr in '0'..'9'\n getNextChar()\n } // while\n if (text.isEmpty())\n error(line, pos, \"Lexer: Unrecognized character: (%d) %c\".\n format(this.chr.code, this.chr))\n return when {\n text[0] in '0'..'9' ->\n if (!is_number)\n error(line, pos, \"Lexer: Invalid number: %s\".\n format(text))\n else {\n val max = Int.MAX_VALUE.toString()\n if (text.length > max.length || (text.length == max.length &&\n max < text))\n error(line, pos,\n \"Lexer: Number exceeds maximum value %s\".\n format(text))\n Token(TokenType.Tk_Integer, text, line, pos)\n } // if\n this.keywords.containsKey(text) ->\n Token(this.keywords[text]!!, \"\", line, pos)\n else ->\n Token(TokenType.Tk_Identifier, text, line, pos) }\n } // identifier_or_integer\n\n // Method to skip whitespace both C's and Unicode ones and retrive the next\n // token.\n private fun getToken(): Token {\n while (this.chr in listOf('\\t', '\\n', '\\u000b', '\\u000c', '\\r', ' ') ||\n this.chr.isWhitespace())\n getNextChar()\n val line = this.line\n val pos = this.pos\n return when (this.chr) {\n '\\u0000' ->\n Token(TokenType.Tk_End_of_input, \"\", line, pos)\n '/' ->\n div_or_comment(line, pos)\n '\\'' ->\n char_lit(line, pos)\n '<' ->\n follow('=', TokenType.Op_lessequal, TokenType.Op_less, line, pos)\n '>' ->\n follow('=', TokenType.Op_greaterequal, TokenType.Op_greater, line, pos)\n '=' ->\n follow('=', TokenType.Op_equal, TokenType.Op_assign, line, pos)\n '!' ->\n follow('=', TokenType.Op_notequal, TokenType.Op_not, line, pos)\n '&' ->\n follow('&', TokenType.Op_and, TokenType.Tk_End_of_input, line, pos)\n '|' ->\n follow('|', TokenType.Op_or, TokenType.Tk_End_of_input, line, pos)\n '\"' ->\n string_lit(this.chr, line, pos)\n '{' -> {\n getNextChar()\n Token(TokenType.Sy_LeftBrace, \"\", line, pos)\n } // open brace\n '}' -> {\n getNextChar()\n Token(TokenType.Sy_RightBrace, \"\", line, pos)\n } // close brace\n '(' -> {\n getNextChar()\n Token(TokenType.Sy_LeftParen, \"\", line, pos)\n } // open paren\n ')' -> {\n getNextChar()\n Token(TokenType.Sy_RightParen, \"\", line, pos)\n } // close paren\n '+' -> {\n getNextChar()\n Token(TokenType.Op_add, \"\", line, pos)\n } // plus\n '-' -> {\n getNextChar()\n Token(TokenType.Op_subtract, \"\", line, pos)\n } // dash\n '*' -> {\n getNextChar()\n Token(TokenType.Op_multiply, \"\", line, pos)\n } // asterisk\n '%' -> {\n getNextChar()\n Token(TokenType.Op_mod, \"\", line, pos)\n } // percent\n ';' -> {\n getNextChar()\n Token(TokenType.Sy_Semicolon, \"\", line, pos)\n } // semicolon\n ',' -> {\n getNextChar()\n Token(TokenType.Sy_Comma, \"\", line, pos)\n } // comma\n else ->\n identifier_or_integer(line, pos) }\n } // getToken\n\n // Method to parse and display tokens.\n fun printTokens() {\n do {\n val t: Token = getToken()\n println(t)\n } while (t.token != TokenType.Tk_End_of_input)\n } // printTokens\n} // Lexer\n\n\n// Function to test all good tests from the website and produce all of the\n// error messages this program supports.\nfun tests(number: Int) {\n\n // Function to generate test case 0 source: Hello World/Text.\n fun hello() {\n Lexer(\n\"\"\"/*\nHello world\n*/\nprint(\"Hello, World!\\n\");\n\"\"\").printTokens()\n } // hello\n\n // Function to generate test case 1 source: Phoenix Number.\n fun phoenix() {\n Lexer(\n\"\"\"/*\nShow Ident and Integers\n*/\nphoenix_number = 142857;\nprint(phoenix_number, \"\\n\");\"\"\").printTokens()\n } // phoenix\n\n // Function to generate test case 2 source: All Symbols.\n fun symbols() {\n Lexer(\n\"\"\"/*\n All lexical tokens - not syntactically correct, but that will\n have to wait until syntax analysis\n */\n/* Print */ print /* Sub */ -\n/* Putc */ putc /* Lss */ <\n/* If */ if /* Gtr */ >\n/* Else */ else /* Leq */ <=\n/* While */ while /* Geq */ >=\n/* Lbrace */ { /* Eq */ ==\n/* Rbrace */ } /* Neq */ !=\n/* Lparen */ ( /* And */ &&\n/* Rparen */ ) /* Or */ ||\n/* Uminus */ - /* Semi */ ;\n/* Not */ ! /* Comma */ ,\n/* Mul */ * /* Assign */ =\n/* Div */ / /* Integer */ 42\n/* Mod */ % /* String */ \"String literal\"\n/* Add */ + /* Ident */ variable_name\n/* character literal */ '\\n'\n/* character literal */ '\\\\'\n/* character literal */ ' '\"\"\").printTokens()\n } // symbols\n\n // Function to generate test case 3 source: Test Case 4.\n fun four() {\n Lexer(\n\"\"\"/*** test printing, embedded \\n and comments with lots of '*' ***/\nprint(42);\nprint(\"\\nHello World\\nGood Bye\\nok\\n\");\nprint(\"Print a slash n - \\\\n.\\n\");\"\"\").printTokens()\n } // four\n\n // Function to generate test case 4 source: Count.\n fun count() {\n Lexer(\n\"\"\"count = 1;\nwhile (count < 10) {\n print(\"count is: \", count, \"\\n\");\n count = count + 1;\n}\"\"\").printTokens()\n } // count\n\n // Function to generate test case 5 source: 100 Doors.\n fun doors() {\n Lexer(\n\"\"\"/* 100 Doors */\ni = 1;\nwhile (i * i <= 100) {\n print(\"door \", i * i, \" is open\\n\");\n i = i + 1;\n}\"\"\").printTokens()\n } // doors\n\n // Function to generate test case 6 source: Negative Tests.\n fun negative() {\n Lexer(\n\"\"\"a = (-1 * ((-1 * (5 * 15)) / 10));\nprint(a, \"\\n\");\nb = -a;\nprint(b, \"\\n\");\nprint(-b, \"\\n\");\nprint(-(1), \"\\n\");\"\"\").printTokens()\n } // negative\n\n // Function to generate test case 7 source: Deep.\n fun deep() {\n Lexer(\n\"\"\"print(---------------------------------+++5, \"\\n\");\nprint(((((((((3 + 2) * ((((((2))))))))))))), \"\\n\");\n\u00a0\nif (1) { if (1) { if (1) { if (1) { if (1) { print(15, \"\\n\"); } } } } }\"\"\").printTokens()\n } // deep\n\n // Function to generate test case 8 source: Greatest Common Divisor.\n fun gcd() {\n Lexer(\n\"\"\"/* Compute the gcd of 1071, 1029: 21 */\n\u00a0\na = 1071;\nb = 1029;\n\u00a0\nwhile (b != 0) {\n new_a = b;\n b = a % b;\n a = new_a;\n}\nprint(a);\"\"\").printTokens()\n } // gcd\n\n // Function to generate test case 9 source: Factorial.\n fun factorial() {\n Lexer(\n\"\"\"/* 12 factorial is 479001600 */\n\u00a0\nn = 12;\nresult = 1;\ni = 1;\nwhile (i <= n) {\n result = result * i;\n i = i + 1;\n}\nprint(result);\"\"\").printTokens()\n } // factorial\n\n // Function to generate test case 10 source: Fibonacci Sequence.\n fun fibonacci() {\n Lexer(\n\"\"\"/* fibonacci of 44 is 701408733 */\n\u00a0\nn = 44;\ni = 1;\na = 0;\nb = 1;\nwhile (i < n) {\n w = a + b;\n a = b;\n b = w;\n i = i + 1;\n}\nprint(w, \"\\n\");\"\"\").printTokens()\n } // fibonacci\n\n // Function to generate test case 11 source: FizzBuzz.\n fun fizzbuzz() {\n Lexer(\n\"\"\"/* FizzBuzz */\ni = 1;\nwhile (i <= 100) {\n if (!(i % 15))\n print(\"FizzBuzz\");\n else if (!(i % 3))\n print(\"Fizz\");\n else if (!(i % 5))\n print(\"Buzz\");\n else\n print(i);\n\u00a0\n print(\"\\n\");\n i = i + 1;\n}\"\"\").printTokens()\n } // fizzbuzz\n\n // Function to generate test case 12 source: 99 Bottles of Beer.\n fun bottles() {\n Lexer(\n\"\"\"/* 99 bottles */\nbottles = 99;\nwhile (bottles > 0) {\n print(bottles, \" bottles of beer on the wall\\n\");\n print(bottles, \" bottles of beer\\n\");\n print(\"Take one down, pass it around\\n\");\n bottles = bottles - 1;\n print(bottles, \" bottles of beer on the wall\\n\\n\");\n}\"\"\").printTokens()\n } // bottles\n\n // Function to generate test case 13 source: Primes.\n fun primes() {\n Lexer(\n\"\"\"/*\nSimple prime number generator\n*/\ncount = 1;\nn = 1;\nlimit = 100;\nwhile (n < limit) {\n k=3;\n p=1;\n n=n+2;\n while ((k*k<=n) && (p)) {\n p=n/k*k!=n;\n k=k+2;\n }\n if (p) {\n print(n, \" is prime\\n\");\n count = count + 1;\n }\n}\nprint(\"Total primes found: \", count, \"\\n\");\"\"\").printTokens()\n } // primes\n\n // Function to generate test case 14 source: Ascii Mandelbrot.\n fun ascii() {\n Lexer(\n\"\"\"{\n/*\n This is an integer ascii Mandelbrot generator\n */\n left_edge = -420;\n right_edge = 300;\n top_edge = 300;\n bottom_edge = -300;\n x_step = 7;\n y_step = 15;\n\n max_iter = 200;\n\n y0 = top_edge;\n while (y0 > bottom_edge) {\n x0 = left_edge;\n while (x0 < right_edge) {\n y = 0;\n x = 0;\n the_char = ' ';\n i = 0;\n while (i < max_iter) {\n x_x = (x * x) / 200;\n y_y = (y * y) / 200;\n if (x_x + y_y > 800 ) {\n the_char = '0' + i;\n if (i > 9) {\n the_char = '@';\n }\n i = max_iter;\n }\n y = x * y / 100 + y0;\n x = x_x - y_y + x0;\n i = i + 1;\n }\n putc(the_char);\n x0 = x0 + x_step;\n }\n putc('\\n');\n y0 = y0 - y_step;\n }\n}\n\"\"\").printTokens()\n } // ascii\n\n when (number) {\n 0 ->\n hello()\n 1 ->\n phoenix()\n 2 ->\n symbols()\n 3 ->\n four()\n 4 ->\n count()\n 5 ->\n doors()\n 6 ->\n negative()\n 7 ->\n deep()\n 8 ->\n gcd()\n 9 ->\n factorial()\n 10 ->\n fibonacci()\n 11 ->\n fizzbuzz()\n 12 ->\n bottles()\n 13 ->\n primes()\n 14 ->\n ascii()\n 15 -> // Lexer: Empty character constant\n Lexer(\"''\").printTokens()\n 16 -> // Lexer: Unknown escape sequence\n Lexer(\"'\\\\x\").printTokens()\n 17 -> // Lexer: Multi-character constant\n Lexer(\"' \").printTokens()\n 18 -> // Lexer: EOF in comment\n Lexer(\"/*\").printTokens()\n 19 -> // Lexer: EOL in string\n Lexer(\"\\\"\\n\").printTokens()\n 20 -> // Lexer: EOF in string\n Lexer(\"\\\"\").printTokens()\n 21 -> // Lexer: Escape sequence unknown\n Lexer(\"\\\"\\\\x\").printTokens()\n 22 -> // Lexer: Unrecognized character\n Lexer(\"~\").printTokens()\n 23 -> // Lexer: invalid number\n Lexer(\"9a9\").printTokens()\n 24 -> // Lexer: Number exceeds maximum value\n Lexer(\"2147483648\\n9223372036854775808\").printTokens()\n 25 -> // Lexer: Operator expected\n Lexer(\"|.\").printTokens()\n else ->\n println(\"Invalid test number %d!\".format(number))\n } // when\n} // tests\n\n// Main function to check our source and read its data before parsing it.\n// With no source specified, run the test of all symbols.\nfun main(args: Array) {\n try {\n val s =\n if (args.size > 0 && args[0].isNotEmpty()) // file on command line\n java.util.Scanner(java.io.File(args[0]))\n else // use the console\n java.util.Scanner(System.`in`)\n var source = \"\"\n while (s.hasNext())\n source += s.nextLine()+\n if (s.hasNext())\n \"\\n\"\n else\n \"\"\n if (args.size > 0 && args[0].isNotEmpty()) // file on command line\n Lexer(source).printTokens()\n else {\n val digits = source.filter { it in '0'..'9' }\n when {\n source.isEmpty() -> // nothing given\n tests(2)\n source.length in 1..2 && digits.length == source.length &&\n digits.toInt() in 0..25 ->\n tests(digits.toInt())\n else ->\n Lexer(source).printTokens()\n } // when\n } // if\n } catch(e: Throwable) {\n println(e.message)\n System.exit(1)\n } // try\n} // main"} {"title": "Conjugate transpose", "language": "Kotlin", "task": "Suppose that a conjugate transpose of M is a matrix M^H containing the [[complex conjugate]]s of the [[matrix transposition]] of M.\n\n::: (M^H)_{ji} = \\overline{M_{ij}}\n\n\nThis means that row j, column i of the conjugate transpose equals the \ncomplex conjugate of row i, column j of the original matrix.\n\n\nIn the next list, M must also be a square matrix.\n\n* A Hermitian matrix equals its own conjugate transpose: M^H = M.\n* A multiplication with its conjugate transpose: M^HM = MM^H.\n* A iff M^HM = I_n and iff MM^H = I_n, where I_n is the identity matrix.\n\n\n\n;Task:\nGiven some matrix of complex numbers, find its conjugate transpose. \n\nAlso determine if the matrix is a:\n::* Hermitian matrix,\n::* normal matrix, or \n::* unitary matrix.\n\n\n;See also:\n* MathWorld entry: conjugate transpose\n* MathWorld entry: Hermitian matrix\n* MathWorld entry: normal matrix\n* MathWorld entry: unitary matrix\n\n", "solution": "// version 1.1.3\n\ntypealias C = Complex\ntypealias Vector = Array\ntypealias Matrix = Array\n\nclass Complex(val real: Double, val imag: Double) {\n\n operator fun plus(other: Complex) =\n Complex(this.real + other.real, this.imag + other.imag)\n\n operator fun times(other: Complex) =\n Complex(this.real * other.real - this.imag * other.imag,\n this.real * other.imag + this.imag * other.real)\n\n fun conj() = Complex(this.real, -this.imag)\n\n /* tolerable equality allowing for rounding of Doubles */\n infix fun teq(other: Complex) =\n Math.abs(this.real - other.real) <= 1e-14 &&\n Math.abs(this.imag - other.imag) <= 1e-14\n\n override fun toString() = \"${\"%.3f\".format(real)} \" + when {\n imag > 0.0 -> \"+ ${\"%.3f\".format(imag)}i\"\n imag == 0.0 -> \"+ 0.000i\"\n else -> \"- ${\"%.3f\".format(-imag)}i\"\n }\n}\n\nfun Matrix.conjTranspose(): Matrix {\n val rows = this.size\n val cols = this[0].size\n return Matrix(cols) { i -> Vector(rows) { j -> this[j][i].conj() } }\n}\n\noperator fun Matrix.times(other: Matrix): Matrix {\n val rows1 = this.size\n val cols1 = this[0].size\n val rows2 = other.size\n val cols2 = other[0].size\n require(cols1 == rows2)\n val result = Matrix(rows1) { Vector(cols2) { C(0.0, 0.0) } }\n for (i in 0 until rows1) {\n for (j in 0 until cols2) {\n for (k in 0 until rows2) {\n result[i][j] += this[i][k] * other[k][j]\n }\n }\n }\n return result\n}\n\n/* tolerable matrix equality using the same concept as for complex numbers */\ninfix fun Matrix.teq(other: Matrix): Boolean {\n if (this.size != other.size || this[0].size != other[0].size) return false\n for (i in 0 until this.size) {\n for (j in 0 until this[0].size) if (!(this[i][j] teq other[i][j])) return false\n }\n return true\n}\n\nfun Matrix.isHermitian() = this teq this.conjTranspose()\n\nfun Matrix.isNormal(): Boolean {\n val ct = this.conjTranspose()\n return (this * ct) teq (ct * this)\n}\n\nfun Matrix.isUnitary(): Boolean {\n val ct = this.conjTranspose()\n val prod = this * ct\n val ident = identityMatrix(prod.size)\n val prod2 = ct * this\n return (prod teq ident) && (prod2 teq ident)\n}\n\nfun Matrix.print() {\n val rows = this.size\n val cols = this[0].size\n for (i in 0 until rows) {\n for (j in 0 until cols) {\n print(this[i][j])\n print(if(j < cols - 1) \", \" else \"\\n\")\n }\n }\n println()\n}\n\nfun identityMatrix(n: Int): Matrix {\n require(n >= 1)\n val ident = Matrix(n) { Vector(n) { C(0.0, 0.0) } }\n for (i in 0 until n) ident[i][i] = C(1.0, 0.0)\n return ident\n}\n\nfun main(args: Array) {\n val x = Math.sqrt(2.0) / 2.0\n val matrices = arrayOf(\n arrayOf(\n arrayOf(C(3.0, 0.0), C(2.0, 1.0)),\n arrayOf(C(2.0, -1.0), C(1.0, 0.0))\n ),\n arrayOf(\n arrayOf(C(1.0, 0.0), C(1.0, 0.0), C(0.0, 0.0)),\n arrayOf(C(0.0, 0.0), C(1.0, 0.0), C(1.0, 0.0)),\n arrayOf(C(1.0, 0.0), C(0.0, 0.0), C(1.0, 0.0))\n ),\n arrayOf(\n arrayOf(C(x, 0.0), C(x, 0.0), C(0.0, 0.0)),\n arrayOf(C(0.0, -x), C(0.0, x), C(0.0, 0.0)),\n arrayOf(C(0.0, 0.0), C(0.0, 0.0), C(0.0, 1.0))\n )\n )\n\n for (m in matrices) {\n println(\"Matrix:\")\n m.print()\n val mct = m.conjTranspose()\n println(\"Conjugate transpose:\")\n mct.print()\n println(\"Hermitian? ${mct.isHermitian()}\")\n println(\"Normal? ${mct.isNormal()}\")\n println(\"Unitary? ${mct.isUnitary()}\\n\")\n }\n}"} {"title": "Continued fraction", "language": "Kotlin from D", "task": "A number may be represented as a continued fraction (see Mathworld for more information) as follows:\n:a_0 + \\cfrac{b_1}{a_1 + \\cfrac{b_2}{a_2 + \\cfrac{b_3}{a_3 + \\ddots}}}\n\nThe task is to write a program which generates such a number and prints a real representation of it. The code should be tested by calculating and printing the square root of 2, Napier's Constant, and Pi, using the following coefficients:\n\nFor the square root of 2, use a_0 = 1 then a_N = 2. b_N is always 1.\n\n:\\sqrt{2} = 1 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\cfrac{1}{2 + \\ddots}}}\n\nFor Napier's Constant, use a_0 = 2, then a_N = N. b_1 = 1 then b_N = N-1.\n\n:e = 2 + \\cfrac{1}{1 + \\cfrac{1}{2 + \\cfrac{2}{3 + \\cfrac{3}{4 + \\ddots}}}}\n\nFor Pi, use a_0 = 3 then a_N = 6. b_N = (2N-1)^2.\n\n:\\pi = 3 + \\cfrac{1}{6 + \\cfrac{9}{6 + \\cfrac{25}{6 + \\ddots}}}\n\n\n;See also:\n:* [[Continued fraction/Arithmetic]] for tasks that do arithmetic over continued fractions.\n\n", "solution": "// version 1.1.2\n\ntypealias Func = (Int) -> IntArray\n\nfun calc(f: Func, n: Int): Double {\n var temp = 0.0\n for (i in n downTo 1) {\n val p = f(i)\n temp = p[1] / (p[0] + temp)\n }\n return f(0)[0] + temp\n}\n\nfun main(args: Array) {\n val pList = listOf>(\n \"sqrt(2)\" to { n -> intArrayOf(if (n > 0) 2 else 1, 1) },\n \"e \" to { n -> intArrayOf(if (n > 0) n else 2, if (n > 1) n - 1 else 1) },\n \"pi \" to { n -> intArrayOf(if (n > 0) 6 else 3, (2 * n - 1) * (2 * n - 1)) }\n )\n for (pair in pList) println(\"${pair.first} = ${calc(pair.second, 200)}\")\n}"} {"title": "Continued fraction/Arithmetic/Construct from rational number", "language": "Kotlin", "task": "To understand this task in context please see [[Continued fraction arithmetic]]\nThe purpose of this task is to write a function \\mathit{r2cf}(\\mathrm{int} N_1, \\mathrm{int} N_2), or \\mathit{r2cf}(\\mathrm{Fraction} N), which will output a continued fraction assuming:\n:N_1 is the numerator\n:N_2 is the denominator\n \nThe function should output its results one digit at a time each time it is called, in a manner sometimes described as lazy evaluation.\n\nTo achieve this it must determine: the integer part; and remainder part, of N_1 divided by N_2. It then sets N_1 to N_2 and N_2 to the determined remainder part. It then outputs the determined integer part. It does this until \\mathrm{abs}(N_2) is zero.\n\nDemonstrate the function by outputing the continued fraction for:\n: 1/2\n: 3\n: 23/8\n: 13/11\n: 22/7\n: -151/77\n\\sqrt 2 should approach [1; 2, 2, 2, 2, \\ldots] try ever closer rational approximations until boredom gets the better of you:\n: 14142,10000\n: 141421,100000\n: 1414214,1000000\n: 14142136,10000000\n\nTry :\n: 31,10\n: 314,100\n: 3142,1000\n: 31428,10000\n: 314285,100000\n: 3142857,1000000\n: 31428571,10000000\n: 314285714,100000000\n\nObserve how this rational number behaves differently to \\sqrt 2 and convince yourself that, in the same way as 3.7 may be represented as 3.70 when an extra decimal place is required, [3;7] may be represented as [3;7,\\infty] when an extra term is required.\n\n", "solution": "// version 1.1.2\n// compile with -Xcoroutines=enable flag from command line\n\nimport kotlin.coroutines.experimental.buildSequence\n\nfun r2cf(frac: Pair) =\n buildSequence {\n var num = frac.first\n var den = frac.second\n while (Math.abs(den) != 0) {\n val div = num / den\n val rem = num % den\n num = den\n den = rem\n yield(div)\n }\n }\n\nfun iterate(seq: Sequence) {\n for (i in seq) print(\"$i \")\n println()\n}\n\nfun main(args: Array) {\n val fracs = arrayOf(1 to 2, 3 to 1, 23 to 8, 13 to 11, 22 to 7, -151 to 77)\n for (frac in fracs) {\n print(\"${\"%4d\".format(frac.first)} / ${\"%-2d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n val root2 = arrayOf(14142 to 10000, 141421 to 100000,\n 1414214 to 1000000, 14142136 to 10000000)\n println(\"\\nSqrt(2) ->\")\n for (frac in root2) {\n print(\"${\"%8d\".format(frac.first)} / ${\"%-8d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n val pi = arrayOf(31 to 10, 314 to 100, 3142 to 1000, 31428 to 10000,\n 314285 to 100000, 3142857 to 1000000,\n 31428571 to 10000000, 314285714 to 100000000)\n println(\"\\nPi ->\")\n for (frac in pi) {\n print(\"${\"%9d\".format(frac.first)} / ${\"%-9d\".format(frac.second)} = \")\n iterate(r2cf(frac))\n }\n}"} {"title": "Continued fraction/Arithmetic/G(matrix ng, continued fraction n)", "language": "Kotlin", "task": "This task investigates mathmatical operations that can be performed on a single continued fraction. This requires only a baby version of NG:\n: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix}\nI may perform perform the following operations:\n:Input the next term of N1\n:Output a term of the continued fraction resulting from the operation.\n\nI output a term if the integer parts of \\frac{a}{b} and \\frac{a_1}{b_1} are equal. Otherwise I input a term from N. If I need a term from N but N has no more terms I inject \\infty.\n\nWhen I input a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a + a_1 * t & a_1 \\\\\n b + b_1 * t & b_1 \n\\end{bmatrix}\n\nWhen I output a term t my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} b_1 & b \\\\\n a_1 - b_1 * t & a - b * t \n\\end{bmatrix}\n\nWhen I need a term t but there are no more my internal state: \\begin{bmatrix}\n a_1 & a \\\\\n b_1 & b \n\\end{bmatrix} is transposed thus \\begin{bmatrix} a_1 & a_1 \\\\\n b_1 & b_1 \n\\end{bmatrix}\n\nI am done when b1 and b are zero.\n\nDemonstrate your solution by calculating:\n:[1;5,2] + 1/2\n:[3;7] + 1/2 \n:[3;7] divided by 4\nUsing a generator for \\sqrt{2} (e.g., from [[Continued fraction]]) calculate \\frac{1}{\\sqrt{2}}. You are now at the starting line for using Continued Fractions to implement [[Arithmetic-geometric mean]] without ulps and epsilons.\n\nThe first step in implementing [[Arithmetic-geometric mean]] is to calculate \\frac{1 + \\frac{1}{\\sqrt{2}}}{2} do this now to cross the starting line and begin the race.\n\n", "solution": "// version 1.1.3\n// compile with -Xcoroutines=enable flag from command line\n \nimport kotlin.coroutines.experimental.*\n\ntypealias CFGenerator = (Pair) -> Sequence\n\ndata class CFData( \n val str: String, \n val ng: IntArray,\n val r: Pair,\n val gen: CFGenerator\n)\n \nfun r2cf(frac: Pair) = \n buildSequence {\n var num = frac.first\n var den = frac.second\n while (Math.abs(den) != 0) {\n val div = num / den\n val rem = num % den\n num = den\n den = rem\n yield(div)\n }\n }\n\nfun d2cf(d: Double) = \n buildSequence {\n var dd = d\n while (true) {\n val div = Math.floor(dd)\n val rem = dd - div\n yield(div.toInt())\n if (rem == 0.0) break\n dd = 1.0 / rem\n }\n }\n\n@Suppress(\"UNUSED_PARAMETER\")\nfun root2(dummy: Pair) =\n buildSequence {\n yield(1)\n while (true) yield(2)\n }\n\n@Suppress(\"UNUSED_PARAMETER\")\nfun recipRoot2(dummy: Pair) =\n buildSequence {\n yield(0)\n yield(1)\n while (true) yield(2)\n }\n \nclass NG(var a1: Int, var a: Int, var b1: Int, var b: Int) {\n\n fun ingress(n: Int) {\n var t = a\n a = a1\n a1 = t + a1 * n\n t = b\n b = b1\n b1 = t + b1 * n\n }\n\n fun egress(): Int {\n val n = a / b\n var t = a\n a = b\n b = t - b * n\n t = a1\n a1 = b1\n b1 = t - b1 * n\n return n\n }\n\n val needTerm get() = (b == 0 || b1 == 0) || ((a / b) != (a1 / b1))\n \n val egressDone: Int\n get() {\n if (needTerm) {\n a = a1\n b = b1\n }\n return egress()\n }\n \n val done get() = b == 0 && b1 == 0\n}\n\nfun main(args: Array) {\n val data = listOf(\n CFData(\"[1;5,2] + 1/2 \", intArrayOf(2, 1, 0, 2), 13 to 11, ::r2cf),\n CFData(\"[3;7] + 1/2 \", intArrayOf(2, 1, 0, 2), 22 to 7, ::r2cf),\n CFData(\"[3;7] divided by 4 \", intArrayOf(1, 0, 0, 4), 22 to 7, ::r2cf),\n CFData(\"sqrt(2) \", intArrayOf(0, 1, 1, 0), 0 to 0, ::recipRoot2),\n CFData(\"1 / sqrt(2) \", intArrayOf(0, 1, 1, 0), 0 to 0, ::root2),\n CFData(\"(1 + sqrt(2)) / 2 \", intArrayOf(1, 1, 0, 2), 0 to 0, ::root2),\n CFData(\"(1 + 1 / sqrt(2)) / 2\", intArrayOf(1, 1, 0, 2), 0 to 0, ::recipRoot2) \n )\n println(\"Produced by NG class:\")\n for ((str, ng, r, gen) in data) {\n print(\"$str -> \")\n val (a1, a, b1, b) = ng\n val op = NG(a1, a, b1, b) \n for (n in gen(r).take(20)) {\n if (!op.needTerm) print(\" ${op.egress()} \") \n op.ingress(n) \n } \n while (true) {\n print(\" ${op.egressDone} \")\n if (op.done) break\n }\n println()\n }\n println(\"\\nProduced by direct calculation:\")\n val data2 = listOf(\n Pair(\"(1 + sqrt(2)) / 2 \", (1 + Math.sqrt(2.0)) / 2), \n Pair(\"(1 + 1 / sqrt(2)) / 2\", (1 + 1 / Math.sqrt(2.0)) / 2)\n )\n for ((str, d) in data2) {\n println(\"$str -> ${d2cf(d).take(20).joinToString(\" \")}\")\n }\n}"} {"title": "Convert decimal number to rational", "language": "Kotlin", "task": "The task is to write a program to transform a decimal number into a fraction in lowest terms.\n\nIt is not always possible to do this exactly. For instance, while rational numbers can be converted to decimal representation, some of them need an infinite number of digits to be represented exactly in decimal form. Namely, repeating decimals such as 1/3 = 0.333...\n\nBecause of this, the following fractions cannot be obtained (reliably) unless the language has some way of representing repeating decimals:\n* 67 / 74 = 0.9(054) = 0.9054054...\n* 14 / 27 = 0.(518) = 0.518518...\n\nAcceptable output:\n\n* 0.9054054 - 4527027 / 5000000\n* 0.518518 - 259259 / 500000\n\nFinite decimals are of course no problem:\n\n* 0.75 - 3 / 4 \n\n", "solution": "// version 1.1.2\n\nclass Rational(val num: Long, val den: Long) {\n override fun toString() = \"$num/$den\"\n}\n\nfun decimalToRational(d: Double): Rational {\n val ds = d.toString().trimEnd('0').trimEnd('.')\n val index = ds.indexOf('.')\n if (index == -1) return Rational(ds.toLong(), 1L)\n var num = ds.replace(\".\", \"\").toLong()\n var den = 1L\n for (n in 1..(ds.length - index - 1)) den *= 10L\n while (num % 2L == 0L && den % 2L == 0L) {\n num /= 2L\n den /= 2L\n }\n while (num % 5L == 0L && den % 5L == 0L) {\n num /= 5L\n den /= 5L\n }\n return Rational(num, den)\n}\n\nfun main(args: Array) {\n val decimals = doubleArrayOf(0.9054054, 0.518518, 2.405308, .75, 0.0, -0.64, 123.0, -14.6)\n for (decimal in decimals)\n println(\"${decimal.toString().padEnd(9)} = ${decimalToRational(decimal)}\")\n}"} {"title": "Convert seconds to compound duration", "language": "Kotlin", "task": "Write a function or program which:\n* takes a positive integer representing a duration in seconds as input (e.g., 100), and\n* returns a string which shows the same duration decomposed into:\n:::* weeks,\n:::* days, \n:::* hours, \n:::* minutes, and \n:::* seconds.\n\nThis is detailed below (e.g., \"2 hr, 59 sec\").\n\n\nDemonstrate that it passes the following three test-cases:\n\n'''''Test Cases'''''\n\n:::::{| class=\"wikitable\"\n|-\n! input number\n! output string\n|-\n| 7259\n| 2 hr, 59 sec\n|-\n| 86400\n| 1 d\n|-\n| 6000000\n| 9 wk, 6 d, 10 hr, 40 min\n|}\n\n'''''Details'''''\n\nThe following five units should be used:\n:::::{| class=\"wikitable\"\n|-\n! unit\n! suffix used in output\n! conversion\n|-\n| week\n| wk\n| 1 week = 7 days\n|-\n| day\n| d\n| 1 day = 24 hours\n|-\n| hour\n| hr\n| 1 hour = 60 minutes\n|-\n| minute\n| min\n| 1 minute = 60 seconds\n|-\n| second\n| sec\n| \n|}\n\nHowever, '''only''' include quantities with non-zero values in the output (e.g., return \"1 d\" and not \"0 wk, 1 d, 0 hr, 0 min, 0 sec\").\n\nGive larger units precedence over smaller ones as much as possible (e.g., return 2 min, 10 sec and not 1 min, 70 sec or 130 sec)\n\nMimic the formatting shown in the test-cases (quantities sorted from largest unit to smallest and separated by comma+space; value and unit of each quantity separated by space).\n\n\n", "solution": "fun compoundDuration(n: Int): String {\n if (n < 0) return \"\" // task doesn't ask for negative integers to be converted\n if (n == 0) return \"0 sec\"\n val weeks : Int\n val days : Int\n val hours : Int\n val minutes: Int\n val seconds: Int\n var divisor: Int = 7 * 24 * 60 * 60\n var rem : Int\n var result = \"\"\n\n weeks = n / divisor\n rem = n % divisor\n divisor /= 7\n days = rem / divisor\n rem %= divisor\n divisor /= 24\n hours = rem / divisor\n rem %= divisor\n divisor /= 60\n minutes = rem / divisor\n seconds = rem % divisor\n\n if (weeks > 0) result += \"$weeks wk, \"\n if (days > 0) result += \"$days d, \"\n if (hours > 0) result += \"$hours hr, \"\n if (minutes > 0) result += \"$minutes min, \"\n if (seconds > 0)\n result += \"$seconds sec\"\n else\n result = result.substring(0, result.length - 2)\n return result\n}\n\nfun main(args: Array) {\n val durations = intArrayOf(0, 7, 84, 7259, 86400, 6000000)\n durations.forEach { println(\"$it\\t-> ${compoundDuration(it)}\") }\n}"} {"title": "Copy stdin to stdout", "language": "Kotlin", "task": "Create an executable file that copies stdin to stdout, or else a script that does so through the invocation of an interpreter at the command line.\n\n", "solution": "fun main() {\n var c: Int\n do {\n c = System.`in`.read()\n System.out.write(c)\n } while (c >= 0)\n}"} {"title": "Count the coins", "language": "Kotlin from C#", "task": "There are four types of common coins in US currency: \n:::# quarters (25 cents)\n:::# dimes (10 cents)\n:::# nickels (5 cents), and \n:::# pennies (1 cent) \n\n\nThere are six ways to make change for 15 cents:\n:::# A dime and a nickel \n:::# A dime and 5 pennies\n:::# 3 nickels\n:::# 2 nickels and 5 pennies\n:::# A nickel and 10 pennies\n:::# 15 pennies\n\n\n;Task:\nHow many ways are there to make change for a dollar using these common coins? (1 dollar = 100 cents).\n\n\n;Optional:\nLess common are dollar coins (100 cents); and very rare are half dollars (50 cents). With the addition of these two coins, how many ways are there to make change for $1000? \n\n(Note: the answer is larger than 232).\n\n\n;References:\n* an algorithm from the book ''Structure and Interpretation of Computer Programs''.\n* an article in the algorithmist.\n* Change-making problem on Wikipedia.\n\n", "solution": "// version 1.0.6\n\nfun countCoins(c: IntArray, m: Int, n: Int): Long {\n val table = LongArray(n + 1)\n table[0] = 1\n for (i in 0 until m) \n for (j in c[i]..n) table[j] += table[j - c[i]]\n return table[n]\n}\n\nfun main(args: Array) {\n val c = intArrayOf(1, 5, 10, 25, 50, 100)\n println(countCoins(c, 4, 100))\n println(countCoins(c, 6, 1000 * 100)) \n}"} {"title": "Create an HTML table", "language": "Kotlin", "task": "Create an HTML table. \n* The table body should have at least three rows of three columns.\n* Each of these three columns should be labelled \"X\", \"Y\", and \"Z\". \n* An extra column should be added at either the extreme left or the extreme right of the table that has no heading, but is filled with sequential row numbers. \n* The rows of the \"X\", \"Y\", and \"Z\" columns should be filled with random or sequential integers having 4 digits or less. \n* The numbers should be aligned in the same fashion for all columns.\n\n", "solution": "// version 1.1.3\n\nimport java.util.Random\n\nfun main(args: Array) {\n val r = Random()\n val sb = StringBuilder()\n val i = \" \" // indent\n with (sb) {\n append(\"\\n\\n\")\n append(\"\\n\\n\\n\") \n append(\"\\n\")\n append(\"$i\\n\")\n append(\"$i$i\")\n for (c in 'X'..'Z') append(\"\")\n append(\"\\n\")\n append(\"$i\\n\")\n append(\"$i\\n\")\n val f = \"$i$i\\n\"\n for (j in 1..4) {\n append(f.format(j, r.nextInt(10000), r.nextInt(10000), r.nextInt(10000)))\n } \n append(\"$i\\n\")\n append(\"
$c
%d%d%d%d
\\n\")\n append(\"\\n\")\n }\n println(sb.toString())\n}"} {"title": "Currency", "language": "Kotlin", "task": "Show how to represent currency in a simple example, using a data type that represent exact values of dollars and cents. \n\n\n;Note:\nThe '''IEEE 754''' binary floating point representations of numbers like '''2.86''' and '''.0765''' are not exact.\n\nFor this example, data will be two items with prices in dollars and cents, a quantity for each, and a tax rate. \n \nUse the values:\n::* 4000000000000000 hamburgers at $5.50 each (four quadrillion burgers)\n::* 2 milkshakes at $2.86 each, and \n::* a tax rate of 7.65%. \n\n\n(That number of hamburgers is a 4 with 15 zeros after it. The number is contrived to exclude naive task solutions using 64 bit floating point types.) \n\nCompute and output (show results on this page):\n::* the total price before tax\n::* the tax\n::* the total with tax \n\n\nThe tax value must be computed by rounding to the nearest whole cent and this exact value must be added to the total price before tax. \n\nThe output must show dollars and cents with a decimal point. \n \nThe three results displayed should be:\n::* 22000000000000005.72\n::* 1683000000000000.44 \n::* 23683000000000006.16 \n\n\nDollar signs and thousands separators are optional.\n\n", "solution": "// version 1.1.2\n\nimport java.math.BigDecimal\nimport java.math.MathContext\n\nfun main(args: Array) {\n val mc = MathContext.DECIMAL128\n val nHamburger = BigDecimal(\"4000000000000000\", mc)\n val pHamburger = BigDecimal(\"5.50\")\n val nMilkshakes = BigDecimal(\"2\", mc)\n val pMilkshakes = BigDecimal(\"2.86\")\n val taxRate = BigDecimal(\"0.0765\")\n val price = nHamburger * pHamburger + nMilkshakes * pMilkshakes\n val tax = price * taxRate\n val fmt = \"%20.2f\"\n println(\"Total price before tax : ${fmt.format(price)}\")\n println(\"Tax thereon @ 7.65% : ${fmt.format(tax)}\")\n println(\"Total price after tax : ${fmt.format(price + tax)}\")\n}"} {"title": "Currying", "language": "Kotlin", "task": "{{Wikipedia|Currying}}\n\n\n;Task:\nCreate a simple demonstrative example of Currying in a specific language. \n\nAdd any historic details as to how the feature made its way into the language.\n\n\n\n", "solution": "// version 1.1.2\n\nfun curriedAdd(x: Int) = { y: Int -> x + y }\n\nfun main(args: Array) {\n val a = 2\n val b = 3\n val sum = curriedAdd(a)(b)\n println(\"$a + $b = $sum\")\n}"} {"title": "Cut a rectangle", "language": "Kotlin from C", "task": "A given rectangle is made from ''m'' x ''n'' squares. If ''m'' and ''n'' are not both odd, then it is possible to cut a path through the rectangle along the square edges such that the rectangle splits into two connected pieces with the same shape (after rotating one of the pieces by 180deg). All such paths for 2 x 2 and 4 x 3 rectangles are shown below.\n\n[[file:rect-cut.svg]]\n\nWrite a program that calculates the number of different ways to cut an ''m'' x ''n'' rectangle. Optionally, show each of the cuts.\n\nPossibly related task: [[Maze generation]] for depth-first search.\n\n", "solution": "// version 1.0.6\n\nobject RectangleCutter {\n private var w: Int = 0\n private var h: Int = 0\n private var len: Int = 0\n private var cnt: Long = 0\n\n private lateinit var grid: ByteArray\n private val next = IntArray(4)\n private val dir = arrayOf(\n intArrayOf(0, -1),\n intArrayOf(-1, 0),\n intArrayOf(0, 1),\n intArrayOf(1, 0)\n )\n\n private fun walk(y: Int, x: Int) {\n if (y == 0 || y == h || x == 0 || x == w) {\n cnt += 2\n return\n }\n val t = y * (w + 1) + x\n grid[t]++\n grid[len - t]++\n (0..3).filter { grid[t + next[it]] == 0.toByte() }\n .forEach { walk(y + dir[it][0], x + dir[it][1]) }\n grid[t]--\n grid[len - t]--\n }\n\n fun solve(hh: Int, ww: Int, recur: Boolean): Long {\n var t: Int\n h = hh\n w = ww\n if ((h and 1) != 0) {\n t = w\n w = h\n h = t\n }\n if ((h and 1) != 0) return 0L\n if (w == 1) return 1L\n if (w == 2) return h.toLong()\n if (h == 2) return w.toLong()\n val cy = h / 2\n val cx = w / 2\n len = (h + 1) * (w + 1)\n grid = ByteArray(len)\n len--\n next[0] = -1\n next[1] = -w - 1\n next[2] = 1\n next[3] = w + 1\n if (recur) cnt = 0L\n for (x in cx + 1 until w) {\n t = cy * (w + 1) + x\n grid[t] = 1\n grid[len - t] = 1\n walk(cy - 1, x)\n }\n cnt++\n if (h == w) cnt *= 2\n else if ((w and 1) == 0 && recur) solve(w, h, false)\n return cnt\n }\n}\n\nfun main(args: Array) {\n for (y in 1..10) {\n for (x in 1..y) {\n if ((x and 1) == 0 || (y and 1) == 0) {\n println(\"${\"%2d\".format(y)} x ${\"%2d\".format(x)}: ${RectangleCutter.solve(y, x, true)}\")\n }\n }\n }\n}"} {"title": "Cyclotomic polynomial", "language": "Kotlin from Java", "task": "The nth Cyclotomic polynomial, for any positive integer n, is the unique irreducible polynomial of largest degree with integer coefficients that is a divisor of x^n - 1, and is not a divisor of x^k - 1 for any k < n.\n\n\n;Task:\n* Find and print the first 30 cyclotomic polynomials.\n* Find and print the order of the first 10 cyclotomic polynomials that have n or -n as a coefficient.\n\n\n;See also\n* Wikipedia article, Cyclotomic polynomial, showing ways to calculate them.\n* The sequence A013594 with the smallest order of cyclotomic polynomial containing n or -n as a coefficient.\n\n", "solution": "import java.util.TreeMap\nimport kotlin.math.abs\nimport kotlin.math.pow\nimport kotlin.math.sqrt\n\nprivate const val algorithm = 2\n\nfun main() {\n println(\"Task 1: cyclotomic polynomials for n <= 30:\")\n for (i in 1..30) {\n val p = cyclotomicPolynomial(i)\n println(\"CP[$i] = $p\")\n }\n println()\n\n println(\"Task 2: Smallest cyclotomic polynomial with n or -n as a coefficient:\")\n var n = 0\n for (i in 1..10) {\n while (true) {\n n++\n val cyclo = cyclotomicPolynomial(n)\n if (cyclo!!.hasCoefficientAbs(i)) {\n println(\"CP[$n] has coefficient with magnitude = $i\")\n n--\n break\n }\n }\n }\n}\n\nprivate val COMPUTED: MutableMap = HashMap()\nprivate fun cyclotomicPolynomial(n: Int): Polynomial? {\n if (COMPUTED.containsKey(n)) {\n return COMPUTED[n]\n }\n if (n == 1) {\n // Polynomial: x - 1\n val p = Polynomial(1, 1, -1, 0)\n COMPUTED[1] = p\n return p\n }\n val factors = getFactors(n)\n if (factors.containsKey(n)) {\n // n prime\n val termList: MutableList = ArrayList()\n for (index in 0 until n) {\n termList.add(Term(1, index.toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 2 && factors.containsKey(2) && factors[2] == 1 && factors.containsKey(n / 2) && factors[n / 2] == 1) {\n // n = 2p\n val prime = n / 2\n val termList: MutableList = ArrayList()\n var coeff = -1\n for (index in 0 until prime) {\n coeff *= -1\n termList.add(Term(coeff.toLong(), index.toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 1 && factors.containsKey(2)) {\n // n = 2^h\n val h = factors[2]!!\n val termList: MutableList = ArrayList()\n termList.add(Term(1, 2.0.pow((h - 1).toDouble()).toLong()))\n termList.add(Term(1, 0))\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 1 && !factors.containsKey(n)) {\n // n = p^k\n var p = 0\n for (prime in factors.keys) {\n p = prime\n }\n val k = factors[p]!!\n val termList: MutableList = ArrayList()\n for (index in 0 until p) {\n termList.add(Term(1, (index * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.size == 2 && factors.containsKey(2)) {\n // n = 2^h * p^k\n var p = 0\n for (prime in factors.keys) {\n if (prime != 2) {\n p = prime\n }\n }\n val termList: MutableList = ArrayList()\n var coeff = -1\n val twoExp = 2.0.pow((factors[2]!!) - 1.toDouble()).toInt()\n val k = factors[p]!!\n for (index in 0 until p) {\n coeff *= -1\n termList.add(Term(coeff.toLong(), (index * twoExp * p.toDouble().pow(k - 1.toDouble()).toInt()).toLong()))\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n } else if (factors.containsKey(2) && n / 2 % 2 == 1 && n / 2 > 1) {\n // CP(2m)[x] = CP(-m)[x], n odd integer > 1\n val cycloDiv2 = cyclotomicPolynomial(n / 2)\n val termList: MutableList = ArrayList()\n for (term in cycloDiv2!!.polynomialTerms) {\n termList.add(if (term.exponent % 2 == 0L) term else term.negate())\n }\n val cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n return cyclo\n }\n\n // General Case\n return when (algorithm) {\n 0 -> {\n // Slow - uses basic definition.\n val divisors = getDivisors(n)\n // Polynomial: ( x^n - 1 )\n var cyclo = Polynomial(1, n, -1, 0)\n for (i in divisors) {\n val p = cyclotomicPolynomial(i)\n cyclo = cyclo.divide(p)\n }\n COMPUTED[n] = cyclo\n cyclo\n }\n 1 -> {\n // Faster. Remove Max divisor (and all divisors of max divisor) - only one divide for all divisors of Max Divisor\n val divisors = getDivisors(n)\n var maxDivisor = Int.MIN_VALUE\n for (div in divisors) {\n maxDivisor = maxDivisor.coerceAtLeast(div)\n }\n val divisorsExceptMax: MutableList = ArrayList()\n for (div in divisors) {\n if (maxDivisor % div != 0) {\n divisorsExceptMax.add(div)\n }\n }\n\n // Polynomial: ( x^n - 1 ) / ( x^m - 1 ), where m is the max divisor\n var cyclo = Polynomial(1, n, -1, 0).divide(Polynomial(1, maxDivisor, -1, 0))\n for (i in divisorsExceptMax) {\n val p = cyclotomicPolynomial(i)\n cyclo = cyclo.divide(p)\n }\n COMPUTED[n] = cyclo\n cyclo\n }\n 2 -> {\n // Fastest\n // Let p ; q be primes such that p does not divide n, and q q divides n.\n // Then CP(np)[x] = CP(n)[x^p] / CP(n)[x]\n var m = 1\n var cyclo = cyclotomicPolynomial(m)\n val primes = factors.keys.toMutableList()\n primes.sort()\n for (prime in primes) {\n // CP(m)[x]\n val cycloM = cyclo\n // Compute CP(m)[x^p].\n val termList: MutableList = ArrayList()\n for (t in cycloM!!.polynomialTerms) {\n termList.add(Term(t.coefficient, t.exponent * prime))\n }\n cyclo = Polynomial(termList).divide(cycloM)\n m *= prime\n }\n // Now, m is the largest square free divisor of n\n val s = n / m\n // Compute CP(n)[x] = CP(m)[x^s]\n val termList: MutableList = ArrayList()\n for (t in cyclo!!.polynomialTerms) {\n termList.add(Term(t.coefficient, t.exponent * s))\n }\n cyclo = Polynomial(termList)\n COMPUTED[n] = cyclo\n cyclo\n }\n else -> {\n throw RuntimeException(\"ERROR 103: Invalid algorithm.\")\n }\n }\n}\n\nprivate fun getDivisors(number: Int): List {\n val divisors: MutableList = ArrayList()\n val sqrt = sqrt(number.toDouble()).toLong()\n for (i in 1..sqrt) {\n if (number % i == 0L) {\n divisors.add(i.toInt())\n val div = (number / i).toInt()\n if (div.toLong() != i && div != number) {\n divisors.add(div)\n }\n }\n }\n return divisors\n}\n\nprivate fun crutch(): MutableMap> {\n val allFactors: MutableMap> = TreeMap()\n\n val factors: MutableMap = TreeMap()\n factors[2] = 1\n\n allFactors[2] = factors\n return allFactors\n}\n\nprivate val allFactors = crutch()\n\nvar MAX_ALL_FACTORS = 100000\n\nfun getFactors(number: Int): Map {\n if (allFactors.containsKey(number)) {\n return allFactors[number]!!\n }\n val factors: MutableMap = TreeMap()\n if (number % 2 == 0) {\n val factorsDivTwo = getFactors(number / 2)\n factors.putAll(factorsDivTwo)\n factors.merge(2, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n if (number < MAX_ALL_FACTORS) allFactors[number] = factors\n return factors\n }\n val sqrt = sqrt(number.toDouble()).toLong()\n var i = 3\n while (i <= sqrt) {\n if (number % i == 0) {\n factors.putAll(getFactors(number / i))\n factors.merge(i, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n if (number < MAX_ALL_FACTORS) {\n allFactors[number] = factors\n }\n return factors\n }\n i += 2\n }\n factors[number] = 1\n if (number < MAX_ALL_FACTORS) {\n allFactors[number] = factors\n }\n return factors\n}\n\nprivate class Polynomial {\n val polynomialTerms: MutableList\n\n // Format - coeff, exp, coeff, exp, (repeating in pairs) . . .\n constructor(vararg values: Int) {\n require(values.size % 2 == 0) { \"ERROR 102: Polynomial constructor. Length must be even. Length = \" + values.size }\n polynomialTerms = mutableListOf()\n var i = 0\n while (i < values.size) {\n val t = Term(values[i].toLong(), values[i + 1].toLong())\n polynomialTerms.add(t)\n i += 2\n }\n polynomialTerms.sortWith(TermSorter())\n }\n\n constructor() {\n // zero\n polynomialTerms = ArrayList()\n polynomialTerms.add(Term(0, 0))\n }\n\n fun hasCoefficientAbs(coeff: Int): Boolean {\n for (term in polynomialTerms) {\n if (abs(term.coefficient) == coeff.toLong()) {\n return true\n }\n }\n return false\n }\n\n constructor(termList: MutableList) {\n if (termList.isEmpty()) {\n // zero\n termList.add(Term(0, 0))\n } else {\n // Remove zero terms if needed\n termList.removeIf { t -> t.coefficient == 0L }\n }\n if (termList.size == 0) {\n // zero\n termList.add(Term(0, 0))\n }\n polynomialTerms = termList\n polynomialTerms.sortWith(TermSorter())\n }\n\n fun divide(v: Polynomial?): Polynomial {\n var q = Polynomial()\n var r = this\n val lcv = v!!.leadingCoefficient()\n val dv = v.degree()\n while (r.degree() >= v.degree()) {\n val lcr = r.leadingCoefficient()\n val s = lcr / lcv // Integer division\n val term = Term(s, r.degree() - dv)\n q = q.add(term)\n r = r.add(v.multiply(term.negate()))\n }\n return q\n }\n\n fun add(polynomial: Polynomial): Polynomial {\n val termList: MutableList = ArrayList()\n var thisCount = polynomialTerms.size\n var polyCount = polynomial.polynomialTerms.size\n while (thisCount > 0 || polyCount > 0) {\n val thisTerm = if (thisCount == 0) null else polynomialTerms[thisCount - 1]\n val polyTerm = if (polyCount == 0) null else polynomial.polynomialTerms[polyCount - 1]\n when {\n thisTerm == null -> {\n termList.add(polyTerm!!.clone())\n polyCount--\n }\n polyTerm == null -> {\n termList.add(thisTerm.clone())\n thisCount--\n }\n thisTerm.degree() == polyTerm.degree() -> {\n val t = thisTerm.add(polyTerm)\n if (t.coefficient != 0L) {\n termList.add(t)\n }\n thisCount--\n polyCount--\n }\n thisTerm.degree() < polyTerm.degree() -> {\n termList.add(thisTerm.clone())\n thisCount--\n }\n else -> {\n termList.add(polyTerm.clone())\n polyCount--\n }\n }\n }\n return Polynomial(termList)\n }\n\n fun add(term: Term): Polynomial {\n val termList: MutableList = ArrayList()\n var added = false\n for (currentTerm in polynomialTerms) {\n if (currentTerm.exponent == term.exponent) {\n added = true\n if (currentTerm.coefficient + term.coefficient != 0L) {\n termList.add(currentTerm.add(term))\n }\n } else {\n termList.add(currentTerm.clone())\n }\n }\n if (!added) {\n termList.add(term.clone())\n }\n return Polynomial(termList)\n }\n\n fun multiply(term: Term): Polynomial {\n val termList: MutableList = ArrayList()\n for (currentTerm in polynomialTerms) {\n termList.add(currentTerm.clone().multiply(term))\n }\n return Polynomial(termList)\n }\n\n fun leadingCoefficient(): Long {\n return polynomialTerms[0].coefficient\n }\n\n fun degree(): Long {\n return polynomialTerms[0].exponent\n }\n\n override fun toString(): String {\n val sb = StringBuilder()\n var first = true\n for (term in polynomialTerms) {\n if (first) {\n sb.append(term)\n first = false\n } else {\n sb.append(\" \")\n if (term.coefficient > 0) {\n sb.append(\"+ \")\n sb.append(term)\n } else {\n sb.append(\"- \")\n sb.append(term.negate())\n }\n }\n }\n return sb.toString()\n }\n}\n\nprivate class TermSorter : Comparator {\n override fun compare(o1: Term, o2: Term): Int {\n return (o2.exponent - o1.exponent).toInt()\n }\n}\n\n// Note: Cyclotomic Polynomials have small coefficients. Not appropriate for general polynomial usage.\nprivate class Term(var coefficient: Long, var exponent: Long) {\n fun clone(): Term {\n return Term(coefficient, exponent)\n }\n\n fun multiply(term: Term): Term {\n return Term(coefficient * term.coefficient, exponent + term.exponent)\n }\n\n fun add(term: Term): Term {\n if (exponent != term.exponent) {\n throw RuntimeException(\"ERROR 102: Exponents not equal.\")\n }\n return Term(coefficient + term.coefficient, exponent)\n }\n\n fun negate(): Term {\n return Term(-coefficient, exponent)\n }\n\n fun degree(): Long {\n return exponent\n }\n\n override fun toString(): String {\n if (coefficient == 0L) {\n return \"0\"\n }\n if (exponent == 0L) {\n return \"\" + coefficient\n }\n if (coefficient == 1L) {\n return if (exponent == 1L) {\n \"x\"\n } else {\n \"x^$exponent\"\n }\n }\n return if (exponent == 1L) {\n coefficient.toString() + \"x\"\n } else coefficient.toString() + \"x^\" + exponent\n }\n}"} {"title": "Damm algorithm", "language": "Kotlin", "task": "The '''Damm''' algorithm is a checksum algorithm which detects all single digit errors and adjacent transposition errors. \n\n\nThe algorithm is named after H. Michael Damm.\n\n\n;Task:\nVerify the checksum, stored as last digit of an input.\n\n\n\n", "solution": "// version 1.1.2\n\nval table = arrayOf(\n intArrayOf(0, 3, 1,\t7, 5, 9, 8, 6, 4, 2),\n intArrayOf(7, 0, 9, 2, 1, 5, 4, 8, 6, 3),\n intArrayOf(4, 2, 0, 6, 8, 7, 1, 3, 5, 9),\n intArrayOf(1, 7, 5, 0, 9, 8, 3, 4, 2, 6),\n intArrayOf(6, 1, 2, 3, 0, 4, 5, 9, 7, 8),\n intArrayOf(3, 6, 7, 4, 2, 0, 9, 5, 8, 1),\n intArrayOf(5, 8, 6, 9, 7, 2, 0, 1, 3, 4),\n intArrayOf(8, 9, 4, 5, 3, 6, 2, 0, 1, 7),\n intArrayOf(9, 4, 3, 8, 6, 1, 7, 2, 0, 5),\n intArrayOf(2, 5, 8, 1, 4, 3, 6, 7, 9, 0)\n) \n\nfun damm(s: String): Boolean {\n var interim = 0\n for (c in s) interim = table[interim][c - '0']\n return interim == 0\n}\n\nfun main(args: Array) {\n val numbers = intArrayOf(5724, 5727, 112946, 112949)\n for (number in numbers) {\n val isValid = damm(number.toString())\n println(\"${\"%6d\".format(number)} is ${if (isValid) \"valid\" else \"invalid\"}\")\n }\n}"} {"title": "De Bruijn sequences", "language": "Kotlin from Go", "task": "{{DISPLAYTITLE:de Bruijn sequences}}\nThe sequences are named after the Dutch mathematician Nicolaas Govert de Bruijn.\n\n\nA note on Dutch capitalization: Nicolaas' last name is '''de Bruijn''', the '''de''' isn't normally capitalized\nunless it's the first word in a sentence. Rosetta Code (more or less by default or by fiat) requires the first word in the task name to be\ncapitalized.\n\n\nIn combinatorial mathematics, a '''de Bruijn sequence''' of order ''n'' on\na size-''k'' alphabet (computer science) ''A'' is a cyclic sequence in which every\npossible length-''n'' string (computer science, formal theory) on ''A'' occurs\nexactly once as a contiguous substring.\n\n\nSuch a sequence is denoted by ''B''(''k'', ''n'') and has\nlength ''k''''n'', which is also the number of distinct substrings of\nlength ''n'' on ''A''; \nde Bruijn sequences are therefore optimally short.\n\n\nThere are:\n (k!)k(n-1) / kn\ndistinct de Bruijn sequences ''B''(''k'', ''n''). \n\n\n;Task:\nFor this Rosetta Code task, a '''de Bruijn''' sequence is to be generated that can be used to shorten a brute-force attack on\na PIN-like code lock that does not have an \"enter\"\nkey and accepts the last ''n'' digits entered.\n\n\nNote: automated teller machines (ATMs) used to work like\nthis, but their software has been updated to not allow a brute-force attack.\n\n\n;Example:\nA digital door lock with a 4-digit code would\nhave ''B'' (10, 4) solutions, with a length of '''10,000''' (digits).\n\nTherefore, only at most '''10,000 + 3''' (as the solutions are cyclic or ''wrap-around'') presses are needed to\nopen the lock.\n\nTrying all 4-digit codes separately would require '''4 x 10,000''' or '''40,000''' presses.\n\n\n;Task requirements:\n:* Generate a de Bruijn sequence for a 4-digit (decimal) PIN code.\n:::* Show the length of the generated de Bruijn sequence.\n:::* (There are many possible de Bruijn sequences that solve this task, one solution is shown on the ''discussion'' page).\n:::* Show the first and last '''130''' digits of the de Bruijn sequence.\n:* Verify that all four-digit (decimal) '''1,000''' PIN codes are contained within the de Bruijn sequence.\n:::* 0000, 0001, 0002, 0003, ... 9996, 9997, 9998, 9999 (note the leading zeros).\n:* Reverse the de Bruijn sequence.\n:* Again, perform the (above) verification test.\n:* Replace the 4,444th digit with a period (.) in the original de Bruijn sequence.\n:::* Perform the verification test (again). There should be four PIN codes missing.\n\n\n(The last requirement is to ensure that the verification tests performs correctly. The verification processes should list\nany and all missing PIN codes.)\n\nShow all output here, on this page.\n\n\n\n;References:\n:* Wikipedia entry: de Bruijn sequence.\n:* MathWorld entry: de Bruijn sequence.\n:* An OEIS entry: A166315 lexicographically earliest binary de Bruijn sequences, B(2,n) --- Not B(10,4), but possibly relevant.\n\n", "solution": "const val digits = \"0123456789\"\n\nfun deBruijn(k: Int, n: Int): String {\n val alphabet = digits.substring(0, k)\n val a = ByteArray(k * n)\n val seq = mutableListOf()\n fun db(t: Int, p: Int) {\n if (t > n) {\n if (n % p == 0) {\n seq.addAll(a.sliceArray(1..p).asList())\n }\n } else {\n a[t] = a[t - p]\n db(t + 1, p)\n var j = a[t - p] + 1\n while (j < k) {\n a[t] = j.toByte()\n db(t + 1, t)\n j++\n }\n }\n }\n db(1, 1)\n val buf = StringBuilder()\n for (i in seq) {\n buf.append(alphabet[i.toInt()])\n }\n val b = buf.toString()\n return b + b.subSequence(0, n - 1)\n}\n\nfun allDigits(s: String): Boolean {\n for (c in s) {\n if (c < '0' || '9' < c) {\n return false\n }\n }\n return true\n}\n\nfun validate(db: String) {\n val le = db.length\n val found = MutableList(10_000) { 0 }\n val errs = mutableListOf()\n // Check all strings of 4 consecutive digits within 'db'\n // to see if all 10,000 combinations occur without duplication.\n for (i in 0 until le - 3) {\n val s = db.substring(i, i + 4)\n if (allDigits(s)) {\n val n = s.toInt()\n found[n]++\n }\n }\n for (i in 0 until 10_000) {\n if (found[i] == 0) {\n errs.add(\" PIN number %04d missing\".format(i))\n } else if (found[i] > 1) {\n errs.add(\" PIN number %04d occurs %d times\".format(i, found[i]))\n }\n }\n val lerr = errs.size\n if (lerr == 0) {\n println(\" No errors found\")\n } else {\n val pl = if (lerr == 1) {\n \"\"\n } else {\n \"s\"\n }\n println(\" $lerr error$pl found:\")\n println(errs.joinToString(\"\\n\"))\n }\n}\n\nfun main() {\n var db = deBruijn(10, 4)\n val le = db.length\n\n println(\"The length of the de Bruijn sequence is $le\")\n println(\"\\nThe first 130 digits of the de Bruijn sequence are: ${db.subSequence(0, 130)}\")\n println(\"\\nThe last 130 digits of the de Bruijn sequence are: ${db.subSequence(le - 130, le)}\")\n\n println(\"\\nValidating the deBruijn sequence:\")\n validate(db)\n\n println(\"\\nValidating the reversed deBruijn sequence:\")\n validate(db.reversed())\n\n val bytes = db.toCharArray()\n bytes[4443] = '.'\n db = String(bytes)\n println(\"\\nValidating the overlaid deBruijn sequence:\")\n validate(db)\n}"} {"title": "Deepcopy", "language": "Kotlin", "task": "Demonstrate how to copy data structures containing complex heterogeneous and cyclic semantics. \n\nThis is often referred to as deep copying, and is normally required where structures are mutable and to ensure that independent copies can be manipulated without side-effects.\n\nIf this facility is not built into the language, it is permissible to use functions from a common library, or a coded procedure.\n\n\nThe task should show:\n\n* Relevant semantics of structures, such as their homogeneous or heterogeneous properties, or containment of (self- or mutual-reference) cycles.\n\n* Any limitations of the method.\n\n* That the structure and its copy are different.\n\n* Suitable links to external documentation for common libraries.\n\n", "solution": "// Version 1.2.31\n\nimport java.io.Serializable\nimport java.io.ByteArrayOutputStream\nimport java.io.ByteArrayInputStream\nimport java.io.ObjectOutputStream\nimport java.io.ObjectInputStream\n\nfun deepCopy(obj: T?): T? {\n if (obj == null) return null\n val baos = ByteArrayOutputStream()\n val oos = ObjectOutputStream(baos)\n oos.writeObject(obj)\n oos.close()\n val bais = ByteArrayInputStream(baos.toByteArray())\n val ois = ObjectInputStream(bais)\n @Suppress(\"unchecked_cast\")\n return ois.readObject() as T\n} \n\nclass Person(\n val name: String,\n var age: Int,\n val sex: Char,\n var income: Double,\n var partner: Person?\n) : Serializable\n\nfun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) {\n with (p3) {\n println(\"Name : $name\")\n println(\"Age : $age\")\n println(\"Sex : $sex\")\n println(\"Income : $income\")\n if (p4 == null) {\n println(\"Partner : None\")\n }\n else {\n println(\"Partner :-\")\n with (p4) {\n println(\" Name : $name\")\n println(\" Age : $age\")\n println(\" Sex : $sex\")\n println(\" Income : $income\")\n }\n }\n println(\"\\nSame person as original '$name' == ${p1 === p3}\")\n if (p4 != null) {\n println(\"Same person as original '${p2!!.name}' == ${p2 === p4}\")\n }\n }\n println()\n}\n\nfun main(args: Array) {\n var p1 = Person(\"John\", 35, 'M', 50000.0, null)\n val p2 = Person(\"Jane\", 32, 'F', 25000.0, p1)\n p1.partner = p2\n var p3 = deepCopy(p1)\n val p4 = p3!!.partner\n printDetails(p1, p2, p3, p4)\n\n println(\"..or, say, after 2 years have elapsed:-\\n\")\n with (p1) {\n age = 37\n income = 55000.0\n partner = null\n }\n p3 = deepCopy(p1)\n printDetails(p1, null, p3!!, null)\n}"} {"title": "Deming's funnel", "language": "Kotlin from Python", "task": "W Edwards Deming was an American statistician and management guru who used physical demonstrations to illuminate his teachings. In one demonstration Deming repeatedly dropped marbles through a funnel at a target, marking where they landed, and observing the resulting pattern. He applied a sequence of \"rules\" to try to improve performance. In each case the experiment begins with the funnel positioned directly over the target.\n\n* '''Rule 1''': The funnel remains directly above the target.\n* '''Rule 2''': Adjust the funnel position by shifting the target to compensate after each drop. E.g. If the last drop missed 1 cm east, move the funnel 1 cm to the west of its current position.\n* '''Rule 3''': As rule 2, but first move the funnel back over the target, before making the adjustment. E.g. If the funnel is 2 cm north, and the marble lands 3 cm north, move the funnel 3 cm south of the target.\n* '''Rule 4''': The funnel is moved directly over the last place a marble landed.\n\nApply the four rules to the set of 50 pseudorandom displacements provided (e.g in the Racket solution) for the dxs and dys. '''Output''': calculate the mean and standard-deviations of the resulting x and y values for each rule. \n\nNote that rules 2, 3, and 4 give successively worse results. Trying to deterministically compensate for a random process is counter-productive, but -- according to Deming -- quite a popular pastime: see the Further Information, below for examples.\n\n'''Stretch goal 1''': Generate fresh pseudorandom data. The radial displacement of the drop from the funnel position is given by a Gaussian distribution (standard deviation is 1.0) and the angle of displacement is uniformly distributed.\n\n'''Stretch goal 2''': Show scatter plots of all four results.\n\n\n;Further information:\n* Further explanation and interpretation\n* Video demonstration of the funnel experiment at the Mayo Clinic.\n\n", "solution": "// version 1.1.3\n\ntypealias Rule = (Double, Double) -> Double\n\nval dxs = doubleArrayOf(\n -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, 0.275,\n 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001,\n -0.382, 0.161, 0.915, 2.080, -2.337, 0.034, -0.126, 0.014,\n 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047,\n -0.095, 0.695, 0.340, -0.182, 0.287, 0.213, -0.423, -0.021,\n -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315,\n 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181,\n -0.700, -0.361, -0.789, 0.279, -0.174, -0.009, -0.323, -0.658,\n 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774,\n -1.043, 0.051, 0.021, 0.247, -0.310, 0.171, 0.000, 0.106,\n 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, 0.017,\n 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598,\n 0.443, -0.521, -0.799, 0.087\n)\n\nval dys = doubleArrayOf(\n 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395,\n 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000,\n 0.426, 0.205, -0.765, -2.188, -0.742, -0.010, 0.089, 0.208,\n 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096,\n -0.025, -0.868, 1.051, 0.157, 0.216, 0.162, 0.249, -0.007,\n 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226,\n 0.710, 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295,\n 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, 0.217,\n -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219,\n 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, 0.721, 0.104,\n -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477,\n 1.537, -0.901, 0.939, -0.411, 0.341, -0.411, 0.106, 0.224,\n -0.947, -1.424, -0.542, -1.032\n)\n\nfun funnel(da: DoubleArray, rule: Rule): DoubleArray {\n var x = 0.0\n val result = DoubleArray(da.size)\n for ((i, d) in da.withIndex()) {\n result[i] = x + d\n x = rule(x, d)\n }\n return result\n}\n\nfun mean(da: DoubleArray) = da.average()\n\nfun stdDev(da: DoubleArray): Double {\n val m = mean(da)\n return Math.sqrt(da.map { (it - m) * (it - m) }.average())\n}\n\nfun experiment(label: String, rule: Rule) {\n val rxs = funnel(dxs, rule)\n val rys = funnel(dys, rule)\n println(\"$label : x y\")\n println(\"Mean : ${\"%7.4f, %7.4f\".format(mean(rxs), mean(rys))}\")\n println(\"Std Dev : ${\"%7.4f, %7.4f\".format(stdDev(rxs), stdDev(rys))}\")\n println()\n}\n\nfun main(args: Array) {\n experiment(\"Rule 1\") { _, _ -> 0.0 }\n experiment(\"Rule 2\") { _, dz -> -dz }\n experiment(\"Rule 3\") { z, dz -> -(z + dz) }\n experiment(\"Rule 4\") { z, dz -> z + dz }\n}"} {"title": "Department numbers", "language": "Kotlin", "task": "There is a highly organized city that has decided to assign a number to each of their departments:\n::* police department\n::* sanitation department\n::* fire department \n\n\nEach department can have a number between '''1''' and '''7''' (inclusive).\n\nThe three department numbers are to be unique (different from each other) and must add up to '''12'''.\n\nThe Chief of the Police doesn't like odd numbers and wants to have an even number for his department.\n\n\n;Task:\nWrite a computer program which outputs all valid combinations.\n\n\nPossible output (for the 1st and 14th solutions):\n \n --police-- --sanitation-- --fire-- \n 2 3 7 \n 6 5 1\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n println(\"Police Sanitation Fire\")\n println(\"------ ---------- ----\")\n var count = 0\n for (i in 2..6 step 2) {\n for (j in 1..7) {\n if (j == i) continue\n for (k in 1..7) {\n if (k == i || k == j) continue\n if (i + j + k != 12) continue\n println(\" $i $j $k\")\n count++\n }\n }\n }\n println(\"\\n$count valid combinations\")\n}"} {"title": "Detect division by zero", "language": "Kotlin", "task": "Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.\n\n", "solution": "// version 1.1\n\nfun divideByZero(x: Int, y:Int): Boolean =\n try {\n x / y\n false\n } catch(e: ArithmeticException) {\n true\n }\n\nfun main(args: Array) {\n val x = 1\n val y = 0\n if (divideByZero(x, y)) {\n println(\"Attempted to divide by zero\")\n } else {\n @Suppress(\"DIVISION_BY_ZERO\")\n println(\"$x / $y = ${x / y}\")\n }\n}"} {"title": "Determinant and permanent", "language": "Kotlin", "task": "permanent of the matrix.\n\nThe determinant is given by\n:: \\det(A) = \\sum_\\sigma\\sgn(\\sigma)\\prod_{i=1}^n M_{i,\\sigma_i}\nwhile the permanent is given by\n:: \\operatorname{perm}(A)=\\sum_\\sigma\\prod_{i=1}^n M_{i,\\sigma_i}\nIn both cases the sum is over the permutations \\sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.)\n\nMore efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known.\n\n\n;Related task:\n* [[Permutations by swapping]]\n\n", "solution": "// version 1.1.2\n\ntypealias Matrix = Array\n\nfun johnsonTrotter(n: Int): Pair, List> {\n val p = IntArray(n) { it } // permutation\n val q = IntArray(n) { it } // inverse permutation\n val d = IntArray(n) { -1 } // direction = 1 or -1\n var sign = 1\n val perms = mutableListOf()\n val signs = mutableListOf()\n\n fun permute(k: Int) {\n if (k >= n) {\n perms.add(p.copyOf())\n signs.add(sign)\n sign *= -1\n return\n } \n permute(k + 1)\n for (i in 0 until k) {\n val z = p[q[k] + d[k]]\n p[q[k]] = z\n p[q[k] + d[k]] = k\n q[z] = q[k]\n q[k] += d[k]\n permute(k + 1)\n }\n d[k] *= -1\n } \n\n permute(0)\n return perms to signs\n}\n\nfun determinant(m: Matrix): Double {\n val (sigmas, signs) = johnsonTrotter(m.size)\n var sum = 0.0 \n for ((i, sigma) in sigmas.withIndex()) {\n var prod = 1.0\n for ((j, s) in sigma.withIndex()) prod *= m[j][s]\n sum += signs[i] * prod\n }\n return sum\n}\n\nfun permanent(m: Matrix) : Double {\n val (sigmas, _) = johnsonTrotter(m.size)\n var sum = 0.0\n for (sigma in sigmas) {\n var prod = 1.0\n for ((i, s) in sigma.withIndex()) prod *= m[i][s]\n sum += prod\n }\n return sum\n}\n\nfun main(args: Array) {\n val m1 = arrayOf(\n doubleArrayOf(1.0)\n )\n\n val m2 = arrayOf(\n doubleArrayOf(1.0, 2.0),\n doubleArrayOf(3.0, 4.0)\n )\n\n val m3 = arrayOf(\n doubleArrayOf(2.0, 9.0, 4.0),\n doubleArrayOf(7.0, 5.0, 3.0),\n doubleArrayOf(6.0, 1.0, 8.0)\n )\n\n val m4 = arrayOf(\n doubleArrayOf( 1.0, 2.0, 3.0, 4.0),\n doubleArrayOf( 4.0, 5.0, 6.0, 7.0),\n doubleArrayOf( 7.0, 8.0, 9.0, 10.0), \n doubleArrayOf(10.0, 11.0, 12.0, 13.0)\n ) \n\n val matrices = arrayOf(m1, m2, m3, m4)\n for (m in matrices) {\n println(\"m${m.size} -> \")\n println(\" determinant = ${determinant(m)}\")\n println(\" permanent = ${permanent(m)}\\n\")\n } \n}"} {"title": "Determine if a string has all the same characters", "language": "Kotlin from Go", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are the same\n::::* indicate if or which character is different from the previous character\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as all the same character(s)\n::* process the strings from left-to-right\n::* if all the same character, display a message saying such\n::* if not all the same character, then:\n::::* display a message saying such\n::::* display what character is different\n::::* only the 1st different character need be displayed\n::::* display where the different character is in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the different character\n\n\nUse (at least) these seven test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 3 which contains three blanks\n:::* a string of length 1 which contains: '''2'''\n:::* a string of length 3 which contains: '''333'''\n:::* a string of length 3 which contains: '''.55'''\n:::* a string of length 6 which contains: '''tttTTT'''\n:::* a string of length 9 with a blank in the middle: '''4444 444k'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "fun analyze(s: String) {\n println(\"Examining [$s] which has a length of ${s.length}:\")\n if (s.length > 1) {\n val b = s[0]\n for ((i, c) in s.withIndex()) {\n if (c != b) {\n println(\" Not all characters in the string are the same.\")\n println(\" '$c' (0x${Integer.toHexString(c.toInt())}) is different at position $i\")\n return\n }\n }\n }\n println(\" All characters in the string are the same.\")\n}\n\nfun main() {\n val strs = listOf(\"\", \" \", \"2\", \"333\", \".55\", \"tttTTT\", \"4444 444k\")\n for (str in strs) {\n analyze(str)\n }\n}"} {"title": "Determine if a string has all unique characters", "language": "Kotlin from Java", "task": "Given a character string (which may be empty, or have a length of zero characters):\n::* create a function/procedure/routine to:\n::::* determine if all the characters in the string are unique\n::::* indicate if or which character is duplicated and where\n::* display each string and its length (as the strings are being examined)\n::* a zero-length (empty) string shall be considered as unique\n::* process the strings from left-to-right\n::* if unique, display a message saying such\n::* if not unique, then:\n::::* display a message saying such\n::::* display what character is duplicated\n::::* only the 1st non-unique character need be displayed\n::::* display where \"both\" duplicated characters are in the string\n::::* the above messages can be part of a single message\n::::* display the hexadecimal value of the duplicated character\n\n\n\nUse (at least) these five test values (strings):\n:::* a string of length 0 (an empty string)\n:::* a string of length 1 which is a single period ('''.''')\n:::* a string of length 6 which contains: '''abcABC'''\n:::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX'''\n:::* a string of length 36 which ''doesn't'' contain the letter \"oh\":\n:::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ'''\n\n\n\nShow all output here on this page.\n\n\n", "solution": "import java.util.HashMap\n\nfun main() {\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"String\", \"Length\", \"All Unique\", \"1st Diff\", \"Hex\", \"Positions\")\n System.out.printf(\"%-40s %2s %10s %8s %s %s%n\", \"------------------------\", \"------\", \"----------\", \"--------\", \"---\", \"---------\")\n for (s in arrayOf(\"\", \".\", \"abcABC\", \"XYZ ZYX\", \"1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ\")) {\n processString(s)\n }\n}\n\nprivate fun processString(input: String) {\n val charMap: MutableMap = HashMap()\n var dup = 0.toChar()\n var index = 0\n var pos1 = -1\n var pos2 = -1\n for (key in input.toCharArray()) {\n index++\n if (charMap.containsKey(key)) {\n dup = key\n pos1 = charMap[key]!!\n pos2 = index\n break\n }\n charMap[key] = index\n }\n val unique = if (dup.toInt() == 0) \"yes\" else \"no\"\n val diff = if (dup.toInt() == 0) \"\" else \"'$dup'\"\n val hex = if (dup.toInt() == 0) \"\" else Integer.toHexString(dup.toInt()).toUpperCase()\n val position = if (dup.toInt() == 0) \"\" else \"$pos1 $pos2\"\n System.out.printf(\"%-40s %-6d %-10s %-8s %-3s %-5s%n\", input, input.length, unique, diff, hex, position)\n}"} {"title": "Determine if a string is collapsible", "language": "Kotlin from Go", "task": "Determine if a character string is ''collapsible''.\n\nAnd if so, collapse the string (by removing ''immediately repeated'' characters).\n\n\n\nIf a character string has ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nAn ''immediately repeated'' character is any character that is immediately followed by an\nidentical character (or characters). Another word choice could've been ''duplicated character'', but that\nmight have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.}\n\n\n;Examples:\nIn the following character string:\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated\nby underscores (above), even though they (those characters) appear elsewhere in the character string.\n\n\n\nSo, after ''collapsing'' the string, the result would be:\n\n The beter the 4-whel drive, the further you'l be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string:\n\n headmistressship \n\n\nThe \"collapsed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to\nlocate ''repeated'' characters and ''collapse'' (delete) them from the character\nstring. The character string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n string\n number\n ++\n 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln |\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888|\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. |\n 5 | --- Harry S Truman | <###### has many repeated blanks\n +------------------------------------------------------------------------+\n\n\n", "solution": "fun collapse(s: String): String {\n val cs = StringBuilder()\n var last: Char = 0.toChar()\n for (c in s) {\n if (c != last) {\n cs.append(c)\n last = c\n }\n }\n return cs.toString()\n}\n\nfun main() {\n val strings = arrayOf(\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\",\n \"aardvark\"\n )\n for (s in strings) {\n val c = collapse(s)\n println(\"original : length = ${s.length}, string = \u00ab\u00ab\u00ab$s\u00bb\u00bb\u00bb\")\n println(\"collapsed : length = ${c.length}, string = \u00ab\u00ab\u00ab$c\u00bb\u00bb\u00bb\")\n println()\n }\n}"} {"title": "Determine if a string is squeezable", "language": "Kotlin from Java", "task": "Determine if a character string is ''squeezable''.\n\nAnd if so, squeeze the string (by removing any number of\na ''specified'' ''immediately repeated'' character).\n\n\nThis task is very similar to the task '''Determine if a character string is collapsible''' except\nthat only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''.\n\n\nIf a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be\ndeleted (removed), but not the primary (1st) character(s).\n\n\nA specified ''immediately repeated'' character is any specified character that is immediately \nfollowed by an identical character (or characters). Another word choice could've been ''duplicated\ncharacter'', but that might have ruled out (to some readers) triplicated characters *** or more.\n\n\n{This Rosetta Code task was inspired by a newly introduced (as of around\nNovember 2019) '''PL/I''' BIF: '''squeeze'''.}\n\n\n;Examples:\nIn the following character string with a specified ''immediately repeated'' character of '''e''':\n\n\n The better the 4-wheel drive, the further you'll be from help when ya get stuck! \n\n\nOnly the 2nd '''e''' is an specified repeated character, indicated by an underscore\n(above), even though they (the characters) appear elsewhere in the character string.\n\n\n\nSo, after ''squeezing'' the string, the result would be:\n\n The better the 4-whel drive, the further you'll be from help when ya get stuck! \n\n\n\n\nAnother example:\nIn the following character string, using a specified immediately repeated character '''s''':\n\n headmistressship \n\n\nThe \"squeezed\" string would be:\n\n headmistreship \n\n\n\n;Task:\nWrite a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character\nand ''squeeze'' (delete) them from the character string. The\ncharacter string can be processed from either direction.\n\n\nShow all output here, on this page:\n:* the specified repeated character (to be searched for and possibly ''squeezed''):\n:* the original string and its length\n:* the resultant string and its length\n:* the above strings should be \"bracketed\" with '''<<<''' and '''>>>''' (to delineate blanks)\n;* <<<<<>>>>>\n\n\n\nUse (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except\nthe 1st string:\n\n immediately\n string repeated\n number character\n ( | a blank, a minus, a seven, a period)\n ++\n 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero)\n 2 |\"If I were two-faced, would I be wearing this one?\" --- Abraham Lincoln | '-'\n 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7'\n 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.'\n 5 | --- Harry S Truman | (below) <###### has many repeated blanks\n +------------------------------------------------------------------------+ |\n |\n |\n For the 5th string (Truman's signature line), use each of these specified immediately repeated characters:\n * a blank\n * a minus\n * a lowercase '''r'''\n\n\nNote: there should be seven results shown, one each for the 1st four strings, and three results for\nthe 5th string.\n\n\n", "solution": "fun main() {\n val testStrings = arrayOf(\n \"\",\n \"\\\"If I were two-faced, would I be wearing this one?\\\" --- Abraham Lincoln \",\n \"..1111111111111111111111111111111111111111111111111111111111111117777888\",\n \"I never give 'em hell, I just tell the truth, and they think it's hell. \",\n \" --- Harry S Truman \",\n \"122333444455555666666777777788888888999999999\",\n \"The better the 4-wheel drive, the further you'll be from help when ya get stuck!\",\n \"headmistressship\")\n val testChar = arrayOf(\n \" \",\n \"-\",\n \"7\",\n \".\",\n \" -r\",\n \"5\",\n \"e\",\n \"s\")\n for (testNum in testStrings.indices) {\n val s = testStrings[testNum]\n for (c in testChar[testNum].toCharArray()) {\n val result = squeeze(s, c)\n System.out.printf(\"use: '%c'%nold: %2d >>>%s<<<%nnew: %2d >>>%s<<<%n%n\", c, s.length, s, result.length, result)\n }\n }\n}\n\nprivate fun squeeze(input: String, include: Char): String {\n val sb = StringBuilder()\n for (i in input.indices) {\n if (i == 0 || input[i - 1] != input[i] || input[i - 1] == input[i] && input[i] != include) {\n sb.append(input[i])\n }\n }\n return sb.toString()\n}"} {"title": "Determine if two triangles overlap", "language": "Kotlin from C++", "task": "Determining if two triangles in the same plane overlap is an important topic in collision detection.\n\n\n;Task:\nDetermine which of these pairs of triangles overlap in 2D:\n\n:::* (0,0),(5,0),(0,5) and (0,0),(5,0),(0,6)\n:::* (0,0),(0,5),(5,0) and (0,0),(0,5),(5,0)\n:::* (0,0),(5,0),(0,5) and (-10,0),(-5,0),(-1,6)\n:::* (0,0),(5,0),(2.5,5) and (0,4),(2.5,-1),(5,4)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,0),(3,2)\n:::* (0,0),(1,1),(0,2) and (2,1),(3,-2),(3,4)\n\n\nOptionally, see what the result is when only a single corner is in contact (there is no definitive correct answer):\n:::* (0,0),(1,0),(0,1) and (1,0),(2,0),(1,1)\n\n", "solution": "// version 1.1.0\n\ntypealias Point = Pair\n\ndata class Triangle(var p1: Point, var p2: Point, var p3: Point) {\n override fun toString() = \"Triangle: $p1, $p2, $p3\"\n}\n\nfun det2D(t: Triangle): Double {\n val (p1, p2, p3) = t\n return p1.first * (p2.second - p3.second) +\n p2.first * (p3.second - p1.second) +\n p3.first * (p1.second - p2.second)\n}\n\nfun checkTriWinding(t: Triangle, allowReversed: Boolean) {\n val detTri = det2D(t)\n if (detTri < 0.0) {\n if (allowReversed) {\n val a = t.p3\n\t t.p3 = t.p2\n\t t.p2 = a\n }\n else throw RuntimeException(\"Triangle has wrong winding direction\")\n }\n}\n\nfun boundaryCollideChk(t: Triangle, eps: Double) = det2D(t) < eps\n\nfun boundaryDoesntCollideChk(t: Triangle, eps: Double) = det2D(t) <= eps\n\nfun triTri2D(t1: Triangle, t2: Triangle, eps: Double = 0.0,\n allowReversed: Boolean = false, onBoundary: Boolean = true): Boolean {\n // Triangles must be expressed anti-clockwise\n checkTriWinding(t1, allowReversed)\n checkTriWinding(t2, allowReversed)\n // 'onBoundary' determines whether points on boundary are considered as colliding or not\n val chkEdge = if (onBoundary) ::boundaryCollideChk else ::boundaryDoesntCollideChk\n val lp1 = listOf(t1.p1, t1.p2, t1.p3)\n val lp2 = listOf(t2.p1, t2.p2, t2.p3)\n\n // for each edge E of t1\n for (i in 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t2 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n\tif (chkEdge(Triangle(lp1[i], lp1[j], lp2[0]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[1]), eps) &&\n chkEdge(Triangle(lp1[i], lp1[j], lp2[2]), eps)) return false\n }\n\n // for each edge E of t2\n for (i in 0 until 3) {\n val j = (i + 1) % 3\n // Check all points of t1 lay on the external side of edge E.\n // If they do, the triangles do not overlap.\n if (chkEdge(Triangle(lp2[i], lp2[j], lp1[0]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[1]), eps) &&\n chkEdge(Triangle(lp2[i], lp2[j], lp1[2]), eps)) return false\n }\n\n // The triangles overlap\n return true\n}\n\nfun main(args: Array) {\n var t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)\n var t2 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 6.0)\n println(\"$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n // need to allow reversed for this pair to avoid exception\n t1 = Triangle(0.0 to 0.0, 0.0 to 5.0, 5.0 to 0.0)\n t2 = t1\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2, 0.0, true)) \"overlap (reversed)\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 5.0 to 0.0, 0.0 to 5.0)\n t2 = Triangle(-10.0 to 0.0, -5.0 to 0.0, -1.0 to 6.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1.p3 = 2.5 to 5.0\n t2 = Triangle(0.0 to 4.0, 2.5 to -1.0, 5.0 to 4.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 1.0 to 1.0, 0.0 to 2.0)\n t2 = Triangle(2.0 to 1.0, 3.0 to 0.0, 3.0 to 2.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t2 = Triangle(2.0 to 1.0, 3.0 to -2.0, 3.0 to 4.0)\n println(\"\\n$t1 and\\n$t2\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n t1 = Triangle(0.0 to 0.0, 1.0 to 0.0, 0.0 to 1.0)\n t2 = Triangle(1.0 to 0.0, 2.0 to 0.0, 1.0 to 1.1)\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points collide\")\n println(if (triTri2D(t1, t2)) \"overlap\" else \"do not overlap\")\n\n println(\"\\n$t1 and\\n$t2\")\n println(\"which have only a single corner in contact, if boundary points do not collide\")\n println(if (triTri2D(t1, t2, 0.0, false, false)) \"overlap\" else \"do not overlap\")\n}"} {"title": "Dice game probabilities", "language": "Kotlin from C", "task": "Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six.\n\nThey roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player?\n\nLater the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player?\n\nThis task was adapted from the Project Euler Problem n.205:\nhttps://projecteuler.net/problem=205\n\n", "solution": "// version 1.1.2\n\nfun throwDie(nSides: Int, nDice: Int, s: Int, counts: IntArray) {\n if (nDice == 0) {\n counts[s]++\n return\n }\n for (i in 1..nSides) throwDie(nSides, nDice - 1, s + i, counts)\n}\n\nfun beatingProbability(nSides1: Int, nDice1: Int, nSides2: Int, nDice2: Int): Double {\n val len1 = (nSides1 + 1) * nDice1\n val c1 = IntArray(len1) // all elements zero by default\n throwDie(nSides1, nDice1, 0, c1)\n\n val len2 = (nSides2 + 1) * nDice2\n val c2 = IntArray(len2)\n throwDie(nSides2, nDice2, 0, c2)\n\n val p12 = Math.pow(nSides1.toDouble(), nDice1.toDouble()) *\n Math.pow(nSides2.toDouble(), nDice2.toDouble())\n\n var tot = 0.0\n for (i in 0 until len1) {\n for (j in 0 until minOf(i, len2)) {\n tot += c1[i] * c2[j] / p12\n }\n }\n return tot\n}\n\nfun main(args: Array) {\n println(beatingProbability(4, 9, 6, 6))\n println(beatingProbability(10, 5, 7, 6))\n}"} {"title": "Digital root", "language": "Kotlin", "task": "The digital root, X, of a number, n, is calculated:\n: find X as the sum of the digits of n\n: find a new X by summing the digits of X, repeating until X has only one digit.\n\nThe additive persistence is the number of summations required to obtain the single digit. \n\nThe task is to calculate the additive persistence and the digital root of a number, e.g.:\n:627615 has additive persistence 2 and digital root of 9;\n:39390 has additive persistence 2 and digital root of 6;\n:588225 has additive persistence 2 and digital root of 3;\n:393900588225 has additive persistence 2 and digital root of 9;\n\nThe digital root may be calculated in bases other than 10.\n\n\n;See:\n* [[Casting out nines]] for this wiki's use of this procedure.\n* [[Digital root/Multiplicative digital root]]\n* [[Sum digits of an integer]]\n* Digital root sequence on OEIS\n* Additive persistence sequence on OEIS\n* [[Iterated digits squaring]]\n\n", "solution": "// version 1.0.6\n\nfun sumDigits(n: Long): Int = when {\n n < 0L -> throw IllegalArgumentException(\"Negative numbers not allowed\")\n else -> {\n var sum = 0\n var nn = n\n while (nn > 0L) {\n sum += (nn % 10).toInt()\n nn /= 10\n }\n sum\n }\n }\n\nfun digitalRoot(n: Long): Pair = when {\n n < 0L -> throw IllegalArgumentException(\"Negative numbers not allowed\")\n n < 10L -> Pair(n.toInt(), 0)\n else -> {\n var dr = n\n var ap = 0\n while (dr > 9L) {\n dr = sumDigits(dr).toLong()\n ap++\n }\n Pair(dr.toInt(), ap)\n } \n }\n\nfun main(args: Array) {\n val a = longArrayOf(1, 14, 267, 8128, 627615, 39390, 588225, 393900588225)\n for (n in a) {\n val(dr, ap) = digitalRoot(n)\n println(\"${n.toString().padEnd(12)} has additive persistence $ap and digital root of $dr\")\n }\n}"} {"title": "Disarium numbers", "language": "Kotlin", "task": "A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number.\n\n\n;E.G.\n\n'''135''' is a '''Disarium number''':\n\n 11 + 32 + 53 == 1 + 9 + 125 == 135\n\nThere are a finite number of '''Disarium numbers'''.\n\n\n;Task\n\n* Find and display the first 18 '''Disarium numbers'''.\n\n\n;Stretch\n\n* Find and display all 20 '''Disarium numbers'''.\n\n\n;See also\n\n;* Geeks for Geeks - Disarium numbers\n;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...)\n;* Related task: Narcissistic decimal number\n;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''\n\n", "solution": "fun power(n: Int, exp: Int): Int {\n return when {\n exp > 1 -> n * power(n, exp-1)\n exp == 1 -> n\n else -> 1\n }\n}\n\nfun is_disarium(num: Int): Boolean {\n val n = num.toString()\n var sum = 0\n for (i in 1..n.length) {\n sum += power (n[i-1] - '0', i)\n }\n return sum == num\n}\n\nfun main() {\n var i = 0\n var count = 0\n while (count < 19) {\n if (is_disarium(i)) {\n print(\"$i \")\n count++\n }\n i++\n }\n println(\"\")\n}\n"} {"title": "Display a linear combination", "language": "Kotlin", "task": "Display a finite linear combination in an infinite vector basis (e_1, e_2,\\ldots).\n\nWrite a function that, when given a finite list of scalars (\\alpha^1,\\alpha^2,\\ldots), creates a string representing the linear combination \\sum_i\\alpha^i e_i in an explicit format often used in mathematics, that is:\n\n:\\alpha^{i_1}e_{i_1}\\pm|\\alpha^{i_2}|e_{i_2}\\pm|\\alpha^{i_3}|e_{i_3}\\pm\\ldots\n\nwhere \\alpha^{i_k}\\neq 0\n\nThe output must comply to the following rules:\n* don't show null terms, unless the whole combination is null. \n::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong.\n* don't show scalars when they are equal to one or minus one. \n::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong.\n* don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. \n::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong.\n\n\nShow here output for the following lists of scalars:\n\n 1) 1, 2, 3\n 2) 0, 1, 2, 3\n 3) 1, 0, 3, 4\n 4) 1, 2, 0\n 5) 0, 0, 0\n 6) 0\n 7) 1, 1, 1\n 8) -1, -1, -1\n 9) -1, -2, 0, -3\n10) -1\n\n\n", "solution": "// version 1.1.2\n\nfun linearCombo(c: IntArray): String { \n val sb = StringBuilder()\n for ((i, n) in c.withIndex()) {\n if (n == 0) continue\n val op = when {\n n < 0 && sb.isEmpty() -> \"-\"\n n < 0 -> \" - \"\n n > 0 && sb.isEmpty() -> \"\"\n else -> \" + \"\n }\n val av = Math.abs(n)\n val coeff = if (av == 1) \"\" else \"$av*\"\n sb.append(\"$op${coeff}e(${i + 1})\")\n }\n return if(sb.isEmpty()) \"0\" else sb.toString()\n}\n\nfun main(args: Array) { \n val combos = arrayOf(\n intArrayOf(1, 2, 3),\n intArrayOf(0, 1, 2, 3),\n intArrayOf(1, 0, 3, 4),\n intArrayOf(1, 2, 0),\n intArrayOf(0, 0, 0),\n intArrayOf(0),\n intArrayOf(1, 1, 1),\n intArrayOf(-1, -1, -1),\n intArrayOf(-1, -2, 0, -3),\n intArrayOf(-1)\n )\n for (c in combos) {\n println(\"${c.contentToString().padEnd(15)} -> ${linearCombo(c)}\")\n }\n}"} {"title": "Diversity prediction theorem", "language": "Kotlin from TypeScript", "task": "The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert.\n\nWisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. \n\nThus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies.\n\n\nScott E. Page introduced the diversity prediction theorem: \n: ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. \n\n\nTherefore, when the diversity in a group is large, the error of the crowd is small.\n\n\n;Definitions:\n::* Average Individual Error: Average of the individual squared errors\n::* Collective Error: Squared error of the collective prediction\n::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction\n::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then\n:::::: Collective Error = Average Individual Error - Prediction Diversity\n\n;Task:\nFor a given true value and a number of number of estimates (from a crowd), show (here on this page):\n:::* the true value and the crowd estimates\n:::* the average error\n:::* the crowd error\n:::* the prediction diversity\n\n\nUse (at least) these two examples:\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51'''\n:::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42'''\n\n\n\n;Also see:\n:* Wikipedia entry: Wisdom of the crowd\n:* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').\n\n", "solution": "// version 1.1.4-3\n\nfun square(d: Double) = d * d\n\nfun averageSquareDiff(d: Double, predictions: DoubleArray) = \n predictions.map { square(it - d) }.average()\n\nfun diversityTheorem(truth: Double, predictions: DoubleArray): String {\n val average = predictions.average()\n val f = \"%6.3f\"\n return \"average-error : ${f.format(averageSquareDiff(truth, predictions))}\\n\" +\n \"crowd-error : ${f.format(square(truth - average))}\\n\" +\n \"diversity : ${f.format(averageSquareDiff(average, predictions))}\\n\"\n}\n\nfun main(args: Array) {\n println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0)))\n println(diversityTheorem(49.0, doubleArrayOf(48.0, 47.0, 51.0, 42.0)))\n}"} {"title": "Dot product", "language": "Kotlin 1.0+", "task": "Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. \n\nIf possible, make the vectors of arbitrary length.\n\n\nAs an example, compute the dot product of the vectors:\n:::: [1, 3, -5] and \n:::: [4, -2, -1] \n\nIf implementing the dot product of two vectors directly:\n:::* each vector must be the same length\n:::* multiply corresponding terms from each vector\n:::* sum the products (to produce the answer)\n\n\n;Related task:\n* [[Vector products]]\n\n", "solution": "fun dot(v1: Array, v2: Array) =\n v1.zip(v2).map { it.first * it.second }.reduce { a, b -> a + b }\n\nfun main(args: Array) {\n dot(arrayOf(1.0, 3.0, -5.0), arrayOf(4.0, -2.0, -1.0)).let { println(it) }\n}"} {"title": "Draw a clock", "language": "Kotlin from Java", "task": "Draw a clock. \n\n\nMore specific:\n# Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting \"one thousand and one\", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK.\n# The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock.\n# A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task.\n# A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language.\n\n\n;Key points\n* animate simple object\n* timed event \n* polling system resources \n* code clarity\n\n", "solution": "// version 1.1\n\nimport java.awt.*\nimport java.time.LocalTime\nimport javax.swing.*\n\nclass Clock : JPanel() {\n private val degrees06: Float = (Math.PI / 30.0).toFloat()\n private val degrees30: Float = degrees06 * 5.0f\n private val degrees90: Float = degrees30 * 3.0f\n private val size = 590\n private val spacing = 40\n private val diameter = size - 2 * spacing\n private val cx = diameter / 2 + spacing\n private val cy = cx\n\n init {\n preferredSize = Dimension(size, size)\n background = Color.white\n Timer(1000) {\n repaint()\n }.start()\n }\n\n override public fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n drawFace(g)\n val time = LocalTime.now()\n val hour = time.hour\n val minute = time.minute\n val second = time.second\n var angle: Float = degrees90 - degrees06 * second\n drawHand(g, angle, diameter / 2 - 30, Color.red)\n val minsecs: Float = minute + second / 60.0f\n angle = degrees90 - degrees06 * minsecs\n drawHand(g, angle, diameter / 3 + 10, Color.black)\n val hourmins: Float = hour + minsecs / 60.0f\n angle = degrees90 - degrees30 * hourmins\n drawHand(g, angle, diameter / 4 + 10, Color.black)\n }\n\n private fun drawFace(g: Graphics2D) {\n g.stroke = BasicStroke(2.0f)\n g.color = Color.yellow\n g.fillOval(spacing, spacing, diameter, diameter)\n g.color = Color.black\n g.drawOval(spacing, spacing, diameter, diameter)\n }\n\n private fun drawHand(g: Graphics2D, angle: Float, radius: Int, color: Color) {\n val x: Int = cx + (radius.toDouble() * Math.cos(angle.toDouble())).toInt()\n val y: Int = cy - (radius.toDouble() * Math.sin(angle.toDouble())).toInt()\n g.color = color\n g.drawLine(cx, cy, x, y)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Clock\"\n f.isResizable = false\n f.add(Clock(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}"} {"title": "Draw a rotating cube", "language": "Kotlin from Java", "task": "Task\nDraw a rotating cube. \n\nIt should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional.\n\n\n;Related tasks\n* Draw a cuboid\n* write language name in 3D ASCII\n\n", "solution": "// version 1.1\n\nimport java.awt.*\nimport javax.swing.*\n\nclass RotatingCube : JPanel() {\n private val nodes = arrayOf(\n doubleArrayOf(-1.0, -1.0, -1.0),\n doubleArrayOf(-1.0, -1.0, 1.0),\n doubleArrayOf(-1.0, 1.0, -1.0),\n doubleArrayOf(-1.0, 1.0, 1.0),\n doubleArrayOf( 1.0, -1.0, -1.0),\n doubleArrayOf( 1.0, -1.0, 1.0),\n doubleArrayOf( 1.0, 1.0, -1.0),\n doubleArrayOf( 1.0, 1.0, 1.0)\n )\n private val edges = arrayOf(\n intArrayOf(0, 1),\n intArrayOf(1, 3),\n intArrayOf(3, 2),\n intArrayOf(2, 0),\n intArrayOf(4, 5),\n intArrayOf(5, 7),\n intArrayOf(7, 6),\n intArrayOf(6, 4),\n intArrayOf(0, 4),\n intArrayOf(1, 5),\n intArrayOf(2, 6),\n intArrayOf(3, 7)\n )\n\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n scale(100.0)\n rotateCube(Math.PI / 4.0, Math.atan(Math.sqrt(2.0)))\n Timer(17) {\n rotateCube(Math.PI / 180.0, 0.0)\n repaint()\n }.start()\n }\n\n private fun scale(s: Double) {\n for (node in nodes) {\n node[0] *= s\n node[1] *= s\n node[2] *= s\n }\n }\n\n private fun rotateCube(angleX: Double, angleY: Double) {\n val sinX = Math.sin(angleX)\n val cosX = Math.cos(angleX)\n val sinY = Math.sin(angleY)\n val cosY = Math.cos(angleY)\n for (node in nodes) {\n val x = node[0]\n val y = node[1]\n var z = node[2]\n node[0] = x * cosX - z * sinX\n node[2] = z * cosX + x * sinX\n z = node[2]\n node[1] = y * cosY - z * sinY\n node[2] = z * cosY + y * sinY\n }\n }\n\n private fun drawCube(g: Graphics2D) {\n g.translate(width / 2, height / 2)\n for (edge in edges) {\n val xy1 = nodes[edge[0]]\n val xy2 = nodes[edge[1]]\n g.drawLine(Math.round(xy1[0]).toInt(), Math.round(xy1[1]).toInt(),\n Math.round(xy2[0]).toInt(), Math.round(xy2[1]).toInt())\n }\n for (node in nodes) {\n g.fillOval(Math.round(node[0]).toInt() - 4, Math.round(node[1]).toInt() - 4, 8, 8)\n }\n }\n\n override public fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n g.color = Color.blue\n drawCube(g)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Rotating cube\"\n f.isResizable = false\n f.add(RotatingCube(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}"} {"title": "Draw a sphere", "language": "Kotlin from C", "task": "{{requires|Graphics}}\n\n\n;Task:\nDraw a sphere. \n\nThe sphere can be represented graphically, or in ASCII art, depending on the language capabilities. \n\nEither static or rotational projection is acceptable for this task.\n\n\n;Related tasks:\n* draw a cuboid\n* draw a rotating cube\n* write language name in 3D ASCII\n* draw a Deathstar\n\n", "solution": "// version 1.0.6\n\nconst val shades = \".:!*oe&#%@\"\nval light = doubleArrayOf(30.0, 30.0, -50.0)\n\nfun normalize(v: DoubleArray) {\n val len = Math.sqrt(v[0] * v[0] + v[1] * v[1] + v[2] * v[2])\n v[0] /= len; v[1] /= len; v[2] /= len\n}\n\nfun dot(x: DoubleArray, y: DoubleArray): Double {\n val d = x[0] * y[0] + x[1] * y[1] + x[2] * y[2] \n return if (d < 0.0) -d else 0.0\n}\n\nfun drawSphere(r: Double, k: Double, ambient: Double) {\n val vec = DoubleArray(3)\n var intensity: Int\n var b : Double\n var x: Double\n var y: Double\n for (i in Math.floor(-r).toInt() .. Math.ceil(r).toInt()) {\n x = i + 0.5\n for (j in Math.floor(-2.0 * r).toInt() .. Math.ceil(2.0 * r).toInt()) {\n y = j / 2.0 + 0.5\n if (x * x + y * y <= r * r) {\n vec[0] = x\n vec[1] = y\n vec[2] = Math.sqrt(r * r - x * x - y * y) \n normalize(vec)\n b = Math.pow(dot(light, vec), k) + ambient \n intensity = ((1.0 - b) * (shades.length - 1)).toInt() \n if (intensity < 0) intensity = 0 \n if (intensity >= shades.length - 1) intensity = shades.length - 2 \n print(shades[intensity])\n }\n else print(' ')\n }\n println()\n }\n}\n\nfun main(args: Array) {\n normalize(light)\n drawSphere(20.0, 4.0, 0.1)\n drawSphere(10.0, 2.0, 0.4)\n}"} {"title": "Dutch national flag problem", "language": "Kotlin from D", "task": "The Dutch national flag is composed of three coloured bands in the order:\n::* red (top)\n::* then white, and\n::* lastly blue (at the bottom). \n\n\nThe problem posed by Edsger Dijkstra is:\n:Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag.\nWhen the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ...\n\n\n;Task\n# Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''.\n# Sort the balls in a way idiomatic to your language.\n# Check the sorted balls ''are'' in the order of the Dutch national flag.\n\n\n;C.f.:\n* Dutch national flag problem\n* Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)\n\n", "solution": "// version 1.1.4\n\nimport java.util.Random\n\nenum class DutchColors { RED, WHITE, BLUE }\n\nfun Array.swap(i: Int, j: Int) {\n val temp = this[i]\n this[i] = this[j]\n this[j] = temp\n}\n\nfun Array.sort() {\n var lo = 0\n var mid = 0\n var hi = this.lastIndex\n\n while (mid <= hi) {\n when (this[mid]) {\n DutchColors.RED -> this.swap(lo++, mid++)\n DutchColors.WHITE -> mid++\n DutchColors.BLUE -> this.swap(mid, hi--)\n }\n }\n}\n\nfun Array.isSorted(): Boolean {\n return (1 until this.size)\n .none { this[it].ordinal < this[it - 1].ordinal }\n}\n\nconst val NUM_BALLS = 9\n\nfun main(args: Array) {\n val r = Random()\n val balls = Array(NUM_BALLS) { DutchColors.RED }\n val colors = DutchColors.values()\n\n // give balls random colors whilst ensuring they're not already sorted\n do {\n for (i in 0 until NUM_BALLS) balls[i] = colors[r.nextInt(3)]\n }\n while (balls.isSorted())\n\n // print the colors of the balls before sorting\n println(\"Before sorting : ${balls.contentToString()}\")\n\n // sort the balls in DutchColors order\n balls.sort()\n\n // print the colors of the balls after sorting\n println(\"After sorting : ${balls.contentToString()}\")\n}"} {"title": "EKG sequence convergence", "language": "Kotlin from Go", "task": "The sequence is from the natural numbers and is defined by:\n* a(1) = 1; \n* a(2) = Start = 2;\n* for n > 2, a(n) shares at least one prime factor with a(n-1) and is the ''smallest'' such natural number ''not already used''.\n\nThe sequence is called the EKG sequence (after its visual similarity to an electrocardiogram when graphed).\n\nVariants of the sequence can be generated starting 1, N where N is any natural number larger than one. For the purposes of this task let us call: \n* The sequence described above , starting 1, 2, ... the EKG(2) sequence;\n* the sequence starting 1, 3, ... the EKG(3) sequence; \n* ... the sequence starting 1, N, ... the EKG(N) sequence.\n\n\n;Convergence\nIf an algorithm that keeps track of the minimum amount of numbers and their corresponding prime factors used to generate the next term is used, then this may be known as the generators essential '''state'''. Two EKG generators with differing starts can converge to produce the same sequence after initial differences.\nEKG(N1) and EKG(N2) are said to to have converged at and after generation a(c) if state_of(EKG(N1).a(c)) == state_of(EKG(N2).a(c)).\n\n\n;Task:\n# Calculate and show here the first 10 members of EKG(2).\n# Calculate and show here the first 10 members of EKG(5).\n# Calculate and show here the first 10 members of EKG(7).\n# Calculate and show here the first 10 members of EKG(9).\n# Calculate and show here the first 10 members of EKG(10).\n# Calculate and show here at which term EKG(5) and EKG(7) converge ('''stretch goal''').\n\n;Related Tasks:\n# [[Greatest common divisor]]\n# [[Sieve of Eratosthenes]]\n\n;Reference:\n* The EKG Sequence and the Tree of Numbers. (Video).\n\n", "solution": "// Version 1.2.60\n\nfun gcd(a: Int, b: Int): Int {\n var aa = a\n var bb = b\n while (aa != bb) {\n if (aa > bb)\n aa -= bb\n else\n bb -= aa\n }\n return aa\n}\n\nconst val LIMIT = 100\n\nfun main(args: Array) {\n val starts = listOf(2, 5, 7, 9, 10)\n val ekg = Array(5) { IntArray(LIMIT) }\n\n for ((s, start) in starts.withIndex()) {\n ekg[s][0] = 1\n ekg[s][1] = start\n for (n in 2 until LIMIT) {\n var i = 2\n while (true) {\n // a potential sequence member cannot already have been used\n // and must have a factor in common with previous member\n if (!ekg[s].slice(0 until n).contains(i) &&\n gcd(ekg[s][n - 1], i) > 1) {\n ekg[s][n] = i\n break\n }\n i++\n }\n }\n System.out.printf(\"EKG(%2d): %s\\n\", start, ekg[s].slice(0 until 30))\n } \n\n // now compare EKG5 and EKG7 for convergence\n for (i in 2 until LIMIT) {\n if (ekg[1][i] == ekg[2][i] &&\n ekg[1].slice(0 until i).sorted() == ekg[2].slice(0 until i).sorted()) {\n println(\"\\nEKG(5) and EKG(7) converge at term ${i + 1}\")\n return\n }\n }\n println(\"\\nEKG5(5) and EKG(7) do not converge within $LIMIT terms\")\n}"} {"title": "Eban numbers", "language": "Kotlin from Go", "task": "Definition:\nAn '''eban''' number is a number that has no letter '''e''' in it when the number is spelled in English.\n\nOr more literally, spelled numbers that contain the letter '''e''' are banned.\n\n\nThe American version of spelling numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\nOnly numbers less than '''one sextillion''' ('''1021''') will be considered in/for this task.\n\nThis will allow optimizations to be used.\n\n\n\n;Task:\n:::* show all eban numbers <= '''1,000''' (in a horizontal format), and a count\n:::* show all eban numbers between '''1,000''' and '''4,000''' (inclusive), and a count\n:::* show a count of all eban numbers up and including '''10,000'''\n:::* show a count of all eban numbers up and including '''100,000'''\n:::* show a count of all eban numbers up and including '''1,000,000'''\n:::* show a count of all eban numbers up and including '''10,000,000'''\n:::* show all output here.\n\n\n;See also:\n:* The MathWorld entry: eban numbers.\n:* The OEIS entry: A6933, eban numbers.\n:* [[Number names]].\n\n", "solution": "// Version 1.3.21\n\ntypealias Range = Triple\n\nfun main() {\n val rgs = listOf(\n Range(2, 1000, true),\n Range(1000, 4000, true),\n Range(2, 10_000, false),\n Range(2, 100_000, false),\n Range(2, 1_000_000, false),\n Range(2, 10_000_000, false),\n Range(2, 100_000_000, false),\n Range(2, 1_000_000_000, false)\n )\n for (rg in rgs) {\n val (start, end, prnt) = rg\n if (start == 2) {\n println(\"eban numbers up to and including $end:\")\n } else {\n println(\"eban numbers between $start and $end (inclusive):\")\n }\n var count = 0\n for (i in start..end step 2) {\n val b = i / 1_000_000_000\n var r = i % 1_000_000_000\n var m = r / 1_000_000\n r = i % 1_000_000\n var t = r / 1_000\n r %= 1_000\n if (m >= 30 && m <= 66) m %= 10\n if (t >= 30 && t <= 66) t %= 10\n if (r >= 30 && r <= 66) r %= 10\n if (b == 0 || b == 2 || b == 4 || b == 6) {\n if (m == 0 || m == 2 || m == 4 || m == 6) {\n if (t == 0 || t == 2 || t == 4 || t == 6) {\n if (r == 0 || r == 2 || r == 4 || r == 6) {\n if (prnt) print(\"$i \")\n count++\n }\n }\n }\n }\n }\n if (prnt) println()\n println(\"count = $count\\n\")\n }\n}"} {"title": "Eertree", "language": "Kotlin from Python", "task": "An '''eertree''' is a data structure designed for efficient processing of certain palindrome tasks, for instance counting the number of sub-palindromes in an input string. \n\nThe data structure has commonalities to both ''tries'' and ''suffix trees''.\n See links below. \n\n\n;Task:\nConstruct an eertree for the string \"eertree\", then output all sub-palindromes by traversing the tree.\n\n\n;See also:\n* Wikipedia entry: trie.\n* Wikipedia entry: suffix tree \n* Cornell University Library, Computer Science, Data Structures and Algorithms ---> EERTREE: An Efficient Data Structure for Processing Palindromes in Strings.\n\n", "solution": "// version 1.1.4\n\nclass Node {\n val edges = mutableMapOf() // edges (or forward links)\n var link: Node? = null // suffix link (backward links)\n var len = 0 // the length of the node\n}\n\nclass Eertree(str: String) {\n val nodes = mutableListOf()\n\n private val rto = Node() // odd length root node, or node -1\n private val rte = Node() // even length root node, or node 0\n private val s = StringBuilder(\"0\") // accumulated input string, T = S[1..i]\n private var maxSufT = rte // maximum suffix of tree T\n\n init {\n // Initialize and build the tree\n rte.link = rto\n rto.link = rte\n rto.len = -1\n rte.len = 0\n for (ch in str) add(ch)\n }\n\n private fun getMaxSuffixPal(startNode: Node, a: Char): Node {\n // We traverse the suffix-palindromes of T in the order of decreasing length.\n // For each palindrome we read its length k and compare T[i-k] against a\n // until we get an equality or arrive at the -1 node.\n var u = startNode\n val i = s.length\n var k = u.len\n while (u !== rto && s[i - k - 1] != a) {\n if (u === u.link!!) throw RuntimeException(\"Infinite loop detected\")\n u = u.link!!\n k = u.len\n }\n return u\n }\n\n private fun add(a: Char): Boolean {\n // We need to find the maximum suffix-palindrome P of Ta\n // Start by finding maximum suffix-palindrome Q of T.\n // To do this, we traverse the suffix-palindromes of T\n // in the order of decreasing length, starting with maxSuf(T)\n val q = getMaxSuffixPal(maxSufT, a)\n\n // We check Q to see whether it has an outgoing edge labeled by a.\n val createANewNode = a !in q.edges.keys\n\n if (createANewNode) {\n // We create the node P of length Q + 2\n val p = Node()\n nodes.add(p)\n p.len = q.len + 2\n if (p.len == 1) {\n // if P = a, create the suffix link (P, 0)\n p.link = rte\n }\n else {\n // It remains to create the suffix link from P if |P|>1. Just\n // continue traversing suffix-palindromes of T starting with the\n // the suffix link of Q.\n p.link = getMaxSuffixPal(q.link!!, a).edges[a]\n }\n\n // create the edge (Q, P)\n q.edges[a] = p\n }\n\n // P becomes the new maxSufT\n maxSufT = q.edges[a]!!\n\n // Store accumulated input string\n s.append(a)\n\n return createANewNode\n }\n\n fun getSubPalindromes(): List {\n // Traverse tree to find sub-palindromes\n val result = mutableListOf()\n // Odd length words\n getSubPalindromes(rto, listOf(rto), \"\", result)\n // Even length words\n getSubPalindromes(rte, listOf(rte), \"\", result)\n return result\n }\n\n private fun getSubPalindromes(nd: Node, nodesToHere: List,\n charsToHere: String, result: MutableList) {\n // Each node represents a palindrome, which can be reconstructed\n // by the path from the root node to each non-root node.\n\n // Traverse all edges, since they represent other palindromes\n for ((lnkName, nd2) in nd.edges) {\n getSubPalindromes(nd2, nodesToHere + nd2, charsToHere + lnkName, result)\n }\n\n // Reconstruct based on charsToHere characters.\n if (nd !== rto && nd !== rte) { // Don't print for root nodes\n val assembled = charsToHere.reversed() +\n if (nodesToHere[0] === rte) // Even string\n charsToHere\n else // Odd string\n charsToHere.drop(1)\n result.add(assembled)\n }\n }\n}\n\nfun main(args: Array) {\n val str = \"eertree\"\n println(\"Processing string '$str'\")\n val eertree = Eertree(str)\n println(\"Number of sub-palindromes: ${eertree.nodes.size}\")\n val result = eertree.getSubPalindromes()\n println(\"Sub-palindromes: $result\")\n}"} {"title": "Egyptian division", "language": "Kotlin", "task": "Egyptian division is a method of dividing integers using addition and \ndoubling that is similar to the algorithm of [[Ethiopian multiplication]]\n\n'''Algorithm:'''\n\nGiven two numbers where the '''dividend''' is to be divided by the '''divisor''':\n\n# Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column.\n# Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order.\n# Continue with successive i'th rows of 2^i and 2^i * divisor.\n# Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend.\n# We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator'''\n# Consider each row of the table, in the ''reverse'' order of its construction.\n# If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer.\n# When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend).\n\n\n'''Example: 580 / 34'''\n\n''' Table creation: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n|-\n| 1\n| 34\n|-\n| 2\n| 68\n|-\n| 4\n| 136\n|-\n| 8\n| 272\n|-\n| 16\n| 544\n|}\n\n''' Initialization of sums: '''\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| 16\n| 544\n|\n\n|\n\n|-\n|\n|\n| 0\n| 0\n|}\n\n''' Considering table rows, bottom-up: '''\n\nWhen a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations.\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n| 16\n| 544\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n| 16\n| 544\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n| 16\n| 544\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| 1\n| 34\n|\n\n|\n\n|-\n| 2\n| 68\n| 16\n| 544\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n::: {| class=\"wikitable\"\n! powers_of_2\n! doublings\n! answer\n! accumulator\n|-\n| '''1'''\n| '''34'''\n| 17\n| 578\n|-\n| 2\n| 68\n|\n\n|\n\n|-\n| 4\n| 136\n|\n\n|\n\n|-\n| 8\n| 272\n|\n\n|\n\n|-\n| '''16'''\n| '''544'''\n|\n\n|\n\n|}\n\n;Answer:\nSo 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''.\n\n\n;Task:\nThe task is to create a function that does Egyptian division. The function should\nclosely follow the description above in using a list/array of powers of two, and\nanother of doublings.\n\n* Functions should be clear interpretations of the algorithm.\n* Use the function to divide 580 by 34 and show the answer '''here, on this page'''.\n\n\n;Related tasks:\n:* Egyptian fractions\n\n\n;References:\n:* Egyptian Number System\n\n", "solution": "// version 1.1.4\n\ndata class DivMod(val quotient: Int, val remainder: Int)\n\nfun egyptianDivide(dividend: Int, divisor: Int): DivMod {\n require (dividend >= 0 && divisor > 0)\n if (dividend < divisor) return DivMod(0, dividend)\n val powersOfTwo = mutableListOf(1)\n val doublings = mutableListOf(divisor)\n var doubling = divisor\n while (true) {\n doubling *= 2\n if (doubling > dividend) break\n powersOfTwo.add(powersOfTwo[powersOfTwo.lastIndex] * 2)\n doublings.add(doubling)\n }\n var answer = 0\n var accumulator = 0\n for (i in doublings.size - 1 downTo 0) {\n if (accumulator + doublings[i] <= dividend) {\n accumulator += doublings[i]\n answer += powersOfTwo[i]\n if (accumulator == dividend) break\n }\n }\n return DivMod(answer, dividend - accumulator)\n}\n\nfun main(args: Array) {\n val dividend = 580\n val divisor = 34\n val (quotient, remainder) = egyptianDivide(dividend, divisor)\n println(\"$dividend divided by $divisor is $quotient with remainder $remainder\")\n}"} {"title": "Elementary cellular automaton", "language": "Kotlin from C++", "task": "An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits.\n\nThe rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101.\n\n\n;Task:\nCreate a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice.\n\nThe space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally.\n\nThis task is basically a generalization of [[one-dimensional cellular automata]].\n\n\n;See also\n* Cellular automata (natureofcode.com)\n\n", "solution": "// version 1.1.51\n\nimport java.util.BitSet\n\nconst val SIZE = 32\nconst val LINES = SIZE / 2\nconst val RULE = 90\n\nfun ruleTest(x: Int) = (RULE and (1 shl (7 and x))) != 0\n\ninfix fun Boolean.shl(bitCount: Int) = (if (this) 1 else 0) shl bitCount\n\nfun Boolean.toInt() = if (this) 1 else 0\n\nfun evolve(s: BitSet) {\n val t = BitSet(SIZE) // all false by default\n t[SIZE - 1] = ruleTest((s[0] shl 2) or (s[SIZE - 1] shl 1) or s[SIZE - 2].toInt())\n t[0] = ruleTest((s[1] shl 2) or (s[0] shl 1) or s[SIZE - 1].toInt())\n for (i in 1 until SIZE - 1) {\n t[i] = ruleTest((s[i + 1] shl 2) or (s[i] shl 1) or s[i - 1].toInt())\n }\n for (i in 0 until SIZE) s[i] = t[i]\n}\n\nfun show(s: BitSet) {\n for (i in SIZE - 1 downTo 0) print(if (s[i]) \"*\" else \" \")\n println()\n}\n\nfun main(args: Array) {\n var state = BitSet(SIZE)\n state.set(LINES)\n println(\"Rule $RULE:\")\n repeat(LINES) {\n show(state)\n evolve(state)\n }\n}"} {"title": "Elementary cellular automaton/Infinite length", "language": "Kotlin from C++", "task": "The purpose of this task is to create a version of an [[Elementary cellular automaton]] whose number of cells is only limited by the memory size of the computer.\n\nTo be precise, consider the state of the automaton to be made of an infinite number of cells, but with a bounded support. In other words, to describe the state of the automaton, you need a finite number of adjacent cells, along with their individual state, and you then consider that the individual state of each of all other cells is the negation of the closest individual cell among the previously defined finite number of cells.\n\nExamples:\n\n\n1 -> ..., 0, 0, 1, 0, 0, ...\n0, 1 -> ..., 1, 1, 0, 1, 0, 0, ...\n1, 0, 1 -> ..., 0, 0, 1, 0, 1, 0, 0, ...\n\n\nMore complex methods can be imagined, provided it is possible to somehow encode the infinite sections. But for this task we will stick to this simple version.\n\n", "solution": "// version 1.1.51\n\nfun evolve(l: Int, rule: Int) {\n println(\" Rule #$rule:\")\n var cells = StringBuilder(\"*\")\n for (x in 0 until l) {\n addNoCells(cells)\n val width = 40 + (cells.length shr 1)\n println(cells.padStart(width))\n cells = step(cells, rule)\n }\n}\n\nfun step(cells: StringBuilder, rule: Int): StringBuilder {\n val newCells = StringBuilder()\n for (i in 0 until cells.length - 2) {\n var bin = 0\n var b = 2\n for (n in i until i + 3) {\n bin += (if (cells[n] == '*') 1 else 0) shl b\n b = b shr 1\n }\n val a = if ((rule and (1 shl bin)) != 0) '*' else '.'\n newCells.append(a)\n }\n return newCells\n}\n\nfun addNoCells(s: StringBuilder) {\n val l = if (s[0] == '*') '.' else '*'\n val r = if (s[s.length - 1] == '*') '.' else '*'\n repeat(2) {\n s.insert(0, l)\n s.append(r)\n }\n}\n\nfun main(args: Array) {\n evolve(35, 90)\n println()\n}"} {"title": "Elementary cellular automaton/Random number generator", "language": "Kotlin from C", "task": "Mathematica software for its default random number generator.\n\nSteven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state.\n\nThe purpose of this task is to demonstrate this. With the code written in the most significant.\n\nYou can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language.\n\nFor extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic.\n\n;Reference:\n* Cellular automata: Is Rule 30 random? (PDF).\n\n\n", "solution": "// version 1.1.51\n\nconst val N = 64\n\nfun pow2(x: Int) = 1L shl x\n\nfun evolve(state: Long, rule: Int) {\n var state2 = state\n for (p in 0..9) {\n var b = 0\n for (q in 7 downTo 0) {\n val st = state2\n b = (b.toLong() or ((st and 1L) shl q)).toInt()\n state2 = 0L\n for (i in 0 until N) {\n val t = ((st ushr (i - 1)) or (st shl (N + 1 - i)) and 7L).toInt()\n if ((rule.toLong() and pow2(t)) != 0L) state2 = state2 or pow2(i)\n }\n }\n print(\" $b\")\n }\n println()\n}\n\nfun main(args: Array) {\n evolve(1, 30)\n}"} {"title": "Elliptic curve arithmetic", "language": "Kotlin from C", "task": "digital signatures. \n\nThe purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. \n\nIn a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve:\n\n:::: y^2 = x^3 + a x + b\n\n'''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. \n\nFor this particular task, we'll use the following parameters:\n\n:::: a=0, b=7 \n\nThe most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. \n\nTo do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have:\n\n:::: P + Q + R = 0 \n\nHere '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. \n\nWe'll also assume here that this infinity point is unique and defines the neutral element of the addition.\n\nThis was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such:\n\nGiven any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned.\n\nConsidering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet).\n\n'''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis.\n\nThe task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. \n\nYou will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven.\n\n''Hint'': You might need to define a \"doubling\" function, that returns '''P+P''' for any given point '''P'''.\n\n''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a \"multiply\" function that returns, \nfor any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).\n\n", "solution": "// version 1.1.4\n\nconst val C = 7\n\nclass Pt(val x: Double, val y: Double) {\n val zero get() = Pt(Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY)\n\n val isZero get() = x > 1e20 || x < -1e20\n\n fun dbl(): Pt {\n if (isZero) return this\n val l = 3.0 * x * x / (2.0 * y)\n val t = l * l - 2.0 * x\n return Pt(t, l * (x - t) - y)\n }\n\n operator fun unaryMinus() = Pt(x, -y)\n\n operator fun plus(other: Pt): Pt {\n if (x == other.x && y == other.y) return dbl()\n if (isZero) return other\n if (other.isZero) return this\n val l = (other.y - y) / (other.x - x)\n val t = l * l - x - other.x\n return Pt(t, l * (x - t) - y)\n }\n\n operator fun times(n: Int): Pt {\n var r: Pt = zero\n var p = this\n var i = 1\n while (i <= n) {\n if ((i and n) != 0) r += p\n p = p.dbl()\n i = i shl 1\n }\n return r\n }\n\n override fun toString() =\n if (isZero) \"Zero\" else \"(${\"%.3f\".format(x)}, ${\"%.3f\".format(y)})\"\n}\n\nfun Double.toPt() = Pt(Math.cbrt(this * this - C), this)\n\nfun main(args: Array) {\n val a = 1.0.toPt()\n val b = 2.0.toPt()\n val c = a + b\n val d = -c\n println(\"a = $a\")\n println(\"b = $b\")\n println(\"c = a + b = $c\")\n println(\"d = -c = $d\")\n println(\"c + d = ${c + d}\")\n println(\"a + b + d = ${a + b + d}\")\n println(\"a * 12345 = ${a * 12345}\")\n}"} {"title": "Empty directory", "language": "Kotlin", "task": "Starting with a path to some directory, determine whether the directory is empty.\n\nAn empty directory contains no files nor subdirectories. \nWith [[Unix]] or [[Windows]] systems, every directory contains an entry for \".\" and almost every directory contains \"..\" (except for a root directory); an empty directory contains no other entries.\n\n", "solution": "// version 1.1.4\n\nimport java.io.File\n\nfun main(args: Array) {\n val dirPath = \"docs\" // or whatever\n val isEmpty = (File(dirPath).list().isEmpty())\n println(\"$dirPath is ${if (isEmpty) \"empty\" else \"not empty\"}\")\n}"} {"title": "Empty string", "language": "Kotlin", "task": "Languages may have features for dealing specifically with empty strings \n(those containing no characters).\n\n\n;Task:\n::* Demonstrate how to assign an empty string to a variable.\n::* Demonstrate how to check that a string is empty.\n::* Demonstrate how to check that a string is not empty.\n\n\n\n", "solution": "fun main(args: Array) {\n val s = \"\"\n println(s.isEmpty()) // true\n println(s.isNotEmpty()) // false\n println(s.length) // 0\n println(s.none()) // true\n println(s.any()) // false\n}"} {"title": "Entropy/Narcissist", "language": "Kotlin", "task": "Write a computer program that computes and shows its own [[entropy]].\n\n\n;Related Tasks: \n:* [[Fibonacci_word]]\n:* [[Entropy]]\n\n", "solution": "// version 1.1.0 (entropy_narc.kt)\n\nfun log2(d: Double) = Math.log(d) / Math.log(2.0)\n\nfun shannon(s: String): Double {\n val counters = mutableMapOf() \n for (c in s) {\n if (counters.containsKey(c)) counters[c] = counters[c]!! + 1\n else counters.put(c, 1)\n }\n val nn = s.length.toDouble()\n var sum = 0.0\n for (key in counters.keys) { \n val term = counters[key]!! / nn\n sum += term * log2(term)\n }\n return -sum\n}\n\nfun main(args: Array) {\n val prog = java.io.File(\"entropy_narc.kt\").readText()\n println(\"This program's entropy is ${\"%18.16f\".format(shannon(prog))}\")\n}"} {"title": "Equilibrium index", "language": "Kotlin", "task": "An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. \n\n\nFor example, in a sequence A:\n\n::::: A_0 = -7\n::::: A_1 = 1\n::::: A_2 = 5\n::::: A_3 = 2\n::::: A_4 = -4\n::::: A_5 = 3\n::::: A_6 = 0\n\n3 is an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6\n\n6 is also an equilibrium index, because:\n\n::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0\n\n(sum of zero elements is zero) \n\n7 is not an equilibrium index, because it is not a valid index of sequence A.\n\n\n;Task;\nWrite a function that, given a sequence, returns its equilibrium indices (if any).\n\nAssume that the sequence may be very long.\n\n", "solution": "// version 1.1\n\nfun equilibriumIndices(a: IntArray): MutableList {\n val ei = mutableListOf()\n if (a.isEmpty()) return ei // empty list\n val sumAll = a.sumBy { it }\n var sumLeft = 0\n var sumRight: Int\n for (i in 0 until a.size) {\n sumRight = sumAll - sumLeft - a[i]\n if (sumLeft == sumRight) ei.add(i)\n sumLeft += a[i]\n }\n return ei\n}\n\nfun main(args: Array) {\n val a = intArrayOf(-7, 1, 5, 2, -4, 3, 0)\n val ei = equilibriumIndices(a)\n when (ei.size) {\n 0 -> println(\"There are no equilibrium indices\")\n 1 -> println(\"The only equilibrium index is : ${ei[0]}\")\n else -> println(\"The equilibrium indices are : ${ei.joinToString(\", \")}\")\n }\n}"} {"title": "Esthetic numbers", "language": "Kotlin from D", "task": "An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1.\n\n\n;E.G.\n\n:* '''12''' is an esthetic number. One and two differ by 1.\n\n:* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour.\n\n:* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9.\n\n\nThese examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros.\n\nEsthetic numbers are also sometimes referred to as stepping numbers.\n\n\n;Task\n\n:* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base.\n\n:* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.)\n\n:* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''.\n\n:* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''.\n\n\n;Related task:\n* numbers with equal rises and falls\n\n\n;See also:\n:;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1\n:;*Numbers Aplenty - Esthetic numbers\n:;*Geeks for Geeks - Stepping numbers\n\n", "solution": "import kotlin.math.abs\n\nfun isEsthetic(n: Long, b: Long): Boolean {\n if (n == 0L) {\n return false\n }\n var i = n % b\n var n2 = n / b\n while (n2 > 0) {\n val j = n2 % b\n if (abs(i - j) != 1L) {\n return false\n }\n n2 /= b\n i = j\n }\n return true\n}\n\nfun listEsths(n: Long, n2: Long, m: Long, m2: Long, perLine: Int, all: Boolean) {\n val esths = mutableListOf()\n fun dfs(n: Long, m: Long, i: Long) {\n if (i in n..m) {\n esths.add(i)\n }\n if (i == 0L || i > m) {\n return\n }\n val d = i % 10\n val i1 = i * 10 + d - 1\n val i2 = i1 + 2\n when (d) {\n 0L -> {\n dfs(n, m, i2)\n }\n 9L -> {\n dfs(n, m, i1)\n }\n else -> {\n dfs(n, m, i1)\n dfs(n, m, i2)\n }\n }\n }\n\n for (i in 0L until 10L) {\n dfs(n2, m2, i)\n }\n\n val le = esths.size\n println(\"Base 10: $le esthetic numbers between $n and $m:\")\n if (all) {\n for (c_esth in esths.withIndex()) {\n print(\"${c_esth.value} \")\n if ((c_esth.index + 1) % perLine == 0) {\n println()\n }\n }\n println()\n } else {\n for (i in 0 until perLine) {\n print(\"${esths[i]} \")\n }\n println()\n println(\"............\")\n for (i in le - perLine until le) {\n print(\"${esths[i]} \")\n }\n println()\n }\n println()\n}\n\nfun main() {\n for (b in 2..16) {\n println(\"Base $b: ${4 * b}th to ${6 * b}th esthetic numbers:\")\n var n = 1L\n var c = 0L\n while (c < 6 * b) {\n if (isEsthetic(n, b.toLong())) {\n c++\n if (c >= 4 * b) {\n print(\"${n.toString(b)} \")\n }\n }\n n++\n }\n println()\n }\n println()\n\n // the following all use the obvious range limitations for the numbers in question\n listEsths(1000, 1010, 9999, 9898, 16, true);\n listEsths(1e8.toLong(), 101_010_101, 13 * 1e7.toLong(), 123_456_789, 9, true);\n listEsths(1e11.toLong(), 101_010_101_010, 13 * 1e10.toLong(), 123_456_789_898, 7, false);\n listEsths(1e14.toLong(), 101_010_101_010_101, 13 * 1e13.toLong(), 123_456_789_898_989, 5, false);\n listEsths(1e17.toLong(), 101_010_101_010_101_010, 13 * 1e16.toLong(), 123_456_789_898_989_898, 4, false);\n}"} {"title": "Euler's identity", "language": "Kotlin", "task": "{{Wikipedia|Euler's_identity}}\n\n\nIn mathematics, ''Euler's identity'' is the equality:\n\n ei\\pi + 1 = 0\n\nwhere\n\n e is Euler's number, the base of natural logarithms,\n ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and\n \\pi is pi, the ratio of the circumference of a circle to its diameter.\n\nEuler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants:\n\n The number 0.\n The number 1.\n The number \\pi (\\pi = 3.14159+),\n The number e (e = 2.71828+), which occurs widely in mathematical analysis.\n The number ''i'', the imaginary unit of the complex numbers.\n\n;Task\nShow in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. \n\nMost languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. \n\nIf that is the case, or there is some other limitation, show \nthat ei\\pi + 1 is ''approximately'' equal to zero and \nshow the amount of error in the calculation.\n\nIf your language is capable of symbolic calculations, show \nthat ei\\pi + 1 is ''exactly'' equal to zero for bonus kudos points.\n\n", "solution": "// Version 1.2.40\n\nimport kotlin.math.sqrt\nimport kotlin.math.PI\n\nconst val EPSILON = 1.0e-16\nconst val SMALL_PI = '\\u03c0'\nconst val APPROX_EQUALS = '\\u2245'\n\nclass Complex(val real: Double, val imag: Double) {\n operator fun plus(other: Complex) =\n Complex(real + other.real, imag + other.imag)\n\n operator fun times(other: Complex) = Complex(\n real * other.real - imag * other.imag,\n real * other.imag + imag * other.real\n )\n\n fun inv(): Complex {\n val denom = real * real + imag * imag\n return Complex(real / denom, -imag / denom)\n }\n\n operator fun unaryMinus() = Complex(-real, -imag)\n\n operator fun minus(other: Complex) = this + (-other)\n\n operator fun div(other: Complex) = this * other.inv()\n\n val modulus: Double get() = sqrt(real * real + imag * imag)\n\n override fun toString() =\n if (imag >= 0.0) \"$real + ${imag}i\"\n else \"$real - ${-imag}i\"\n}\n\nfun main(args: Array) {\n var fact = 1.0\n val x = Complex(0.0, PI)\n var e = Complex(1.0, PI)\n var n = 2\n var pow = x\n do {\n val e0 = e\n fact *= n++\n pow *= x\n e += pow / Complex(fact, 0.0)\n }\n while ((e - e0).modulus >= EPSILON)\n e += Complex(1.0, 0.0)\n println(\"e^${SMALL_PI}i + 1 = $e $APPROX_EQUALS 0\")\n}"} {"title": "Euler's sum of powers conjecture", "language": "Kotlin", "task": "There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin.\n\nThis conjecture is called Euler's sum of powers conjecture and can be stated as such:\n\n:At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk.\n\nIn 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250.\n\nThe task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here.\n\nRelated tasks are:\n* [[Pythagorean quadruples]]. \n* [[Pythagorean triples]].\n\n\n\n", "solution": "fun main(args: Array) {\n val p5 = LongArray(250){ it.toLong() * it * it * it * it }\n var sum: Long\n var y: Int\n var found = false\n loop@ for (x0 in 0 .. 249)\n for (x1 in 0 .. x0 - 1)\n for (x2 in 0 .. x1 - 1)\n for (x3 in 0 .. x2 - 1) {\n sum = p5[x0] + p5[x1] + p5[x2] + p5[x3]\n y = p5.binarySearch(sum)\n if (y >= 0) {\n println(\"$x0^5 + $x1^5 + $x2^5 + $x3^5 = $y^5\")\n found = true\n break@loop\n }\n }\n if (!found) println(\"No solution was found\")\n}"} {"title": "Even or odd", "language": "Kotlin", "task": "Test whether an integer is even or odd.\n\nThere is more than one way to solve this task:\n\n* Use the even and odd predicates, if the language provides them.\n* Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd.\n* Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd.\n* Use modular congruences:\n** ''i'' 0 (mod 2) iff ''i'' is even.\n** ''i'' 1 (mod 2) iff ''i'' is odd.\n\n", "solution": "// version 1.0.5-2\n\nfun main(args: Array) {\n while (true) {\n print(\"Enter an integer or 0 to finish : \")\n val n = readLine()!!.toInt()\n when {\n n == 0 -> return\n n % 2 == 0 -> println(\"Your number is even\")\n else -> println(\"Your number is odd\")\n }\n }\n}"} {"title": "Evolutionary algorithm", "language": "Kotlin", "task": "Starting with:\n* The target string: \"METHINKS IT IS LIKE A WEASEL\".\n* An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent).\n* A fitness function that computes the 'closeness' of its argument to the target string.\n* A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated.\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n:* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others.\n:* repeat until the parent converges, (hopefully), to the target.\n\n\n;See also:\n* Wikipedia entry: Weasel algorithm.\n* Wikipedia entry: Evolutionary algorithm.\n\n\nNote: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions\n\nA cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically,\n* While the parent is not yet the target:\n:* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate.\n\nNote that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of \"converges\"\n\n (:* repeat until the parent converges, (hopefully), to the target.\n\nStrictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent!\n\nAs illustration of this error, the code for 8th has the following remark.\n\n Create a new string based on the TOS, '''changing randomly any characters which\n don't already match the target''':\n\n''NOTE:'' this has been changed, the 8th version is completely random now\n\nClearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters!\n\nTo ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.\n\n", "solution": "import java.util.*\n\nval target = \"METHINKS IT IS LIKE A WEASEL\"\nval validChars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ \"\n\nval random = Random()\n\nfun randomChar() = validChars[random.nextInt(validChars.length)]\nfun hammingDistance(s1: String, s2: String) =\n s1.zip(s2).map { if (it.first == it.second) 0 else 1 }.sum()\n\nfun fitness(s1: String) = target.length - hammingDistance(s1, target)\n\nfun mutate(s1: String, mutationRate: Double) =\n s1.map { if (random.nextDouble() > mutationRate) it else randomChar() }\n .joinToString(separator = \"\")\n\nfun main(args: Array) {\n val initialString = (0 until target.length).map { randomChar() }.joinToString(separator = \"\")\n\n println(initialString)\n println(mutate(initialString, 0.2))\n\n val mutationRate = 0.05\n val childrenPerGen = 50\n\n var i = 0\n var currVal = initialString\n while (currVal != target) {\n i += 1\n currVal = (0..childrenPerGen).map { mutate(currVal, mutationRate) }.maxBy { fitness(it) }!!\n }\n println(\"Evolution found target after $i generations\")\n}"} {"title": "Execute Brain****", "language": "Kotlin from Groovy", "task": "Brainf***}}\nRCBF is a set of [[Brainf*** compilers and interpreters written for Rosetta Code in a variety of languages. \n\nBelow are links to each of the versions of RCBF.\n\nAn implementation need only properly implement the following instructions:\n{| class=\"wikitable\"\n!Command\n!Description\n|-\n| style=\"text-align:center\"| > || Move the pointer to the right\n|-\n| style=\"text-align:center\"| < || Move the pointer to the left\n|-\n| style=\"text-align:center\"| + || Increment the memory cell under the pointer\n|-\n| style=\"text-align:center\"| - || Decrement the memory cell under the pointer\n|-\n| style=\"text-align:center\"| . || Output the character signified by the cell at the pointer\n|-\n| style=\"text-align:center\"| , || Input a character and store it in the cell at the pointer\n|-\n| style=\"text-align:center\"| [ || Jump past the matching ] if the cell under the pointer is 0\n|-\n| style=\"text-align:center\"| ] || Jump back to the matching [ if the cell under the pointer is nonzero\n|}\nAny cell size is allowed, EOF (End-O-File) support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "// version 1.1.2\n\nclass Brainf__k(val prog: String, memSize: Int) {\n private val mem = IntArray(memSize)\n private var ip = 0\n private var dp = 0\n private val memVal get() = mem.getOrElse(dp) { 0 }\n\n fun execute() {\n while (ip < prog.length) {\n when (prog[ip++]) {\n '>' -> dp++\n '<' -> dp--\n '+' -> mem[dp] = memVal + 1\n '-' -> mem[dp] = memVal - 1\n ',' -> mem[dp] = System.`in`.read()\n '.' -> print(memVal.toChar())\n '[' -> handleLoopStart()\n ']' -> handleLoopEnd()\n }\n }\n }\n\n private fun handleLoopStart() {\n if (memVal != 0) return\n var depth = 1\n while (ip < prog.length) {\n when (prog[ip++]) {\n '[' -> depth++\n ']' -> if (--depth == 0) return\n }\n }\n throw IllegalStateException(\"Could not find matching end bracket\")\n }\n\n private fun handleLoopEnd() {\n var depth = 0\n while (ip >= 0) {\n when (prog[--ip]) {\n ']' -> depth++\n '[' -> if (--depth == 0) return\n }\n }\n throw IllegalStateException(\"Could not find matching start bracket\")\n }\n}\n\nfun main(args: Array) {\n val prog = \"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.\"\n Brainf__k(prog, 10).execute()\n}"} {"title": "Execute HQ9+", "language": "Kotlin", "task": "Implement a ''' [[HQ9+]] ''' interpreter or compiler.\n\n", "solution": "// version 1.1.3\n\nfun hq9plus(code: String) {\n var acc = 0\n val sb = StringBuilder()\n for (c in code) {\n sb.append(\n when (c) {\n 'h', 'H' -> \"Hello, world!\\n\"\n 'q', 'Q' -> code + \"\\n\"\n '9'-> {\n val sb2 = StringBuilder()\n for (i in 99 downTo 1) {\n val s = if (i > 1) \"s\" else \"\"\n sb2.append(\"$i bottle$s of beer on the wall\\n\")\n sb2.append(\"$i bottle$s of beer\\n\")\n sb2.append(\"Take one down, pass it around\\n\")\n }\n sb2.append(\"No more bottles of beer on the wall!\\n\")\n sb2.toString()\n }\n '+' -> { acc++; \"\" } // yeah, it's weird!\n else -> throw IllegalArgumentException(\"Code contains illegal operation '$c'\")\n }\n )\n }\n println(sb)\n}\n\nfun main(args: Array) {\n val code = args[0] // pass in code as command line argument (using hq9+)\n hq9plus(code)\n}"} {"title": "Execute SNUSP", "language": "Kotlin from Go", "task": "SNUSP}}'''RCSNUSP''' is a set of [[SNUSP compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCSNUSP.\n\nAn implementation need only properly implement the Core SNUSP instructions ('$', '\\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.\n\n", "solution": "// version 1.1.2\n\n// requires 5 chars (10 bytes) of data store\nconst val hw = \"\"\"\n/++++!/===========?\\>++.>+.+++++++..+++\\\n\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./\n$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\\n \\==-<<<<+>+++/ /=.>.+>.--------.-/\"\"\"\n\n// input is a multi-line string.\nfun snusp(dlen: Int, raw: String) {\n val ds = CharArray(dlen) // data store\n var dp = 0 // data pointer\n var s = raw\n\n // remove leading '\\n' from string if present\n s = s.trimStart('\\n')\n\n // make 2 dimensional instruction store and declare instruction pointers\n val cs = s.split('\\n')\n var ipr = 0\n var ipc = 0\n\n // look for starting instruction\n findStart@ for ((r, row) in cs.withIndex()) {\n for ((i, c) in row.withIndex()) {\n if (c == '$') {\n ipr = r\n ipc = i\n break@findStart\n }\n }\n }\n\n var id = 0\n val step = fun() {\n if (id and 1 == 0)\n ipc += 1 - (id and 2)\n else\n ipr += 1 - (id and 2)\n }\n\n // execute\n while ((ipr in 0 until cs.size) && (ipc in 0 until cs[ipr].length)) {\n when (cs[ipr][ipc]) {\n '>' -> dp++\n '<' -> dp--\n '+' -> ds[dp]++\n '-' -> ds[dp]--\n '.' -> print(ds[dp])\n ',' -> ds[dp] = readLine()!![0]\n '/' -> id = id.inv()\n '\\\\' -> id = id xor 1\n '!' -> step()\n '?' -> if (ds[dp] == '\\u0000') step()\n }\n step()\n }\n}\n\nfun main(args: Array) {\n snusp(5, hw)\n}"} {"title": "Exponentiation order", "language": "Kotlin", "task": "This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents.\n\n(Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.)\n\n\n;Task requirements\nShow the result of a language's evaluation of multiple exponentiation (either as an integer or floating point).\n\nIf your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it.\n\n\nUsing whatever operator or syntax your language supports (if any), show the results in three lines (with identification):\n \n::::* 5**3**2 \n::::* (5**3)**2\n::::* 5**(3**2)\n\n\nIf there are other methods (or formats) of multiple exponentiations, show them as well. \n\n\n;See also:\n* MathWorld entry: exponentiation\n\n\n;Related tasks:\n* exponentiation operator\n* arbitrary-precision integers (included)\n* [[Exponentiation with infix operators in (or operating on) the base]]\n\n", "solution": "// version 1.0.5-2\n\ninfix fun Int.ipow(exp: Int): Int = when {\n exp < 0 -> throw IllegalArgumentException(\"negative exponents not allowed\")\n exp == 0 -> 1\n else -> {\n var ans = 1\n var base = this\n var e = exp\n while(e != 0) {\n if (e and 1 == 1) ans *= base\n e = e shr 1\n base *= base\n }\n ans\n }\n} \n\nfun main(args: Array) {\n println(\"5**3**2 = ${5 ipow 3 ipow 2}\") \n println(\"(5**3)**2 = ${(5 ipow 3) ipow 2}\")\n println(\"5**(3**2) = ${5 ipow (3 ipow 2)}\")\n}"} {"title": "Extend your language", "language": "Kotlin", "task": "{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.\n\nIf your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:\n\nOccasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are \"true\"). In a C-like language this could look like the following:\n\n if (condition1isTrue) {\n if (condition2isTrue)\n bothConditionsAreTrue();\n else\n firstConditionIsTrue();\n }\n else if (condition2isTrue)\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nBesides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.\n\nThis can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:\n\n if2 (condition1isTrue) (condition2isTrue)\n bothConditionsAreTrue();\n else1\n firstConditionIsTrue();\n else2\n secondConditionIsTrue();\n else\n noConditionIsTrue();\n\nPick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.\n", "solution": "// version 1.0.6\n\ndata class IfBoth(val cond1: Boolean, val cond2: Boolean) {\n fun elseFirst(func: () -> Unit): IfBoth {\n if (cond1 && !cond2) func()\n return this\n }\n\n fun elseSecond(func: () -> Unit): IfBoth {\n if (cond2 && !cond1) func()\n return this\n }\n\n fun elseNeither(func: () -> Unit): IfBoth { \n if (!cond1 && !cond2) func()\n return this // in case it's called out of order\n }\n}\n\nfun ifBoth(cond1: Boolean, cond2: Boolean, func: () -> Unit): IfBoth {\n if (cond1 && cond2) func()\n return IfBoth(cond1, cond2)\n}\n\nfun main(args: Array) {\n var a = 0\n var b = 1\n ifBoth (a == 1, b == 3) {\n println(\"a = 1 and b = 3\")\n }\n .elseFirst {\n println(\"a = 1 and b <> 3\") \n }\n .elseSecond {\n println(\"a <> 1 and b = 3\") \n }\n .elseNeither {\n println(\"a <> 1 and b <> 3\") \n }\n\n // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order\n a = 1\n b = 0\n ifBoth (a == 1, b == 3) {\n println(\"a = 1 and b = 3\")\n }\n .elseNeither {\n println(\"a <> 1 and b <> 3\") \n }\n .elseFirst {\n println(\"a = 1 and b <> 3\") \n }\n}"} {"title": "Extreme floating point values", "language": "Kotlin", "task": "The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.\n\nThe task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. \n\nPrint the values of these variables if possible; and show some arithmetic with these values and variables. \n\nIf your language can directly enter these extreme floating point values then show it.\n\n\n;See also:\n* What Every Computer Scientist Should Know About Floating-Point Arithmetic\n\n\n;Related tasks:\n* [[Infinity]]\n* [[Detect division by zero]]\n* [[Literals/Floating point]]\n\n", "solution": "// version 1.0.5-2\n\n@Suppress(\"DIVISION_BY_ZERO\", \"FLOAT_LITERAL_CONFORMS_ZERO\")\n\nfun main(args: Array) {\n val inf = 1.0 / 0.0\n val negInf = -1.0 / 0.0\n val nan = 0.0 / 0.0\n val negZero = -1.0e-325\n\n println(\"*** Indirect ***\\n\")\n println(\"Infinity : $inf\")\n println(\"Negative infinity : $negInf\")\n println(\"Not a number : $nan\")\n println(\"Negative zero : $negZero\")\n\n println(\"\\n*** Direct ***\\n\")\n println(\"Infinity : ${Double.POSITIVE_INFINITY}\")\n println(\"Negative infinity : ${Double.NEGATIVE_INFINITY}\")\n println(\"Not a number : ${Double.NaN}\")\n println(\"Negative zero : ${-0.0}\")\n\n println(\"\\n*** Calculations ***\\n\")\n println(\"inf * inf : ${inf * inf}\")\n println(\"inf + negInf : ${inf + negInf}\")\n println(\"nan / nan : ${nan / nan}\")\n println(\"negZero + 0.0 : ${negZero + 0.0}\")\n}"} {"title": "FASTA format", "language": "Kotlin from FreeBASIC", "task": "In FASTA. \n\nA FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.\n\n\n;Task:\nWrite a program that reads a FASTA file such as:\n\n>Rosetta_Example_1\nTHERECANBENOSPACE\n>Rosetta_Example_2\nTHERECANBESEVERAL\nLINESBUTTHEYALLMUST\nBECONCATENATED\n\n", "solution": "// version 1.1.2\n\nimport java.util.Scanner\nimport java.io.File\n\nfun checkNoSpaces(s: String) = ' ' !in s && '\\t' !in s\n\nfun main(args: Array) {\n var first = true\n val sc = Scanner(File(\"input.fasta\"))\n while (sc.hasNextLine()) {\n val line = sc.nextLine()\n if (line[0] == '>') {\n if (!first) println()\n print(\"${line.substring(1)}: \")\n if (first) first = false\n }\n else if (first) {\n println(\"Error : File does not begin with '>'\")\n break\n }\n else if (checkNoSpaces(line))\n print(line)\n else {\n println(\"\\nError : Sequence contains space(s)\")\n break\n }\n }\n sc.close()\n}"} {"title": "Fairshare between two and more", "language": "Kotlin from Visual Basic .NET", "task": "The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people\ntake turns in the given order, the first persons turn for every '0' in the\nsequence, the second for every '1'; then this is shown to give a fairer, more\nequitable sharing of resources. (Football penalty shoot-outs for example, might\nnot favour the team that goes first as much if the penalty takers take turns\naccording to the Thue-Morse sequence and took 2^n penalties)\n\nThe Thue-Morse sequence of ones-and-zeroes can be generated by:\n:''\"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence\"''\n\n\n;Sharing fairly between two or more:\nUse this method:\n:''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.''\n\n\n;Task\nCounting from zero; using a function/method/routine to express an integer count in base '''b''',\nsum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people.\n\n\nShow the first 25 terms of the fairshare sequence:\n:* For two people:\n:* For three people\n:* For five people\n:* For eleven people\n\n\n;Related tasks: \n:* [[Non-decimal radices/Convert]]\n:* [[Thue-Morse]]\n\n\n;See also:\n:* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))\n\n", "solution": "fun turn(base: Int, n: Int): Int {\n var sum = 0\n var n2 = n\n while (n2 != 0) {\n val re = n2 % base\n n2 /= base\n sum += re\n }\n return sum % base\n}\n\nfun fairShare(base: Int, count: Int) {\n print(String.format(\"Base %2d:\", base))\n for (i in 0 until count) {\n val t = turn(base, i)\n print(String.format(\" %2d\", t))\n }\n println()\n}\n\nfun turnCount(base: Int, count: Int) {\n val cnt = IntArray(base) { 0 }\n for (i in 0 until count) {\n val t = turn(base, i)\n cnt[t]++\n }\n\n var minTurn = Int.MAX_VALUE\n var maxTurn = Int.MIN_VALUE\n var portion = 0\n for (i in 0 until base) {\n val num = cnt[i]\n if (num > 0) {\n portion++\n }\n if (num < minTurn) {\n minTurn = num\n }\n if (num > maxTurn) {\n maxTurn = num\n }\n }\n\n print(\" With $base people: \")\n when (minTurn) {\n 0 -> {\n println(\"Only $portion have a turn\")\n }\n maxTurn -> {\n println(minTurn)\n }\n else -> {\n println(\"$minTurn or $maxTurn\")\n }\n }\n}\n\nfun main() {\n fairShare(2, 25)\n fairShare(3, 25)\n fairShare(5, 25)\n fairShare(11, 25)\n\n println(\"How many times does each get a turn in 50000 iterations?\")\n turnCount(191, 50000)\n turnCount(1377, 50000)\n turnCount(49999, 50000)\n turnCount(50000, 50000)\n turnCount(50001, 50000)\n}\n"} {"title": "Farey sequence", "language": "Kotlin", "task": "The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size.\n\nThe ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. \n\n\nEach Farey sequence:\n:::* starts with the value '''0''' (zero), denoted by the fraction \\frac{0}{1} \n:::* ends with the value '''1''' (unity), denoted by the fraction \\frac{1}{1}.\n\n\nThe Farey sequences of orders '''1''' to '''5''' are:\n\n:::: {\\bf\\it{F}}_1 = \\frac{0}{1}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_2 = \\frac{0}{1}, \\frac{1}{2}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_3 = \\frac{0}{1}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_4 = \\frac{0}{1}, \\frac{1}{4}, \\frac{1}{3}, \\frac{1}{2}, \\frac{2}{3}, \\frac{3}{4}, \\frac{1}{1}\n:\n:::: {\\bf\\it{F}}_5 = \\frac{0}{1}, \\frac{1}{5}, \\frac{1}{4}, \\frac{1}{3}, \\frac{2}{5}, \\frac{1}{2}, \\frac{3}{5}, \\frac{2}{3}, \\frac{3}{4}, \\frac{4}{5}, \\frac{1}{1}\n\n;Task\n* Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive).\n* Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds.\n* Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). \n\n\nThe length (the number of fractions) of a Farey sequence asymptotically approaches:\n\n::::::::::: 3 x n2 / \\pi2 \n\n;See also:\n* OEIS sequence A006842 numerators of Farey series of order 1, 2, *** \n* OEIS sequence A006843 denominators of Farey series of order 1, 2, *** \n* OEIS sequence A005728 number of fractions in Farey series of order n \n* MathWorld entry Farey sequence\n* Wikipedia entry Farey sequence\n\n", "solution": "// version 1.1\n\nfun farey(n: Int): List {\n var a = 0\n var b = 1\n var c = 1\n var d = n\n val f = mutableListOf(\"$a/$b\")\n while (c <= n) {\n val k = (n + b) / d\n val aa = a\n val bb = b\n a = c\n b = d\n c = k * c - aa\n d = k * d - bb\n f.add(\"$a/$b\")\n }\n return f.toList()\n}\n\nfun main(args: Array) {\n for (i in 1..11)\n println(\"${\"%2d\".format(i)}: ${farey(i).joinToString(\" \")}\")\n println()\n for (i in 100..1000 step 100)\n println(\"${\"%4d\".format(i)}: ${\"%6d\".format(farey(i).size)} fractions\")\n}"} {"title": "Fast Fourier transform", "language": "Kotlin", "task": "Calculate the FFT (Fast Fourier Transform) of an input sequence.\n\nThe most general case allows for complex numbers at the input \nand results in a sequence of equal length, again of complex numbers. \nIf you need to restrict yourself to real numbers, the output should \nbe the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. \n\nThe classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. \nFurther optimizations are possible but not required.\n\n", "solution": "object FFT {\n fun fft(a: Array) = _fft(a, Complex(0.0, 2.0), 1.0)\n fun rfft(a: Array) = _fft(a, Complex(0.0, -2.0), 2.0)\n\n private fun _fft(a: Array, direction: Complex, scalar: Double): Array =\n if (a.size == 1)\n a\n else {\n val n = a.size\n require(n % 2 == 0, { \"The Cooley-Tukey FFT algorithm only works when the length of the input is even.\" })\n\n var (evens, odds) = Pair(emptyArray(), emptyArray())\n for (i in a.indices)\n if (i % 2 == 0) evens += a[i]\n else odds += a[i]\n evens = _fft(evens, direction, scalar)\n odds = _fft(odds, direction, scalar)\n\n val pairs = (0 until n / 2).map {\n val offset = (direction * (java.lang.Math.PI * it / n)).exp * odds[it] / scalar\n val base = evens[it] / scalar\n Pair(base + offset, base - offset)\n }\n var (left, right) = Pair(emptyArray(), emptyArray())\n for ((l, r) in pairs) { left += l; right += r }\n left + right\n }\n}"} {"title": "Feigenbaum constant calculation", "language": "Kotlin from Ring", "task": "Calculate the Feigenbaum constant. \n\n\n;See:\n:* Details in the Wikipedia article: Feigenbaum constant.\n\n", "solution": "// Version 1.2.40\n\nfun feigenbaum() {\n val maxIt = 13\n val maxItJ = 10\n var a1 = 1.0\n var a2 = 0.0\n var d1 = 3.2\n println(\" i d\")\n for (i in 2..maxIt) {\n var a = a1 + (a1 - a2) / d1\n for (j in 1..maxItJ) {\n var x = 0.0\n var y = 0.0\n for (k in 1..(1 shl i)) {\n y = 1.0 - 2.0 * y * x\n x = a - x * x\n }\n a -= x / y\n }\n val d = (a1 - a2) / (a - a1)\n println(\"%2d %.8f\".format(i,d))\n d1 = d\n a2 = a1\n a1 = a\n }\n}\n\nfun main(args: Array) {\n feigenbaum()\n}"} {"title": "Fibonacci n-step number sequences", "language": "Kotlin", "task": "These number series are an expansion of the ordinary [[Fibonacci sequence]] where:\n# For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2\n# For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3\n# For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4...\n# For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \\sum_{i=1}^{(n)} {F_{k-i}^{(n)}}\n\nFor small values of n, Greek numeric prefixes are sometimes used to individually name each series.\n\n:::: {| style=\"text-align: left;\" border=\"4\" cellpadding=\"2\" cellspacing=\"2\"\n|+ Fibonacci n-step sequences\n|- style=\"background-color: rgb(255, 204, 255);\"\n! n !! Series name !! Values\n|-\n| 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...\n|-\n| 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...\n|-\n| 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...\n|-\n| 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...\n|-\n| 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...\n|-\n| 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...\n|-\n| 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...\n|-\n| 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...\n|-\n| 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...\n|}\n\nAllied sequences can be generated where the initial values are changed:\n: '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values.\n\n\n\n;Task:\n# Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.\n# Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.\n\n\n;Related tasks:\n* [[Fibonacci sequence]]\n* Wolfram Mathworld\n* [[Hofstadter Q sequence]]\n* [[Leonardo numbers]]\n\n\n;Also see:\n* Lucas Numbers - Numberphile (Video)\n* Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)\n* Wikipedia, Lucas number\n* MathWorld, Fibonacci Number\n* Some identities for r-Fibonacci numbers\n* OEIS Fibonacci numbers\n* OEIS Lucas numbers\n\n", "solution": "// version 1.1.2\n\nfun fibN(initial: IntArray, numTerms: Int) : IntArray {\n val n = initial.size\n require(n >= 2 && numTerms >= 0)\n val fibs = initial.copyOf(numTerms)\n if (numTerms <= n) return fibs\n for (i in n until numTerms) {\n var sum = 0\n for (j in i - n until i) sum += fibs[j]\n fibs[i] = sum\n }\n return fibs\n}\n\nfun main(args: Array) {\n val names = arrayOf(\"fibonacci\", \"tribonacci\", \"tetranacci\", \"pentanacci\", \"hexanacci\",\n \"heptanacci\", \"octonacci\", \"nonanacci\", \"decanacci\")\n val initial = intArrayOf(1, 1, 2, 4, 8, 16, 32, 64, 128, 256)\n println(\" n name values\")\n var values = fibN(intArrayOf(2, 1), 15).joinToString(\", \")\n println(\"%2d %-10s %s\".format(2, \"lucas\", values))\n for (i in 0..8) {\n values = fibN(initial.sliceArray(0 until i + 2), 15).joinToString(\", \")\n println(\"%2d %-10s %s\".format(i + 2, names[i], values))\n }\n}"} {"title": "Fibonacci word", "language": "Kotlin", "task": "The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:\n\n Define F_Word1 as '''1'''\n Define F_Word2 as '''0'''\n Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01'''\n Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2\n\n\n;Task:\nPerform the above steps for n = 37.\n\nYou may display the first few but not the larger values of n.\n{Doing so will get the task's author into trouble with them what be (again!).} \n\nInstead, create a table for F_Words '''1''' to '''37''' which shows:\n::* The number of characters in the word\n::* The word's [[Entropy]]\n\n\n;Related tasks: \n* Fibonacci word/fractal\n* [[Entropy]]\n* [[Entropy/Narcissist]]\n\n", "solution": "// version 1.0.6\n\nfun fibWord(n: Int): String {\n if (n < 1) throw IllegalArgumentException(\"Argument can't be less than 1\")\n if (n == 1) return \"1\"\n val words = Array(n){ \"\" }\n words[0] = \"1\"\n words[1] = \"0\"\n for (i in 2 until n) words[i] = words[i - 1] + words[i - 2]\n return words[n - 1]\n}\n\nfun log2(d: Double) = Math.log(d) / Math.log(2.0)\n\nfun shannon(s: String): Double {\n if (s.length <= 1) return 0.0\n val count0 = s.count { it == '0' }\n val count1 = s.length - count0\n val nn = s.length.toDouble()\n return -(count0 / nn * log2(count0 / nn) + count1 / nn * log2(count1 / nn))\n}\n\nfun main(args: Array) {\n println(\"N Length Entropy Word\")\n println(\"-- -------- ------------------ ----------------------------------\")\n for (i in 1..37) {\n val s = fibWord(i)\n print(String.format(\"%2d %8d %18.16f\", i, s.length, shannon(s)))\n if (i < 10) println(\" $s\")\n else println()\n }\n}"} {"title": "File extension is in extensions list", "language": "Kotlin", "task": "Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''.\n\nIt also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid.\n\nFor these reasons, this task exists in addition to the [[Extract file extension]] task.\n\n\n;Related tasks: \n* [[Extract file extension]]\n* [[String matching]]\n\n", "solution": "// version 1.1\n\n/* implicitly allows for extensions containing dots */\nfun String.isFileExtensionListed(extensions: List): Boolean {\n return extensions.any { toLowerCase().endsWith(\".\" + it.toLowerCase()) }\n}\n\nfun main(args: Array) {\n val extensions = listOf(\"zip\", \"rar\", \"7z\", \"gz\", \"archive\", \"A##\", \"tar.bz2\")\n val fileNames = listOf(\n \"MyData.a##\",\n \"MyData.tar.Gz\",\n \"MyData.gzip\",\n \"MyData.7z.backup\",\n \"MyData...\",\n \"MyData\",\n \"MyData_v1.0.tar.bz2\",\n \"MyData_v1.0.bz2\"\n )\n\n for (fileName in fileNames) {\n println(\"${fileName.padEnd(19)} -> ${fileName.isFileExtensionListed(extensions)}\")\n }\n}"} {"title": "File size distribution", "language": "Kotlin", "task": "Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy.\n\n\nMy suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant.\n\nDon't forget that empty files may exist, to serve as a marker.\n\n\nIs your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?\n\n", "solution": "// version 1.2.10\n\nimport java.io.File\nimport kotlin.math.log10\nimport kotlin.math.floor\n\nfun fileSizeDistribution(path: String) {\n val sizes = IntArray(12)\n val p = File(path)\n val files = p.walk()\n var accessible = 0\n var notAccessible = 0\n var totalSize = 0L\n for (file in files) {\n try {\n if (file.isFile()) {\n val len = file.length()\n accessible++\n if (len == 0L) {\n sizes[0]++\n continue\n }\n totalSize += len\n val logLen = log10(len.toDouble())\n val index = floor(logLen).toInt()\n sizes[index + 1]++\n }\n }\n catch (se: SecurityException) {\n notAccessible++\n }\n }\n\n println(\"File size distribution for '$path' :-\\n\")\n for (i in 0 until sizes.size) {\n print(if (i == 0) \" \" else \"+ \")\n print(\"Files less than 10 ^ ${\"%-2d\".format(i)} bytes : \")\n println(\"%5d\".format(sizes[i]))\n }\n println(\" -----\")\n println(\"= Number of accessible files : ${\"%5d\".format(accessible)}\")\n println(\"\\n Total size in bytes : $totalSize\")\n println(\"\\n Number of inaccessible files : ${\"%5d\".format(notAccessible)}\")\n}\n\nfun main(args: Array) {\n fileSizeDistribution(\"./\") // current directory\n}"} {"title": "Find if a point is within a triangle", "language": "Kotlin from Java", "task": "Find if a point is within a triangle.\n\n\n;Task:\n \n::* Assume points are on a plane defined by (x, y) real number coordinates.\n\n::* Given a point P(x, y) and a triangle formed by points A, B, and C, determine if P is within triangle ABC. \n\n::* You may use any algorithm. \n\n::* Bonus: explain why the algorithm you chose works.\n\n\n;Related tasks:\n* [[Determine_if_two_triangles_overlap]]\n\n\n;Also see:\n:* Discussion of several methods. [[http://totologic.blogspot.com/2014/01/accurate-point-in-triangle-test.html]]\n:* Determine if a point is in a polygon [[https://en.wikipedia.org/wiki/Point_in_polygon]]\n:* Triangle based coordinate systems [[https://en.wikipedia.org/wiki/Barycentric_coordinate_system]]\n:* Wolfram entry [[https://mathworld.wolfram.com/TriangleInterior.html]]\n\n", "solution": "import kotlin.math.max\nimport kotlin.math.min\n\nprivate const val EPS = 0.001\nprivate const val EPS_SQUARE = EPS * EPS\n\nprivate fun test(t: Triangle, p: Point) {\n println(t)\n println(\"Point $p is within triangle ? ${t.within(p)}\")\n}\n\nfun main() {\n var p1 = Point(1.5, 2.4)\n var p2 = Point(5.1, -3.1)\n var p3 = Point(-3.8, 1.2)\n var tri = Triangle(p1, p2, p3)\n test(tri, Point(0.0, 0.0))\n test(tri, Point(0.0, 1.0))\n test(tri, Point(3.0, 1.0))\n println()\n p1 = Point(1.0 / 10, 1.0 / 9)\n p2 = Point(100.0 / 8, 100.0 / 3)\n p3 = Point(100.0 / 4, 100.0 / 9)\n tri = Triangle(p1, p2, p3)\n val pt = Point(p1.x + 3.0 / 7 * (p2.x - p1.x), p1.y + 3.0 / 7 * (p2.y - p1.y))\n test(tri, pt)\n println()\n p3 = Point(-100.0 / 8, 100.0 / 6)\n tri = Triangle(p1, p2, p3)\n test(tri, pt)\n}\n\nclass Point(val x: Double, val y: Double) {\n override fun toString(): String {\n return \"($x, $y)\"\n }\n}\n\nclass Triangle(private val p1: Point, private val p2: Point, private val p3: Point) {\n private fun pointInTriangleBoundingBox(p: Point): Boolean {\n val xMin = min(p1.x, min(p2.x, p3.x)) - EPS\n val xMax = max(p1.x, max(p2.x, p3.x)) + EPS\n val yMin = min(p1.y, min(p2.y, p3.y)) - EPS\n val yMax = max(p1.y, max(p2.y, p3.y)) + EPS\n return !(p.x < xMin || xMax < p.x || p.y < yMin || yMax < p.y)\n }\n\n private fun nativePointInTriangle(p: Point): Boolean {\n val checkSide1 = side(p1, p2, p) >= 0\n val checkSide2 = side(p2, p3, p) >= 0\n val checkSide3 = side(p3, p1, p) >= 0\n return checkSide1 && checkSide2 && checkSide3\n }\n\n private fun distanceSquarePointToSegment(p1: Point, p2: Point, p: Point): Double {\n val p1P2SquareLength = (p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)\n val dotProduct = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / p1P2SquareLength\n if (dotProduct < 0) {\n return (p.x - p1.x) * (p.x - p1.x) + (p.y - p1.y) * (p.y - p1.y)\n }\n if (dotProduct <= 1) {\n val pP1SquareLength = (p1.x - p.x) * (p1.x - p.x) + (p1.y - p.y) * (p1.y - p.y)\n return pP1SquareLength - dotProduct * dotProduct * p1P2SquareLength\n }\n return (p.x - p2.x) * (p.x - p2.x) + (p.y - p2.y) * (p.y - p2.y)\n }\n\n private fun accuratePointInTriangle(p: Point): Boolean {\n if (!pointInTriangleBoundingBox(p)) {\n return false\n }\n if (nativePointInTriangle(p)) {\n return true\n }\n if (distanceSquarePointToSegment(p1, p2, p) <= EPS_SQUARE) {\n return true\n }\n return if (distanceSquarePointToSegment(p2, p3, p) <= EPS_SQUARE) {\n true\n } else distanceSquarePointToSegment(p3, p1, p) <= EPS_SQUARE\n }\n\n fun within(p: Point): Boolean {\n return accuratePointInTriangle(p)\n }\n\n override fun toString(): String {\n return \"Triangle[$p1, $p2, $p3]\"\n }\n\n companion object {\n private fun side(p1: Point, p2: Point, p: Point): Double {\n return (p2.y - p1.y) * (p.x - p1.x) + (-p2.x + p1.x) * (p.y - p1.y)\n }\n }\n}"} {"title": "Find limit of recursion", "language": "Kotlin", "task": "{{selection|Short Circuit|Console Program Basics}}\n\n \n\n\n;Task:\nFind the limit of recursion.\n\n", "solution": "// version 1.1.2\n\nfun recurse(i: Int) {\n try {\n recurse(i + 1)\n }\n catch(e: StackOverflowError) {\n println(\"Limit of recursion is $i\")\n }\n}\n\nfun main(args: Array) = recurse(0)"} {"title": "Find palindromic numbers in both binary and ternary bases", "language": "Kotlin from FreeBASIC", "task": "* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'':\n:::* base 2\n:::* base 3\n* Display '''0''' (zero) as the first number found, even though some other definitions ignore it.\n* Optionally, show the decimal number found in its binary and ternary form.\n* Show all output here.\n\n\nIt's permissible to assume the first two numbers and simply list them.\n\n\n;See also\n* Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.\n\n", "solution": "// version 1.0.5-2\n\n/** converts decimal 'n' to its ternary equivalent */\nfun Long.toTernaryString(): String = when {\n this < 0L -> throw IllegalArgumentException(\"negative numbers not allowed\")\n this == 0L -> \"0\"\n else -> {\n var result = \"\"\n var n = this\n while (n > 0) {\n result += n % 3\n n /= 3\n }\n result.reversed()\n }\n}\n\n/** wraps java.lang.Long.toBinaryString in a Kotlin extension function */\nfun Long.toBinaryString(): String = java.lang.Long.toBinaryString(this)\n\n/** check if a binary or ternary numeric string 's' is palindromic */\nfun isPalindromic(s: String): Boolean = (s == s.reversed())\n\n/** print a number which is both a binary and ternary palindrome in all three bases */\nfun printPalindrome(n: Long) {\n println(\"Decimal : $n\")\n println(\"Binary : ${n.toBinaryString()}\")\n println(\"Ternary : ${n.toTernaryString()}\")\n println()\n}\n\n/** create a ternary palindrome whose left part is the ternary equivalent of 'n' and return its decimal equivalent */\nfun createPalindrome3(n: Long): Long {\n val ternary = n.toTernaryString()\n var power3 = 1L\n var sum = 0L\n val length = ternary.length\n for (i in 0 until length) { // right part of palindrome is mirror image of left part\n if (ternary[i] > '0') sum += (ternary[i].toInt() - 48) * power3\n power3 *= 3L\n }\n sum += power3 // middle digit must be 1\n power3 *= 3L\n sum += n * power3 // value of left part is simply 'n' multiplied by appropriate power of 3\n return sum\n}\n\nfun main(args: Array) {\n var i = 1L\n var p3: Long\n var count = 2\n var binStr: String\n println(\"The first 6 numbers which are palindromic in both binary and ternary are:\\n\")\n // we can assume the first two palindromic numbers as per the task description\n printPalindrome(0L) // 0 is a palindrome in all 3 bases\n printPalindrome(1L) // 1 is a palindrome in all 3 bases\n\n do {\n p3 = createPalindrome3(i)\n if (p3 % 2 > 0L) { // cannot be even as binary equivalent would end in zero\n binStr = p3.toBinaryString()\n if (binStr.length % 2 == 1) { // binary palindrome must have an odd number of digits\n if (isPalindromic(binStr)) {\n printPalindrome(p3)\n count++\n }\n }\n }\n i++\n }\n while (count < 6)\n}"} {"title": "Find the intersection of a line with a plane", "language": "Kotlin", "task": "Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection.\n\n\n;Task:\nFind the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].\n\n", "solution": "// version 1.1.51\n\nclass Vector3D(val x: Double, val y: Double, val z: Double) {\n\n operator fun plus(v: Vector3D) = Vector3D(x + v.x, y + v.y, z + v.z)\n\n operator fun minus(v: Vector3D) = Vector3D(x - v.x, y - v.y, z - v.z)\n\n operator fun times(s: Double) = Vector3D(s * x, s * y, s * z)\n\n infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z\n\n override fun toString() = \"($x, $y, $z)\"\n}\n\nfun intersectPoint(\n rayVector: Vector3D,\n rayPoint: Vector3D,\n planeNormal: Vector3D,\n planePoint: Vector3D\n): Vector3D {\n val diff = rayPoint - planePoint\n val prod1 = diff dot planeNormal\n val prod2 = rayVector dot planeNormal\n val prod3 = prod1 / prod2\n return rayPoint - rayVector * prod3\n}\n\nfun main(args: Array) {\n val rv = Vector3D(0.0, -1.0, -1.0)\n val rp = Vector3D(0.0, 0.0, 10.0)\n val pn = Vector3D(0.0, 0.0, 1.0)\n val pp = Vector3D(0.0, 0.0, 5.0)\n val ip = intersectPoint(rv, rp, pn, pp)\n println(\"The ray intersects the plane at $ip\")\n}"} {"title": "Find the intersection of two lines", "language": "Kotlin from C#", "task": "Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html]\n\n;Task:\nFind the point of intersection of two lines in 2D. \n\n\nThe 1st line passes though (4,0) and (6,10) . \nThe 2nd line passes though (0,3) and (10,7) .\n\n", "solution": "// version 1.1.2\n\nclass PointF(val x: Float, val y: Float) {\n override fun toString() = \"{$x, $y}\"\n}\n\nclass LineF(val s: PointF, val e: PointF)\n\nfun findIntersection(l1: LineF, l2: LineF): PointF {\n val a1 = l1.e.y - l1.s.y\n val b1 = l1.s.x - l1.e.x\n val c1 = a1 * l1.s.x + b1 * l1.s.y\n\n val a2 = l2.e.y - l2.s.y\n val b2 = l2.s.x - l2.e.x\n val c2 = a2 * l2.s.x + b2 * l2.s.y\n\n val delta = a1 * b2 - a2 * b1\n // If lines are parallel, intersection point will contain infinite values\n return PointF((b2 * c1 - b1 * c2) / delta, (a1 * c2 - a2 * c1) / delta)\n}\n\nfun main(args: Array) {\n var l1 = LineF(PointF(4f, 0f), PointF(6f, 10f))\n var l2 = LineF(PointF(0f, 3f), PointF(10f, 7f))\n println(findIntersection(l1, l2))\n l1 = LineF(PointF(0f, 0f), PointF(1f, 1f))\n l2 = LineF(PointF(1f, 2f), PointF(4f, 5f))\n println(findIntersection(l1, l2))\n}"} {"title": "Find the last Sunday of each month", "language": "Kotlin", "task": "Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).\n\nExample of an expected output:\n\n./last_sundays 2013\n2013-01-27\n2013-02-24\n2013-03-31\n2013-04-28\n2013-05-26\n2013-06-30\n2013-07-28\n2013-08-25\n2013-09-29\n2013-10-27\n2013-11-24\n2013-12-29\n\n;Related tasks\n* [[Day of the week]]\n* [[Five weekends]]\n* [[Last Friday of each month]]\n\n", "solution": "// version 1.0.6\n\nimport java.util.*\n\nfun main(args: Array) {\n print(\"Enter a year : \")\n val year = readLine()!!.toInt()\n\n println(\"The last Sundays of each month in $year are as follows:\")\n val calendar = GregorianCalendar(year, 0, 31)\n for (month in 1..12) {\n val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)\n val lastSunday = daysInMonth - (calendar[Calendar.DAY_OF_WEEK] - Calendar.SUNDAY)\n println(\"$year-\" + \"%02d-\".format(month) + \"%02d\".format(lastSunday))\n if (month < 12) {\n calendar.add(Calendar.DAY_OF_MONTH, 1)\n calendar.add(Calendar.MONTH, 1)\n calendar.add(Calendar.DAY_OF_MONTH, -1)\n }\n }\n}"} {"title": "Find the missing permutation", "language": "Kotlin", "task": "ABCD\n CABD\n ACDB\n DACB\n BCDA\n ACBD\n ADCB\n CDAB\n DABC\n BCAD\n CADB\n CDBA\n CBAD\n ABDC\n ADBC\n BDCA\n DCBA\n BACD\n BADC\n BDAC\n CBDA\n DBCA\n DCAB\n\n\nListed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. \n\n\n;Task:\nFind that missing permutation.\n\n\n;Methods:\n* Obvious method: \n enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', \n and then look for the missing permutation. \n\n* alternate method:\n Hint: if all permutations were shown above, how many \n times would '''A''' appear in each position? \n What is the ''parity'' of this number?\n\n* another alternate method:\n Hint: if you add up the letter values of each column, \n does a missing letter '''A''', '''B''', '''C''', and '''D''' from each\n column cause the total value for each column to be unique?\n\n\n;Related task:\n* [[Permutations]])\n\n", "solution": "// version 1.1.2\n\nfun permute(input: List): List> {\n if (input.size == 1) return listOf(input)\n val perms = mutableListOf>()\n val toInsert = input[0]\n for (perm in permute(input.drop(1))) {\n for (i in 0..perm.size) {\n val newPerm = perm.toMutableList()\n newPerm.add(i, toInsert)\n perms.add(newPerm)\n }\n }\n return perms\n}\n\nfun missingPerms(input: List, perms: List>) = permute(input) - perms\n\nfun main(args: Array) {\n val input = listOf('A', 'B', 'C', 'D')\n val strings = listOf(\n \"ABCD\", \"CABD\", \"ACDB\", \"DACB\", \"BCDA\", \"ACBD\", \"ADCB\", \"CDAB\",\n \"DABC\", \"BCAD\", \"CADB\", \"CDBA\", \"CBAD\", \"ABDC\", \"ADBC\", \"BDCA\",\n \"DCBA\", \"BACD\", \"BADC\", \"BDAC\", \"CBDA\", \"DBCA\", \"DCAB\"\n )\n val perms = strings.map { it.toList() }\n val missing = missingPerms(input, perms)\n if (missing.size == 1)\n print(\"The missing permutation is ${missing[0].joinToString(\"\")}\")\n else {\n println(\"There are ${missing.size} missing permutations, namely:\\n\")\n for (perm in missing) println(perm.joinToString(\"\"))\n }\n}"} {"title": "First-class functions/Use numbers analogously", "language": "Kotlin", "task": "In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.\n\nThis tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.\n\n\nWrite a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:\n x = 2.0\n xi = 0.5\n y = 4.0\n yi = 0.25\n z = x + y\n zi = 1.0 / ( x + y )\n\nCreate a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call:\n new_function = multiplier(n1,n2)\n # where new_function(m) returns the result of n1 * n2 * m\n\nApplying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one.\n'''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close.\n\nTo paraphrase the task description: Do what was done before, but with numbers rather than functions\n\n", "solution": "// version 1.1.2\n\nfun multiplier(n1: Double, n2: Double) = { m: Double -> n1 * n2 * m}\n\nfun main(args: Array) {\n val x = 2.0\n val xi = 0.5\n val y = 4.0\n val yi = 0.25\n val z = x + y\n val zi = 1.0 / ( x + y)\n val a = doubleArrayOf(x, y, z)\n val ai = doubleArrayOf(xi, yi, zi)\n val m = 0.5\n for (i in 0 until a.size) {\n println(\"${multiplier(a[i], ai[i])(m)} = multiplier(${a[i]}, ${ai[i]})($m)\")\n }\n}"} {"title": "First perfect square in base n with n unique digits", "language": "Kotlin from Java", "task": "Find the first perfect square in a given base '''N''' that has at least '''N''' digits and\nexactly '''N''' ''significant unique'' digits when expressed in base '''N'''.\n\nE.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432''').\n\nYou may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct.\n\n;Task\n\n* Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated.\n\n* (optional) Do the same for bases '''13''' through '''16'''.\n\n* (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math)\n\n\n;See also:\n\n;* OEIS A260182: smallest square that is pandigital in base n.\n\n;Related task\n\n;* [[Casting out nines]]\n\n", "solution": "import java.math.BigInteger\nimport java.time.Duration\nimport java.util.ArrayList\nimport java.util.HashSet\nimport kotlin.math.sqrt\n\nconst val ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz|\"\nvar base: Byte = 0\nvar bmo: Byte = 0\nvar blim: Byte = 0\nvar ic: Byte = 0\nvar st0: Long = 0\nvar bllim: BigInteger? = null\nvar threshold: BigInteger? = null\nvar hs: MutableSet = HashSet()\nvar o: MutableSet = HashSet()\nval chars = ALPHABET.toCharArray()\nvar limits: MutableList? = null\nvar ms: String? = null\n\nfun indexOf(c: Char): Int {\n for (i in chars.indices) {\n if (chars[i] == c) {\n return i\n }\n }\n return -1\n}\n\n// convert BigInteger to string using current base\nfun toStr(b: BigInteger): String {\n var b2 = b\n val bigBase = BigInteger.valueOf(base.toLong())\n val res = StringBuilder()\n while (b2 > BigInteger.ZERO) {\n val divRem = b2.divideAndRemainder(bigBase)\n res.append(chars[divRem[1].toInt()])\n b2 = divRem[0]\n }\n return res.toString()\n}\n\n// check for a portion of digits, bailing if uneven\nfun allInQS(b: BigInteger): Boolean {\n var b2 = b\n val bigBase = BigInteger.valueOf(base.toLong())\n var c = ic.toInt()\n hs.clear()\n hs.addAll(o)\n while (b2 > bllim) {\n val divRem = b2.divideAndRemainder(bigBase)\n hs.add(divRem[1].toByte())\n c++\n if (c > hs.size) {\n return false\n }\n b2 = divRem[0]\n }\n return true\n}\n\n// check for a portion of digits, all the way to the end\nfun allInS(b: BigInteger): Boolean {\n var b2 = b\n val bigBase = BigInteger.valueOf(base.toLong())\n hs.clear()\n hs.addAll(o)\n while (b2 > bllim) {\n val divRem = b2.divideAndRemainder(bigBase)\n hs.add(divRem[1].toByte())\n b2 = divRem[0]\n }\n return hs.size == base.toInt()\n}\n\n// check for all digits, bailing if uneven\nfun allInQ(b: BigInteger): Boolean {\n var b2 = b\n val bigBase = BigInteger.valueOf(base.toLong())\n var c = 0\n hs.clear()\n while (b2 > BigInteger.ZERO) {\n val divRem = b2.divideAndRemainder(bigBase)\n hs.add(divRem[1].toByte())\n c++\n if (c > hs.size) {\n return false\n }\n b2 = divRem[0]\n }\n return true\n}\n\n// check for all digits, all the way to the end\nfun allIn(b: BigInteger): Boolean {\n var b2 = b\n val bigBase = BigInteger.valueOf(base.toLong())\n hs.clear()\n while (b2 > BigInteger.ZERO) {\n val divRem = b2.divideAndRemainder(bigBase)\n hs.add(divRem[1].toByte())\n b2 = divRem[0]\n }\n return hs.size == base.toInt()\n}\n\n// parse a string into a BigInteger, using current base\nfun to10(s: String?): BigInteger {\n val bigBase = BigInteger.valueOf(base.toLong())\n var res = BigInteger.ZERO\n for (element in s!!) {\n val idx = indexOf(element)\n val bigIdx = BigInteger.valueOf(idx.toLong())\n res = res.multiply(bigBase).add(bigIdx)\n }\n return res\n}\n\n// returns the minimum value string, optionally inserting extra digit\nfun fixup(n: Int): String {\n var res = ALPHABET.substring(0, base.toInt())\n if (n > 0) {\n val sb = StringBuilder(res)\n sb.insert(n, n)\n res = sb.toString()\n }\n return \"10\" + res.substring(2)\n}\n\n// checks the square against the threshold, advances various limits when needed\nfun check(sq: BigInteger) {\n if (sq > threshold) {\n o.remove(indexOf(ms!![blim.toInt()]).toByte())\n blim--\n ic--\n threshold = limits!![bmo - blim - 1]\n bllim = to10(ms!!.substring(0, blim + 1))\n }\n}\n\n// performs all the calculations for the current base\nfun doOne() {\n limits = ArrayList()\n bmo = (base - 1).toByte()\n var dr: Byte = 0\n if ((base.toInt() and 1) == 1) {\n dr = (base.toInt() shr 1).toByte()\n }\n o.clear()\n blim = 0\n var id: Byte = 0\n var inc = 1\n val st = System.nanoTime()\n val sdr = ByteArray(bmo.toInt())\n var rc: Byte = 0\n for (i in 0 until bmo) {\n sdr[i] = (i * i % bmo).toByte()\n if (sdr[i] == dr) {\n rc = (rc + 1).toByte()\n }\n if (sdr[i] == 0.toByte()) {\n sdr[i] = (sdr[i] + bmo).toByte()\n }\n }\n var i: Long = 0\n if (dr > 0) {\n id = base\n i = 1\n while (i <= dr) {\n if (sdr[i.toInt()] >= dr) {\n if (id > sdr[i.toInt()]) {\n id = sdr[i.toInt()]\n }\n }\n i++\n }\n id = (id - dr).toByte()\n i = 0\n }\n ms = fixup(id.toInt())\n var sq = to10(ms)\n var rt = BigInteger.valueOf((sqrt(sq.toDouble()) + 1).toLong())\n sq = rt.multiply(rt)\n if (base > 9) {\n for (j in 1 until base) {\n limits!!.add(to10(ms!!.substring(0, j) + chars[bmo.toInt()].toString().repeat(base - j + if (rc > 0) 0 else 1)))\n }\n limits!!.reverse()\n while (sq < limits!![0]) {\n rt = rt.add(BigInteger.ONE)\n sq = rt.multiply(rt)\n }\n }\n var dn = rt.shiftLeft(1).add(BigInteger.ONE)\n var d = BigInteger.ONE\n if (base > 3 && rc > 0) {\n while (sq.remainder(BigInteger.valueOf(bmo.toLong())).compareTo(BigInteger.valueOf(dr.toLong())) != 0) {\n rt = rt.add(BigInteger.ONE)\n sq = sq.add(dn)\n dn = dn.add(BigInteger.TWO)\n } // aligns sq to dr\n inc = bmo / rc\n if (inc > 1) {\n dn = dn.add(rt.multiply(BigInteger.valueOf(inc - 2.toLong())).subtract(BigInteger.ONE))\n d = BigInteger.valueOf(inc * inc.toLong())\n }\n dn = dn.add(dn).add(d)\n }\n d = d.shiftLeft(1)\n if (base > 9) {\n blim = 0\n while (sq < limits!![bmo - blim - 1]) {\n blim++\n }\n ic = (blim + 1).toByte()\n threshold = limits!![bmo - blim - 1]\n if (blim > 0) {\n for (j in 0..blim) {\n o.add(indexOf(ms!![j]).toByte())\n }\n }\n bllim = if (blim > 0) {\n to10(ms!!.substring(0, blim + 1))\n } else {\n BigInteger.ZERO\n }\n if (base > 5 && rc > 0) while (!allInQS(sq)) {\n sq = sq.add(dn)\n dn = dn.add(d)\n i += 1\n check(sq)\n } else {\n while (!allInS(sq)) {\n sq = sq.add(dn)\n dn = dn.add(d)\n i += 1\n check(sq)\n }\n }\n } else {\n if (base > 5 && rc > 0) {\n while (!allInQ(sq)) {\n sq = sq.add(dn)\n dn = dn.add(d)\n i += 1\n }\n } else {\n while (!allIn(sq)) {\n sq = sq.add(dn)\n dn = dn.add(d)\n i += 1\n }\n }\n }\n rt = rt.add(BigInteger.valueOf(i * inc))\n val delta1 = System.nanoTime() - st\n val dur1 = Duration.ofNanos(delta1)\n val delta2 = System.nanoTime() - st0\n val dur2 = Duration.ofNanos(delta2)\n System.out.printf(\n \"%3d %2d %2s %20s -> %-40s %10d %9s %9s\\n\",\n base, inc, if (id > 0) ALPHABET.substring(id.toInt(), id + 1) else \" \", toStr(rt), toStr(sq), i, format(dur1), format(dur2)\n )\n}\n\nprivate fun format(d: Duration): String {\n val minP = d.toMinutesPart()\n val secP = d.toSecondsPart()\n val milP = d.toMillisPart()\n return String.format(\"%02d:%02d.%03d\", minP, secP, milP)\n}\n\nfun main() {\n println(\"base inc id root square test count time total\")\n st0 = System.nanoTime()\n base = 2\n while (base < 28) {\n doOne()\n ++base\n }\n}"} {"title": "First power of 2 that has leading decimal digits of 12", "language": "Kotlin from Java", "task": "(This task is taken from a ''Project Euler'' problem.)\n\n(All numbers herein are expressed in base ten.)\n\n\n'''27 = 128''' and '''7''' is\nthe first power of '''2''' whose leading decimal digits are '''12'''.\n\nThe next power of '''2''' whose leading decimal digits\nare '''12''' is '''80''',\n'''280 = 1208925819614629174706176'''.\n\n\nDefine ''' '' p''(''L,n'')''' to be the ''' ''n''th'''-smallest\nvalue of ''' ''j'' ''' such that the base ten representation\nof '''2''j''''' begins with the digits of ''' ''L'' '''.\n\n So ''p''(12, 1) = 7 and\n ''p''(12, 2) = 80\n\n\nYou are also given that:\n ''p''(123, 45) = 12710\n\n\n;Task:\n::* find: \n:::::* ''' ''p''(12, 1) ''' \n:::::* ''' ''p''(12, 2) ''' \n:::::* ''' ''p''(123, 45) ''' \n:::::* ''' ''p''(123, 12345) ''' \n:::::* ''' ''p''(123, 678910) ''' \n::* display the results here, on this page.\n\n", "solution": "import kotlin.math.ln\nimport kotlin.math.pow\n\nfun main() {\n runTest(12, 1)\n runTest(12, 2)\n runTest(123, 45)\n runTest(123, 12345)\n runTest(123, 678910)\n}\n\nprivate fun runTest(l: Int, n: Int) {\n// System.out.printf(\"p(%d, %d) = %,d%n\", l, n, p(l, n))\n println(\"p($l, $n) = %,d\".format(p(l, n)))\n}\n\nfun p(l: Int, n: Int): Int {\n var m = n\n var test = 0\n val log = ln(2.0) / ln(10.0)\n var factor = 1\n var loop = l\n while (loop > 10) {\n factor *= 10\n loop /= 10\n }\n while (m > 0) {\n test++\n val value = (factor * 10.0.pow(test * log % 1)).toInt()\n if (value == l) {\n m--\n }\n }\n return test\n}"} {"title": "Fivenum", "language": "Kotlin", "task": "Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory.\n\nFor example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function.\n\n\n;Task:\nGiven an array of numbers, compute the five-number summary.\n\n\n;Note: \nWhile these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. \n\nMoreover, while there is a consensus about the \"box\" of the boxplot, there are variations among statistical packages for the whiskers.\n\n", "solution": "// version 1.2.21\n\nfun median(x: DoubleArray, start: Int, endInclusive: Int): Double {\n val size = endInclusive - start + 1\n require (size > 0) { \"Array slice cannot be empty\" }\n val m = start + size / 2\n return if (size % 2 == 1) x[m] else (x[m - 1] + x[m]) / 2.0\n}\n\nfun fivenum(x: DoubleArray): DoubleArray {\n require(x.none { it.isNaN() }) { \"Unable to deal with arrays containing NaN\" }\n val result = DoubleArray(5)\n x.sort()\n result[0] = x[0]\n result[2] = median(x, 0, x.size - 1)\n result[4] = x[x.lastIndex]\n val m = x.size / 2\n var lowerEnd = if (x.size % 2 == 1) m else m - 1\n result[1] = median(x, 0, lowerEnd)\n result[3] = median(x, m, x.size - 1)\n return result\n}\n\nfun main(args: Array) {\n var xl = listOf(\n doubleArrayOf(15.0, 6.0, 42.0, 41.0, 7.0, 36.0, 49.0, 40.0, 39.0, 47.0, 43.0),\n doubleArrayOf(36.0, 40.0, 7.0, 39.0, 41.0, 15.0),\n doubleArrayOf(\n 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555,\n -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527,\n -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385,\n 0.75775634, 0.32566578\n )\n )\n xl.forEach { println(\"${fivenum(it).asList()}\\n\") }\n}"} {"title": "Flatten a list", "language": "Kotlin", "task": "Write a function to flatten the nesting in an arbitrary list of values. \n\nYour program should work on the equivalent of this list:\n [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []]\nWhere the correct result would be the list:\n [1, 2, 3, 4, 5, 6, 7, 8]\n\n;Related task:\n* [[Tree traversal]]\n\n", "solution": "// version 1.0.6\n\n@Suppress(\"UNCHECKED_CAST\")\n\nfun flattenList(nestList: List, flatList: MutableList) {\n for (e in nestList)\n if (e is Int)\n flatList.add(e)\n else\n // using unchecked cast here as can't check for instance of 'erased' generic type\n flattenList(e as List, flatList) \n}\n \nfun main(args: Array) {\n val nestList : List = listOf(\n listOf(1),\n 2,\n listOf(listOf(3, 4), 5),\n listOf(listOf(listOf())),\n listOf(listOf(listOf(6))),\n 7,\n 8,\n listOf()\n )\n println(\"Nested : \" + nestList)\n val flatList = mutableListOf()\n flattenList(nestList, flatList)\n println(\"Flattened : \" + flatList) \n}"} {"title": "Flipping bits game", "language": "Kotlin", "task": "The game:\nGiven an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones.\n\n\nThe game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered \ncolumns at once (as one move).\n\nIn an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column.\n\n\n;Task:\nCreate a program to score for the Flipping bits game.\n# The game should create an original random target configuration and a starting configuration.\n# Ensure that the starting position is ''never'' the target position.\n# The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position).\n# The number of moves taken so far should be shown.\n\n\nShow an example of a short game here, on this page, for a '''3x3''' array of bits.\n\n", "solution": "// version 1.1.3\n\nimport java.util.Random\n\nval rand = Random()\nval target = Array(3) { IntArray(3) { rand.nextInt(2) } }\nval board = Array(3) { IntArray(3) }\n\nfun flipRow(r: Int) {\n for (c in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0\n}\n\nfun flipCol(c: Int) {\n for (r in 0..2) board[r][c] = if (board[r][c] == 0) 1 else 0\n}\n\n/** starting from the target we make 9 random row or column flips */\nfun initBoard() {\n for (i in 0..2) {\n for (j in 0..2) board[i][j] = target[i][j]\n }\n repeat(9) {\n val rc = rand.nextInt(2)\n if (rc == 0)\n flipRow(rand.nextInt(3))\n else\n flipCol(rand.nextInt(3))\n }\n}\n\nfun printBoard(label: String, isTarget: Boolean = false) {\n val a = if (isTarget) target else board\n println(\"$label:\")\n println(\" | a b c\")\n println(\"---------\")\n for (r in 0..2) {\n print(\"${r + 1} |\")\n for (c in 0..2) print(\" ${a[r][c]}\")\n println()\n }\n println()\n}\n\nfun gameOver(): Boolean {\n for (r in 0..2) {\n for (c in 0..2) if (board[r][c] != target[r][c]) return false\n }\n return true\n}\n\nfun main(args: Array) {\n // initialize board and ensure it differs from the target i.e. game not already over!\n do {\n initBoard()\n }\n while(gameOver())\n\n printBoard(\"TARGET\", true)\n printBoard(\"OPENING BOARD\")\n var flips = 0\n\n do {\n var isRow = true\n var n = -1\n do {\n print(\"Enter row number or column letter to be flipped: \")\n val input = readLine()!!\n val ch = if (input.isNotEmpty()) input[0].toLowerCase() else '0'\n if (ch !in \"123abc\") {\n println(\"Must be 1, 2, 3, a, b or c\")\n continue\n }\n if (ch in '1'..'3') {\n n = ch.toInt() - 49\n }\n else {\n isRow = false\n n = ch.toInt() - 97\n }\n }\n while (n == -1)\n\n flips++\n if (isRow) flipRow(n) else flipCol(n)\n val plural = if (flips == 1) \"\" else \"S\"\n printBoard(\"\\nBOARD AFTER $flips FLIP$plural\")\n }\n while (!gameOver())\n\n val plural = if (flips == 1) \"\" else \"s\"\n println(\"You've succeeded in $flips flip$plural\")\n}"} {"title": "Floyd's triangle", "language": "Kotlin from Java", "task": "Floyd's triangle lists the natural numbers in a right triangle aligned to the left where \n* the first row is '''1''' (unity)\n* successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above.\n\n\nThe first few lines of a Floyd triangle looks like this:\n\n 1\n 2 3\n 4 5 6\n 7 8 9 10\n11 12 13 14 15\n\n\n\n;Task:\n:# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows).\n:# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.\n\n", "solution": "fun main(args: Array) = args.forEach { Triangle(it.toInt()) }\n\ninternal class Triangle(n: Int) {\n init {\n println(\"$n rows:\")\n var printMe = 1\n var printed = 0\n var row = 1\n while (row <= n) {\n val cols = Math.ceil(Math.log10(n * (n - 1) / 2 + printed + 2.0)).toInt()\n print(\"%${cols}d \".format(printMe))\n if (++printed == row) { println(); row++; printed = 0 }\n printMe++\n }\n }\n}"} {"title": "Four bit adder", "language": "Kotlin", "task": "\"''Simulate''\" a four-bit adder.\n \nThis design can be realized using four 1-bit full adders. \nEach of these 1-bit full adders can be built with two gate. ; \n\nFinally a half adder can be made using an ''xor'' gate and an ''and'' gate. \n\nThe ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''.\n\n'''Not''', '''or''' and '''and''', the only allowed \"gates\" for the task, can be \"imitated\" by using the bitwise operators of your language. \n\nIf there is not a ''bit type'' in your language, to be sure that the ''not'' does not \"invert\" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input.\n\nInstead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other \"constructive blocks\", in turn made of \"simpler\" and \"smaller\" ones.\n\n{|\n|+Schematics of the \"constructive blocks\"\n!(Xor gate with ANDs, ORs and NOTs) \n! (A half adder) \n! (A full adder) \n! (A 4-bit adder) \n|-\n|Xor gate done with ands, ors and nots\n|A half adder\n|A full adder\n|A 4-bit adder\n|}\n\n\n\nSolutions should try to be as descriptive as possible, making it as easy as possible to identify \"connections\" between higher-order \"blocks\". \n\nIt is not mandatory to replicate the syntax of higher-order blocks in the atomic \"gate\" blocks, i.e. basic \"gate\" operations can be performed as usual bitwise operations, or they can be \"wrapped\" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice.\n\nTo test the implementation, show the sum of two four-bit numbers (in binary).\n\n\n", "solution": "// version 1.1.51\n\nval Boolean.I get() = if (this) 1 else 0\n\nval Int.B get() = this != 0\n\nclass Nybble(val n3: Boolean, val n2: Boolean, val n1: Boolean, val n0: Boolean) {\n fun toInt() = n0.I + n1.I * 2 + n2.I * 4 + n3.I * 8\n\n override fun toString() = \"${n3.I}${n2.I}${n1.I}${n0.I}\"\n}\n\nfun Int.toNybble(): Nybble {\n val n = BooleanArray(4)\n for (k in 0..3) n[k] = ((this shr k) and 1).B\n return Nybble(n[3], n[2], n[1], n[0])\n}\n\nfun xorGate(a: Boolean, b: Boolean) = (a && !b) || (!a && b)\n\nfun halfAdder(a: Boolean, b: Boolean) = Pair(xorGate(a, b), a && b)\n\nfun fullAdder(a: Boolean, b: Boolean, c: Boolean): Pair {\n val (s1, c1) = halfAdder(c, a)\n val (s2, c2) = halfAdder(s1, b)\n return s2 to (c1 || c2)\n}\n\nfun fourBitAdder(a: Nybble, b: Nybble): Pair {\n val (s0, c0) = fullAdder(a.n0, b.n0, false)\n val (s1, c1) = fullAdder(a.n1, b.n1, c0)\n val (s2, c2) = fullAdder(a.n2, b.n2, c1)\n val (s3, c3) = fullAdder(a.n3, b.n3, c2)\n return Nybble(s3, s2, s1, s0) to c3.I\n}\n\nconst val f = \"%s + %s = %d %s (%2d + %2d = %2d)\"\n\nfun test(i: Int, j: Int) {\n val a = i.toNybble()\n val b = j.toNybble()\n val (r, c) = fourBitAdder(a, b)\n val s = c * 16 + r.toInt()\n println(f.format(a, b, c, r, i, j, s))\n}\n\nfun main(args: Array) {\n println(\" A B C R I J S\")\n for (i in 0..15) {\n for (j in i..minOf(i + 1, 15)) test(i, j)\n }\n}"} {"title": "Four is magic", "language": "Kotlin", "task": "Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma.\n\nContinue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. \n\nContinue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four.\n\nFor instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' \n\n '''Three is five, five is four, four is magic.'''\n\nFor reference, here are outputs for 0 through 9.\n\n Zero is four, four is magic.\n One is three, three is five, five is four, four is magic.\n Two is three, three is five, five is four, four is magic.\n Three is five, five is four, four is magic.\n Four is magic.\n Five is four, four is magic.\n Six is three, three is five, five is four, four is magic.\n Seven is five, five is four, four is magic.\n Eight is five, five is four, four is magic.\n Nine is four, four is magic.\n\n\n;Some task guidelines:\n:* You may assume the input will only contain integer numbers.\n:* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.)\n:* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.)\n:* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.)\n:* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''.\n:* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''.\n:* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''.\n:* The output should follow the format \"N is K, K is M, M is ... four is magic.\" (unless the input is 4, in which case the output should simply be \"four is magic.\")\n:* The output can either be the return value from the function, or be displayed from within the function.\n:* You are encouraged, though not mandated to use proper sentence capitalization.\n:* You may optionally support negative numbers. '''-7''' is '''negative seven'''.\n:* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration.\n\n\nYou can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. \n\nIf you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.)\n\nFour is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code.\n\n\n;Related tasks:\n:* [[Four is the number of_letters in the ...]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Summarize and say sequence]]\n:* [[Spelling of ordinal numbers]]\n:* [[De Bruijn sequences]]\n\n", "solution": "// version 1.1.4-3\n\nval names = mapOf(\n 1 to \"one\",\n 2 to \"two\",\n 3 to \"three\",\n 4 to \"four\",\n 5 to \"five\",\n 6 to \"six\",\n 7 to \"seven\",\n 8 to \"eight\",\n 9 to \"nine\",\n 10 to \"ten\",\n 11 to \"eleven\",\n 12 to \"twelve\",\n 13 to \"thirteen\",\n 14 to \"fourteen\",\n 15 to \"fifteen\",\n 16 to \"sixteen\",\n 17 to \"seventeen\",\n 18 to \"eighteen\",\n 19 to \"nineteen\",\n 20 to \"twenty\",\n 30 to \"thirty\",\n 40 to \"forty\",\n 50 to \"fifty\",\n 60 to \"sixty\",\n 70 to \"seventy\",\n 80 to \"eighty\",\n 90 to \"ninety\"\n)\nval bigNames = mapOf(\n 1_000L to \"thousand\",\n 1_000_000L to \"million\",\n 1_000_000_000L to \"billion\",\n 1_000_000_000_000L to \"trillion\",\n 1_000_000_000_000_000L to \"quadrillion\",\n 1_000_000_000_000_000_000L to \"quintillion\"\n)\n\nfun numToText(n: Long): String {\n if (n == 0L) return \"zero\"\n val neg = n < 0L\n val maxNeg = n == Long.MIN_VALUE\n var nn = if (maxNeg) -(n + 1) else if (neg) -n else n\n val digits3 = IntArray(7)\n for (i in 0..6) { // split number into groups of 3 digits from the right\n digits3[i] = (nn % 1000).toInt()\n nn /= 1000\n }\n\n fun threeDigitsToText(number: Int) : String {\n val sb = StringBuilder()\n if (number == 0) return \"\"\n val hundreds = number / 100\n val remainder = number % 100\n if (hundreds > 0) {\n sb.append(names[hundreds], \" hundred\")\n if (remainder > 0) sb.append(\" \")\n }\n if (remainder > 0) {\n val tens = remainder / 10\n val units = remainder % 10\n if (tens > 1) {\n sb.append(names[tens * 10])\n if (units > 0) sb.append(\"-\", names[units])\n }\n else sb.append(names[remainder])\n }\n return sb.toString()\n }\n\n val strings = Array(7) { threeDigitsToText(digits3[it]) }\n var text = strings[0]\n var big = 1000L\n for (i in 1..6) {\n if (digits3[i] > 0) {\n var text2 = strings[i] + \" \" + bigNames[big]\n if (text.length > 0) text2 += \" \"\n text = text2 + text\n }\n big *= 1000\n }\n if (maxNeg) text = text.dropLast(5) + \"eight\"\n if (neg) text = \"negative \" + text\n return text\n}\n\nfun fourIsMagic(n: Long): String {\n if (n == 4L) return \"Four is magic.\"\n var text = numToText(n).capitalize()\n val sb = StringBuilder()\n while (true) {\n val len = text.length.toLong()\n if (len == 4L) return sb.append(\"$text is four, four is magic.\").toString()\n val text2 = numToText(len)\n sb.append(\"$text is $text2, \")\n text = text2\n }\n}\n\nfun main(args: Array) {\n val la = longArrayOf(0, 4, 6, 11, 13, 75, 100, 337, -164, 9_223_372_036_854_775_807L)\n for (i in la) {\n println(fourIsMagic(i))\n println()\n }\n}"} {"title": "Four is the number of letters in the ...", "language": "Kotlin", "task": "The '''Four is ...''' sequence is based on the counting of the number of\nletters in the words of the (never-ending) sentence:\n Four is the number of letters in the first word of this sentence, two in the second,\n three in the third, six in the fourth, two in the fifth, seven in the sixth, *** \n\n\n;Definitions and directives:\n:* English is to be used in spelling numbers.\n:* '''Letters''' are defined as the upper- and lowercase letters in the Latin alphabet ('''A-->Z''' and '''a-->z''').\n:* Commas are not counted, nor are hyphens (dashes or minus signs).\n:* '''twenty-three''' has eleven letters.\n:* '''twenty-three''' is considered one word (which is hyphenated).\n:* no ''' ''and'' ''' words are to be used when spelling a (English) word for a number.\n:* The American version of numbers will be used here in this task (as opposed to the British version).\n '''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\n;Task:\n:* Write a driver (invoking routine) and a function (subroutine/routine***) that returns the sequence (for any positive integer) of the number of letters in the first '''N''' words in the never-ending sentence. For instance, the portion of the never-ending sentence shown above (2nd sentence of this task's preamble), the sequence would be:\n '''4 2 3 6 2 7'''\n:* Only construct as much as is needed for the never-ending sentence.\n:* Write a driver (invoking routine) to show the number of letters in the Nth word, ''as well as'' showing the Nth word itself.\n:* After each test case, show the total number of characters (including blanks, commas, and punctuation) of the sentence that was constructed.\n:* Show all output here.\n\n\n;Test cases:\n Display the first 201 numbers in the sequence (and the total number of characters in the sentence).\n Display the number of letters (and the word itself) of the 1,000th word.\n Display the number of letters (and the word itself) of the 10,000th word.\n Display the number of letters (and the word itself) of the 100,000th word.\n Display the number of letters (and the word itself) of the 1,000,000th word.\n Display the number of letters (and the word itself) of the 10,000,000th word (optional).\n\n\n;Related tasks:\n:* [[Four is magic]]\n:* [[Look-and-say sequence]]\n:* [[Number names]]\n:* [[Self-describing numbers]]\n:* [[Self-referential sequence]]\n:* [[Spelling of ordinal numbers]]\n\n\n;Also see:\n:* See the OEIS sequence A72425 \"Four is the number of letters...\".\n:* See the OEIS sequence A72424 \"Five's the number of letters...\"\n\n", "solution": "// version 1.1.4-3\n\nval names = mapOf(\n 1 to \"one\",\n 2 to \"two\",\n 3 to \"three\",\n 4 to \"four\",\n 5 to \"five\",\n 6 to \"six\",\n 7 to \"seven\",\n 8 to \"eight\",\n 9 to \"nine\",\n 10 to \"ten\",\n 11 to \"eleven\",\n 12 to \"twelve\",\n 13 to \"thirteen\",\n 14 to \"fourteen\",\n 15 to \"fifteen\",\n 16 to \"sixteen\",\n 17 to \"seventeen\",\n 18 to \"eighteen\",\n 19 to \"nineteen\",\n 20 to \"twenty\",\n 30 to \"thirty\",\n 40 to \"forty\",\n 50 to \"fifty\",\n 60 to \"sixty\",\n 70 to \"seventy\",\n 80 to \"eighty\",\n 90 to \"ninety\"\n)\n\nval bigNames = mapOf(\n 1_000L to \"thousand\",\n 1_000_000L to \"million\",\n 1_000_000_000L to \"billion\",\n 1_000_000_000_000L to \"trillion\",\n 1_000_000_000_000_000L to \"quadrillion\",\n 1_000_000_000_000_000_000L to \"quintillion\"\n)\n\nval irregOrdinals = mapOf(\n \"one\" to \"first\",\n \"two\" to \"second\",\n \"three\" to \"third\",\n \"five\" to \"fifth\",\n \"eight\" to \"eighth\",\n \"nine\" to \"ninth\",\n \"twelve\" to \"twelfth\"\n)\n\nfun String.toOrdinal(): String {\n if (this == \"zero\") return \"zeroth\" // or alternatively 'zeroeth'\n val splits = this.split(' ', '-')\n val last = splits[splits.lastIndex]\n return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!\n else if (last.endsWith(\"y\")) this.dropLast(1) + \"ieth\"\n else this + \"th\"\n}\n\nfun numToText(n: Long, uk: Boolean = false): String {\n if (n == 0L) return \"zero\"\n val neg = n < 0L\n val maxNeg = n == Long.MIN_VALUE\n var nn = if (maxNeg) -(n + 1) else if (neg) -n else n\n val digits3 = IntArray(7)\n for (i in 0..6) { // split number into groups of 3 digits from the right\n digits3[i] = (nn % 1000).toInt()\n nn /= 1000\n }\n\n fun threeDigitsToText(number: Int) : String {\n val sb = StringBuilder()\n if (number == 0) return \"\"\n val hundreds = number / 100\n val remainder = number % 100\n if (hundreds > 0) {\n sb.append(names[hundreds], \" hundred\")\n if (remainder > 0) sb.append(if (uk) \" and \" else \" \")\n }\n if (remainder > 0) {\n val tens = remainder / 10\n val units = remainder % 10\n if (tens > 1) {\n sb.append(names[tens * 10])\n if (units > 0) sb.append(\"-\", names[units])\n }\n else sb.append(names[remainder])\n }\n return sb.toString()\n }\n\n val strings = Array(7) { threeDigitsToText(digits3[it]) }\n var text = strings[0]\n var andNeeded = uk && digits3[0] in 1..99\n var big = 1000L\n for (i in 1..6) {\n if (digits3[i] > 0) {\n var text2 = strings[i] + \" \" + bigNames[big]\n if (text.isNotEmpty()) {\n text2 += if (andNeeded) \" and \" else \" \" // no commas inserted in this version\n andNeeded = false\n }\n else andNeeded = uk && digits3[i] in 1..99\n text = text2 + text\n }\n big *= 1000\n }\n if (maxNeg) text = text.dropLast(5) + \"eight\"\n if (neg) text = \"minus \" + text\n return text\n}\n\nval opening = \"Four is the number of letters in the first word of this sentence,\".split(' ')\n\nval String.adjustedLength get() = this.replace(\",\", \"\").replace(\"-\", \"\").length // no ',' or '-'\n\nfun getWords(n: Int): List {\n val words = mutableListOf()\n words.addAll(opening)\n if (n > opening.size) {\n var k = 2\n while (true) {\n val len = words[k - 1].adjustedLength\n val text = numToText(len.toLong())\n val splits = text.split(' ')\n words.addAll(splits)\n words.add(\"in\")\n words.add(\"the\")\n val text2 = numToText(k.toLong()).toOrdinal() + \",\" // add trailing comma\n val splits2 = text2.split(' ')\n words.addAll(splits2)\n if (words.size >= n) break\n k++\n }\n }\n return words\n}\n\nfun getLengths(n: Int): Pair, Int> {\n val words = getWords(n)\n val lengths = words.take(n).map { it.adjustedLength }\n val sentenceLength = words.sumBy { it.length } + words.size - 1 // includes hyphens, commas & spaces\n return Pair(lengths, sentenceLength)\n}\n\nfun getLastWord(n: Int): Triple {\n val words = getWords(n)\n val nthWord = words[n - 1]\n val nthWordLength = nthWord.adjustedLength\n val sentenceLength = words.sumBy { it.length } + words.size - 1 // includes hyphens, commas & spaces\n return Triple(nthWord, nthWordLength, sentenceLength)\n}\n\nfun main(args: Array) {\n var n = 201\n println(\"The lengths of the first $n words are:\\n\")\n val (list, sentenceLength) = getLengths(n)\n for (i in 0 until n) {\n if (i % 25 == 0) {\n if (i > 0) println()\n print(\"${\"%3d\".format(i + 1)}: \")\n }\n print(\"%3d\".format(list[i]))\n }\n println(\"\\n\\nLength of sentence = $sentenceLength\\n\")\n n = 1_000\n do {\n var (word, wLen, sLen) = getLastWord(n)\n if (word.endsWith(\",\")) word = word.dropLast(1) // strip off any trailing comma\n println(\"The length of word $n [$word] is $wLen\")\n println(\"Length of sentence = $sLen\\n\")\n n *= 10\n }\n while (n <= 10_000_000)\n}"} {"title": "French Republican calendar", "language": "Kotlin", "task": "Write a program to convert dates between the French Republican calendar.\n\nThe year 1 of the Republican calendar began on 22 September 1792. There were twelve months (Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, and Fructidor) of 30 days each, followed by five intercalary days or Sansculottides (Fete de la vertu / Virtue Day, Fete du genie / Talent Day, Fete du travail / Labour Day, Fete de l'opinion / Opinion Day, and Fete des recompenses / Honours Day). In leap years (the years 3, 7, and 11) a sixth Sansculottide was added: Fete de la Revolution / Revolution Day.\n\nAs a minimum, your program should give correct results for dates in the range from 1 Vendemiaire 1 = 22 September 1792 to 10 Nivose 14 = 31 December 1805 (the last day when the Republican calendar was officially in use). If you choose to accept later dates, be aware that there are several different methods (described on the Wikipedia page) about how to determine leap years after the year 14. You should indicate which method you are using. (Because of these different methods, correct programs may sometimes give different results for dates after 1805.)\n\nTest your program by converting the following dates both from Gregorian to Republican and from Republican to Gregorian:\n\n* 1 Vendemiaire 1 = 22 September 1792\n\n* 1 Prairial 3 = 20 May 1795\n\n* 27 Messidor 7 = 15 July 1799 (Rosetta Stone discovered)\n\n* Fete de la Revolution 11 = 23 September 1803\n\n* 10 Nivose 14 = 31 December 1805\n\n", "solution": "// version 1.1.4-3\n\nimport java.time.format.DateTimeFormatter\nimport java.time.LocalDate\nimport java.time.temporal.ChronoUnit.DAYS\n\n/* year = 1.. month = 1..13 day = 1..30 */ \nclass FrenchRCDate(val year: Int, val month: Int, val day: Int) {\n\n init {\n require (year > 0 && month in 1..13)\n if (month < 13) require (day in 1..30)\n else {\n val leap = isLeapYear(year)\n require (day in (if (leap) 1..6 else 1..5))\n }\n }\n\n override fun toString() =\n if (month < 13) \"$day ${months[month - 1]} $year\"\n else \"${intercal[day - 1]} $year\"\n\n fun toLocalDate(): LocalDate {\n var sumDays = 0L\n for (i in 1 until year) sumDays += if (isLeapYear(i)) 366 else 365\n val dayInYear = (month - 1) * 30 + day - 1\n return introductionDate.plusDays(sumDays + dayInYear)\n }\n\n companion object {\n /* uses the 'continuous method' for years after 1805 */\n fun isLeapYear(y: Int): Boolean {\n val yy = y + 1\n return (yy % 4 == 0) && (yy % 100 != 0 || yy % 400 == 0)\n }\n\n fun parse(frcDate: String): FrenchRCDate {\n val splits = frcDate.trim().split(' ')\n if (splits.size == 3) {\n val month = months.indexOf(splits[1]) + 1\n require(month in 1..13)\n val year = splits[2].toIntOrNull() ?: 0\n require(year > 0)\n val monthLength = if (month < 13) 30 else if (isLeapYear(year)) 6 else 5\n val day = splits[0].toIntOrNull() ?: 0\n require(day in 1..monthLength)\n return FrenchRCDate(year, month, day)\n }\n else if (splits.size in 4..5) {\n val yearStr = splits[splits.lastIndex]\n val year = yearStr.toIntOrNull() ?: 0\n require(year > 0)\n val scDay = frcDate.trim().dropLast(yearStr.length + 1)\n val day = intercal.indexOf(scDay) + 1\n val maxDay = if (isLeapYear(year)) 6 else 5\n require (day in 1..maxDay)\n return FrenchRCDate(year, 13, day)\n }\n else throw IllegalArgumentException(\"Invalid French Republican date\")\n }\n\n /* for convenience we treat 'Sansculottide' as an extra month with 5 or 6 days */\n val months = arrayOf(\n \"Vend\u00e9miaire\", \"Brumaire\", \"Frimaire\", \"Niv\u00f4se\", \"Pluvi\u00f4se\", \"Vent\u00f4se\", \"Germinal\",\n \"Flor\u00e9al\", \"Prairial\", \"Messidor\", \"Thermidor\", \"Fructidor\", \"Sansculottide\"\n )\n\n val intercal = arrayOf(\n \"F\u00eate de la vertu\", \"F\u00eate du g\u00e9nie\", \"F\u00eate du travail\",\n \"F\u00eate de l'opinion\", \"F\u00eate des r\u00e9compenses\", \"F\u00eate de la R\u00e9volution\"\n )\n\n val introductionDate = LocalDate.of(1792, 9, 22)\n }\n}\n\nfun LocalDate.toFrenchRCDate(): FrenchRCDate {\n val daysDiff = DAYS.between(FrenchRCDate.introductionDate, this).toInt() + 1\n if (daysDiff <= 0) throw IllegalArgumentException(\"Date can't be before 22 September 1792\")\n var year = 1\n var startDay = 1\n while (true) {\n val endDay = startDay + if (FrenchRCDate.isLeapYear(year)) 365 else 364\n if (daysDiff in startDay..endDay) break\n year++\n startDay = endDay + 1\n }\n val remDays = daysDiff - startDay\n val month = remDays / 30\n val day = remDays - month * 30\n return FrenchRCDate(year, month + 1, day + 1)\n}\n\nfun main(args: Array) {\n val formatter = DateTimeFormatter.ofPattern(\"d MMMM yyyy\")\n val dates = arrayOf(\"22 September 1792\", \"20 May 1795\", \"15 July 1799\", \"23 September 1803\",\n \"31 December 1805\", \"18 March 1871\", \"25 August 1944\", \"19 September 2016\",\n \"22 September 2017\", \"28 September 2017\")\n val frcDates = Array(dates.size) { \"\" }\n for ((i, date) in dates.withIndex()) {\n val thisDate = LocalDate.parse(date, formatter)\n val frcd = thisDate.toFrenchRCDate()\n frcDates[i] = frcd.toString()\n println(\"${date.padEnd(25)} => $frcd\")\n }\n\n // now process the other way around\n println()\n for (frcDate in frcDates) {\n val thisDate = FrenchRCDate.parse(frcDate)\n val lds = formatter.format(thisDate.toLocalDate())\n println(\"${frcDate.padEnd(25)} => $lds\")\n }\n}"} {"title": "Function prototype", "language": "Kotlin", "task": "Some languages provide the facility to declare functions and subroutines through the use of function prototyping. \n\n\n;Task:\nDemonstrate the methods available for declaring prototypes within the language. The provided solutions should include:\n\n* An explanation of any placement restrictions for prototype declarations\n* A prototype declaration for a function that does not require arguments\n* A prototype declaration for a function that requires two arguments\n* A prototype declaration for a function that utilizes varargs\n* A prototype declaration for a function that utilizes optional arguments\n* A prototype declaration for a function that utilizes named parameters\n* Example of prototype declarations for subroutines or procedures (if these differ from functions)\n* An explanation and example of any special forms of prototyping not covered by the above\n\n\nLanguages that do not provide function prototyping facilities should be omitted from this task.\n\n", "solution": "// version 1.0.6\n\ninterface MyInterface {\n fun foo() // no arguments, no return type\n fun goo(i: Int, j: Int) // two arguments, no return type\n fun voo(vararg v: Int) // variable number of arguments, no return type\n fun ooo(o: Int = 1): Int // optional argument with default value and return type Int\n fun roo(): Int // no arguments with return type Int\n val poo: Int // read only property of type Int\n}\n\nabstract class MyAbstractClass {\n abstract fun afoo() // abstract member function, no arguments or return type\n abstract var apoo: Int // abstract read/write member property of type Int\n}\n\nclass Derived : MyAbstractClass(), MyInterface {\n override fun afoo() {}\n override var apoo: Int = 0\n\n override fun foo() {}\n override fun goo(i: Int, j: Int) {}\n override fun voo(vararg v: Int) {}\n override fun ooo(o: Int): Int = o // can't specify default argument again here but same as in interface\n override fun roo(): Int = 2\n override val poo: Int = 3\n}\n\nfun main(args: Array) {\n val d = Derived()\n println(d.apoo)\n println(d.ooo()) // default argument of 1 inferred\n println(d.roo())\n println(d.poo)\n}"} {"title": "Functional coverage tree", "language": "Kotlin", "task": "Functional coverage is a measure of how much a particular function of a system \nhas been verified as correct. It is used heavily in tracking the completeness \nof the verification of complex System on Chip (SoC) integrated circuits, where \nit can also be used to track how well the functional ''requirements'' of the \nsystem have been verified.\n\nThis task uses a sub-set of the calculations sometimes used in tracking \nfunctional coverage but uses a more familiar(?) scenario.\n\n;Task Description:\nThe head of the clean-up crews for \"The Men in a very dark shade of grey when \nviewed at night\" has been tasked with managing the cleansing of two properties\nafter an incident involving aliens.\n\nShe arranges the task hierarchically with a manager for the crews working on \neach house who return with a breakdown of how they will report on progress in \neach house.\n\nThe overall hierarchy of (sub)tasks is as follows, \ncleaning\n house1\n bedrooms\n bathrooms\n bathroom1\n bathroom2\n outside lavatory\n attic\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n basement\n garage\n garden\n house2\n upstairs\n bedrooms\n suite 1\n suite 2\n bedroom 3\n bedroom 4\n bathroom\n toilet\n attics\n groundfloor\n kitchen\n living rooms\n lounge\n dining room\n conservatory\n playroom\n wet room & toilet\n garage\n garden\n hot tub suite\n basement\n cellars\n wine cellar\n cinema\n\nThe head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit.\n\nSome time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0.\nNAME_HIERARCHY |WEIGHT |COVERAGE |\ncleaning | | |\n house1 |40 | |\n bedrooms | |0.25 |\n bathrooms | | |\n bathroom1 | |0.5 |\n bathroom2 | | |\n outside_lavatory | |1 |\n attic | |0.75 |\n kitchen | |0.1 |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | |1 |\n basement | | |\n garage | | |\n garden | |0.8 |\n house2 |60 | |\n upstairs | | |\n bedrooms | | |\n suite_1 | | |\n suite_2 | | |\n bedroom_3 | | |\n bedroom_4 | | |\n bathroom | | |\n toilet | | |\n attics | |0.6 |\n groundfloor | | |\n kitchen | | |\n living_rooms | | |\n lounge | | |\n dining_room | | |\n conservatory | | |\n playroom | | |\n wet_room_&_toilet | | |\n garage | | |\n garden | |0.9 |\n hot_tub_suite | |1 |\n basement | | |\n cellars | |1 |\n wine_cellar | |1 |\n cinema | |0.75 |\n\n;Calculation:\nThe coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree.\n\n'''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes.\n\n;Extra Credit:\nAfter calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node.\nThe power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children.\n\nThe pseudo code would be:\n\n method delta_calculation(this, power):\n sum_of_weights = sum(node.weight for node in children)\n this.delta = (1 - this.coverage) * power\n for node in self.children:\n node.delta_calculation(power * node.weight / sum_of_weights)\n return this.delta\n\nFollowed by a call to:\n\n top.delta_calculation(power=1)\n\n\n'''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.\n\n", "solution": "// version 1.2.10\n\nclass FCNode(val name: String, val weight: Int = 1, coverage: Double = 0.0) {\n\n var coverage = coverage\n set(value) {\n if (field != value) {\n field = value\n // update any parent's coverage\n if (parent != null) parent!!.updateCoverage()\n }\n }\n\n val children = mutableListOf()\n var parent: FCNode? = null\n\n fun addChildren(nodes: List) {\n children.addAll(nodes)\n nodes.forEach { it.parent = this }\n updateCoverage()\n }\n\n private fun updateCoverage() {\n val v1 = children.sumByDouble { it.weight * it.coverage }\n val v2 = children.sumBy { it.weight }\n coverage = v1 / v2\n }\n\n fun show(level: Int = 0) {\n val indent = level * 4\n val nl = name.length + indent\n print(name.padStart(nl))\n print(\"|\".padStart(32 - nl))\n print(\" %3d |\".format(weight))\n println(\" %8.6f |\".format(coverage))\n if (children.size == 0) return\n for (child in children) child.show(level + 1)\n }\n}\n\nval houses = listOf(\n FCNode(\"house1\", 40),\n FCNode(\"house2\", 60)\n)\n\nval house1 = listOf(\n FCNode(\"bedrooms\", 1, 0.25),\n FCNode(\"bathrooms\"),\n FCNode(\"attic\", 1, 0.75),\n FCNode(\"kitchen\", 1, 0.1),\n FCNode(\"living_rooms\"),\n FCNode(\"basement\"),\n FCNode(\"garage\"),\n FCNode(\"garden\", 1, 0.8)\n)\n\nval house2 = listOf(\n FCNode(\"upstairs\"),\n FCNode(\"groundfloor\"),\n FCNode(\"basement\")\n)\n\nval h1Bathrooms = listOf(\n FCNode(\"bathroom1\", 1, 0.5),\n FCNode(\"bathroom2\"),\n FCNode(\"outside_lavatory\", 1, 1.0)\n)\n\nval h1LivingRooms = listOf(\n FCNode(\"lounge\"),\n FCNode(\"dining_room\"),\n FCNode(\"conservatory\"),\n FCNode(\"playroom\", 1, 1.0)\n)\n\nval h2Upstairs = listOf(\n FCNode(\"bedrooms\"),\n FCNode(\"bathroom\"),\n FCNode(\"toilet\"),\n FCNode(\"attics\", 1, 0.6)\n)\n\nval h2Groundfloor = listOf(\n FCNode(\"kitchen\"),\n FCNode(\"living_rooms\"),\n FCNode(\"wet_room_&_toilet\"),\n FCNode(\"garage\"),\n FCNode(\"garden\", 1, 0.9),\n FCNode(\"hot_tub_suite\", 1, 1.0)\n)\n\nval h2Basement = listOf(\n FCNode(\"cellars\", 1, 1.0),\n FCNode(\"wine_cellar\", 1, 1.0),\n FCNode(\"cinema\", 1, 0.75)\n)\n\nval h2UpstairsBedrooms = listOf(\n FCNode(\"suite_1\"),\n FCNode(\"suite_2\"),\n FCNode(\"bedroom_3\"),\n FCNode(\"bedroom_4\")\n)\n\nval h2GroundfloorLivingRooms = listOf(\n FCNode(\"lounge\"),\n FCNode(\"dining_room\"),\n FCNode(\"conservatory\"),\n FCNode(\"playroom\")\n)\n\nfun main(args: Array) {\n val cleaning = FCNode(\"cleaning\")\n\n house1[1].addChildren(h1Bathrooms)\n house1[4].addChildren(h1LivingRooms)\n houses[0].addChildren(house1)\n\n h2Upstairs[0].addChildren(h2UpstairsBedrooms)\n house2[0].addChildren(h2Upstairs)\n h2Groundfloor[1].addChildren(h2GroundfloorLivingRooms)\n house2[1].addChildren(h2Groundfloor)\n house2[2].addChildren(h2Basement)\n houses[1].addChildren(house2)\n\n cleaning.addChildren(houses)\n val topCoverage = cleaning.coverage\n println(\"TOP COVERAGE = ${\"%8.6f\".format(topCoverage)}\\n\")\n println(\"NAME HIERARCHY | WEIGHT | COVERAGE |\")\n cleaning.show()\n\n h2Basement[2].coverage = 1.0 // change Cinema node coverage to 1.0\n val diff = cleaning.coverage - topCoverage\n println(\"\\nIf the coverage of the Cinema node were increased from 0.75 to 1.0\")\n print(\"the top level coverage would increase by \")\n println(\"${\"%8.6f\".format(diff)} to ${\"%8.6f\".format(topCoverage + diff)}\") \n h2Basement[2].coverage = 0.75 // restore to original value if required\n}"} {"title": "Fusc sequence", "language": "Kotlin from Go", "task": "Definitions:\nThe '''fusc''' integer sequence is defined as:\n::* fusc(0) = 0\n::* fusc(1) = 1\n::* for '''n'''>1, the '''n'''th term is defined as:\n::::* if '''n''' is even; fusc(n) = fusc(n/2)\n::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2)\n\n\nNote that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).\n\n\n\n;An observation:\n:::::* fusc(A) = fusc(B)\n\nwhere '''A''' is some non-negative integer expressed in binary, and\nwhere '''B''' is the binary value of '''A''' reversed.\n\n\n\nFusc numbers are also known as:\n::* fusc function (named by Dijkstra, 1982)\n::* Stern's Diatomic series (although it starts with unity, not zero)\n::* Stern-Brocot sequence (although it starts with unity, not zero)\n\n\n\n;Task:\n::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.\n::* show the fusc number (and its index) whose length is greater than any previous fusc number length.\n::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)\n::* show all numbers with commas (if appropriate).\n::* show all output here.\n\n\n;Related task:\n::* RosettaCode Stern-Brocot sequence\n\n\n\n;Also see:\n::* the MathWorld entry: Stern's Diatomic Series.\n::* the OEIS entry: A2487.\n\n", "solution": "// Version 1.3.21\n\nfun fusc(n: Int): IntArray {\n if (n <= 0) return intArrayOf()\n if (n == 1) return intArrayOf(0)\n val res = IntArray(n)\n res[1] = 1\n for (i in 2 until n) {\n if (i % 2 == 0) {\n res[i] = res[i / 2]\n } else {\n res[i] = res[(i - 1) / 2] + res[(i + 1) / 2]\n }\n }\n return res\n}\n\nfun fuscMaxLen(n: Int): List> {\n var maxLen = -1\n var maxFusc = -1\n val f = fusc(n)\n val res = mutableListOf>()\n for (i in 0 until n) {\n if (f[i] <= maxFusc) continue // avoid string conversion\n maxFusc = f[i]\n val len = f[i].toString().length\n if (len > maxLen) {\n res.add(Pair(i, f[i]))\n maxLen = len\n }\n }\n return res\n}\n\nfun main() {\n println(\"The first 61 fusc numbers are:\")\n println(fusc(61).asList())\n println(\"\\nThe fusc numbers whose length > any previous fusc number length are:\")\n val res = fuscMaxLen(20_000_000) // examine first 20 million numbers say\n for (r in res) {\n System.out.printf(\"%,7d (index %,10d)\\n\", r.second, r.first)\n }\n}"} {"title": "Gapful numbers", "language": "Kotlin from Java", "task": "Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the\nfirst and last digit are known as '''gapful numbers'''.\n\n\n''Evenly divisible'' means divisible with no remainder.\n\n\nAll one- and two-digit numbers have this property and are trivially excluded. Only\nnumbers >= '''100''' will be considered for this Rosetta Code task.\n\n\n;Example:\n'''187''' is a '''gapful''' number because it is evenly divisible by the\nnumber '''17''' which is formed by the first and last decimal digits\nof '''187'''. \n\n\nAbout 7.46% of positive integers are ''gapful''. \n\n\n;Task:\n:* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page\n:* Show the first '''30''' gapful numbers\n:* Show the first '''15''' gapful numbers >= '''1,000,000'''\n:* Show the first '''10''' gapful numbers >= '''1,000,000,000'''\n\n\n;Related tasks:\n:* Harshad or Niven series.\n:* palindromic gapful numbers.\n:* largest number divisible by its digits.\n\n\n;Also see:\n:* The OEIS entry: A108343 gapful numbers.\n:* numbersaplenty gapful numbers\n\n", "solution": "private fun commatize(n: Long): String {\n val sb = StringBuilder(n.toString())\n val le = sb.length\n var i = le - 3\n while (i >= 1) {\n sb.insert(i, ',')\n i -= 3\n }\n return sb.toString()\n}\n\nfun main() {\n val starts = listOf(1e2.toLong(), 1e6.toLong(), 1e7.toLong(), 1e9.toLong(), 7123.toLong())\n val counts = listOf(30, 15, 15, 10, 25)\n for (i in starts.indices) {\n var count = 0\n var j = starts[i]\n var pow: Long = 100\n while (j >= pow * 10) {\n pow *= 10\n }\n System.out.printf(\n \"First %d gapful numbers starting at %s:\\n\",\n counts[i],\n commatize(starts[i])\n )\n while (count < counts[i]) {\n val fl = j / pow * 10 + j % 10\n if (j % fl == 0L) {\n System.out.printf(\"%d \", j)\n count++\n }\n j++\n if (j >= 10 * pow) {\n pow *= 10\n }\n }\n println('\\n')\n }\n}"} {"title": "Gauss-Jordan matrix inversion", "language": "Kotlin", "task": "Invert matrix '''A''' using Gauss-Jordan method.\n\n'''A''' being an '''n''' x '''n''' matrix.\n\n", "solution": "// version 1.2.21\n\ntypealias Matrix = Array\n\nfun Matrix.inverse(): Matrix {\n val len = this.size\n require(this.all { it.size == len }) { \"Not a square matrix\" }\n val aug = Array(len) { DoubleArray(2 * len) }\n for (i in 0 until len) {\n for (j in 0 until len) aug[i][j] = this[i][j]\n // augment by identity matrix to right\n aug[i][i + len] = 1.0\n }\n aug.toReducedRowEchelonForm()\n val inv = Array(len) { DoubleArray(len) }\n // remove identity matrix to left\n for (i in 0 until len) {\n for (j in len until 2 * len) inv[i][j - len] = aug[i][j]\n }\n return inv\n}\n\nfun Matrix.toReducedRowEchelonForm() {\n var lead = 0\n val rowCount = this.size\n val colCount = this[0].size\n for (r in 0 until rowCount) {\n if (colCount <= lead) return\n var i = r\n\n while (this[i][lead] == 0.0) {\n i++\n if (rowCount == i) {\n i = r\n lead++\n if (colCount == lead) return\n }\n }\n\n val temp = this[i]\n this[i] = this[r]\n this[r] = temp\n\n if (this[r][lead] != 0.0) {\n val div = this[r][lead]\n for (j in 0 until colCount) this[r][j] /= div\n }\n\n for (k in 0 until rowCount) {\n if (k != r) {\n val mult = this[k][lead]\n for (j in 0 until colCount) this[k][j] -= this[r][j] * mult\n }\n }\n\n lead++\n }\n}\n\nfun Matrix.printf(title: String) {\n println(title)\n val rowCount = this.size\n val colCount = this[0].size\n\n for (r in 0 until rowCount) {\n for (c in 0 until colCount) {\n if (this[r][c] == -0.0) this[r][c] = 0.0 // get rid of negative zeros\n print(\"${\"% 10.6f\".format(this[r][c])} \")\n }\n println()\n }\n\n println()\n}\n\nfun main(args: Array) {\n val a = arrayOf(\n doubleArrayOf(1.0, 2.0, 3.0),\n doubleArrayOf(4.0, 1.0, 6.0),\n doubleArrayOf(7.0, 8.0, 9.0)\n )\n a.inverse().printf(\"Inverse of A is :\\n\")\n\n val b = arrayOf(\n doubleArrayOf( 2.0, -1.0, 0.0),\n doubleArrayOf(-1.0, 2.0, -1.0),\n doubleArrayOf( 0.0, -1.0, 2.0)\n )\n b.inverse().printf(\"Inverse of B is :\\n\") \n}"} {"title": "Gaussian elimination", "language": "Kotlin from Go", "task": "Solve '''Ax=b''' using Gaussian elimination then backwards substitution. \n\n'''A''' being an '''n''' by '''n''' matrix. \n\nAlso, '''x''' and '''b''' are '''n''' by '''1''' vectors. \n\nTo improve accuracy, please use partial pivoting and scaling.\n\n\n;See also:\n:* the Wikipedia entry: Gaussian elimination\n\n", "solution": "// version 1.1.51\n\nval ta = arrayOf(\n doubleArrayOf(1.00, 0.00, 0.00, 0.00, 0.00, 0.00),\n doubleArrayOf(1.00, 0.63, 0.39, 0.25, 0.16, 0.10),\n doubleArrayOf(1.00, 1.26, 1.58, 1.98, 2.49, 3.13),\n doubleArrayOf(1.00, 1.88, 3.55, 6.70, 12.62, 23.80),\n doubleArrayOf(1.00, 2.51, 6.32, 15.88, 39.90, 100.28),\n doubleArrayOf(1.00, 3.14, 9.87, 31.01, 97.41, 306.02)\n)\n\nval tb = doubleArrayOf(-0.01, 0.61, 0.91, 0.99, 0.60, 0.02)\n\nval tx = doubleArrayOf(\n -0.01, 1.602790394502114, -1.6132030599055613,\n 1.2454941213714368, -0.4909897195846576, 0.065760696175232\n)\n\nconst val EPSILON = 1e-14 // tolerance required\n\nfun gaussPartial(a0: Array, b0: DoubleArray): DoubleArray {\n val m = b0.size\n val a = Array(m) { DoubleArray(m) }\n for ((i, ai) in a0.withIndex()) {\n val row = ai.copyOf(m + 1)\n row[m] = b0[i]\n a[i] = row\n }\n for (k in 0 until a.size) {\n var iMax = 0\n var max = -1.0\n for (i in k until m) {\n val row = a[i]\n // compute scale factor s = max abs in row\n var s = -1.0\n for (j in k until m) {\n val e = Math.abs(row[j])\n if (e > s) s = e\n }\n // scale the abs used to pick the pivot\n val abs = Math.abs(row[k]) / s\n if (abs > max) {\n iMax = i\n max = abs\n }\n }\n if (a[iMax][k] == 0.0) {\n throw RuntimeException(\"Matrix is singular.\")\n }\n val tmp = a[k]\n a[k] = a[iMax]\n a[iMax] = tmp\n for (i in k + 1 until m) {\n for (j in k + 1..m) {\n a[i][j] -= a[k][j] * a[i][k] / a[k][k]\n }\n a[i][k] = 0.0\n }\n }\n val x = DoubleArray(m)\n for (i in m - 1 downTo 0) {\n x[i] = a[i][m]\n for (j in i + 1 until m) {\n x[i] -= a[i][j] * x[j]\n }\n x[i] /= a[i][i]\n }\n return x\n}\n\nfun main(args: Array) {\n val x = gaussPartial(ta, tb)\n println(x.asList())\n for ((i, xi) in x.withIndex()) {\n if (Math.abs(tx[i] - xi) > EPSILON) {\n println(\"Out of tolerance.\")\n println(\"Expected values are ${tx.asList()}\")\n return\n }\n }\n}"} {"title": "Generate Chess960 starting position", "language": "Kotlin", "task": "Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints:\n\n* as in the standard chess game, all eight white pawns must be placed on the second rank.\n* White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints:\n** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them)\n** the King must be between two rooks (with any number of other pieces between them all)\n* Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.)\n\n\nWith those constraints there are '''960''' possible starting positions, thus the name of the variant.\n\n\n;Task:\nThe purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.\n\n", "solution": "object Chess960 : Iterable {\n override fun iterator() = patterns.iterator()\n\n private operator fun invoke(b: String, e: String) {\n if (e.length <= 1) {\n val s = b + e\n if (s.is_valid()) patterns += s\n } else {\n for (i in 0 until e.length) {\n invoke(b + e[i], e.substring(0, i) + e.substring(i + 1))\n }\n }\n }\n\n private fun String.is_valid(): Boolean {\n val k = indexOf('K')\n return indexOf('R') < k && k < lastIndexOf('R') &&\n indexOf('B') % 2 != lastIndexOf('B') % 2\n }\n\n private val patterns = sortedSetOf()\n\n init {\n invoke(\"\", \"KQRRNNBB\")\n }\n}\n\nfun main(args: Array) {\n Chess960.forEachIndexed { i, s -> println(\"$i: $s\") }\n}"} {"title": "Generate random chess position", "language": "Kotlin from Java", "task": "Generate a random chess position in FEN format. \n\nThe position does not have to be realistic or even balanced, but it must comply to the following rules:\n:* there is one and only one king of each color (one black king and one white king);\n:* the kings must not be placed on adjacent squares;\n:* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank);\n:* including the kings, up to 32 pieces of either color can be placed. \n:* There is no requirement for material balance between sides. \n:* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. \n:* it is white's turn.\n:* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1).\n\n\nNo requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.\n\n", "solution": "// version 1.2.0\n\nimport java.util.Random\nimport kotlin.math.abs\n\nval rand = Random()\n\nval grid = List(8) { CharArray(8) }\n\nconst val NUL = '\\u0000'\n\nfun createFen(): String {\n placeKings()\n placePieces(\"PPPPPPPP\", true)\n placePieces(\"pppppppp\", true)\n placePieces(\"RNBQBNR\", false)\n placePieces(\"rnbqbnr\", false)\n return toFen()\n}\n\nfun placeKings() {\n while (true) {\n val r1 = rand.nextInt(8)\n val c1 = rand.nextInt(8)\n val r2 = rand.nextInt(8)\n val c2 = rand.nextInt(8)\n if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {\n grid[r1][c1] = 'K'\n grid[r2][c2] = 'k'\n return\n }\n }\n}\n\nfun placePieces(pieces: String, isPawn: Boolean) {\n val numToPlace = rand.nextInt(pieces.length)\n for (n in 0 until numToPlace) {\n var r: Int\n var c: Int\n do {\n r = rand.nextInt(8)\n c = rand.nextInt(8)\n }\n while (grid[r][c] != NUL || (isPawn && (r == 7 || r == 0)))\n grid[r][c] = pieces[n]\n }\n}\n\nfun toFen(): String {\n val fen = StringBuilder()\n var countEmpty = 0\n for (r in 0..7) {\n for (c in 0..7) {\n val ch = grid[r][c]\n print (\"%2c \".format(if (ch == NUL) '.' else ch))\n if (ch == NUL) {\n countEmpty++\n }\n else {\n if (countEmpty > 0) {\n fen.append(countEmpty)\n countEmpty = 0\n }\n fen.append(ch)\n }\n }\n if (countEmpty > 0) {\n fen.append(countEmpty)\n countEmpty = 0\n }\n fen.append(\"/\")\n println()\n }\n return fen.append(\" w - - 0 1\").toString()\n}\n\nfun main(args: Array) {\n println(createFen())\n}"} {"title": "Generator/Exponential", "language": "Kotlin", "task": "A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.\n \nGenerators are often built on top of coroutines or objects so that the internal state of the object is handled \"naturally\". \n\nGenerators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.\n\n\n;Task:\n* Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size).\n* Use it to create a generator of:\n:::* Squares.\n:::* Cubes. \n* Create a new generator that filters all cubes from the generator of squares.\n* Drop the first 20 values from this last generator of filtered results, and then show the next 10 values.\n\n\nNote that this task ''requires'' the use of generators in the calculation of the result.\n\n\n;Also see:\n* Generator\n\n", "solution": "// version 1.1.0\n// compiled with flag -Xcoroutines=enable to suppress 'experimental' warning\n\nimport kotlin.coroutines.experimental.buildSequence\n\nfun generatePowers(m: Int) =\n buildSequence {\n var n = 0\n val mm = m.toDouble()\n while (true) yield(Math.pow((n++).toDouble(), mm).toLong())\n }\n\nfun generateNonCubicSquares(squares: Sequence, cubes: Sequence) =\n buildSequence {\n val iter2 = squares.iterator()\n val iter3 = cubes.iterator()\n var square = iter2.next()\n var cube = iter3.next()\n while (true) {\n if (square > cube) {\n cube = iter3.next()\n continue\n } else if (square < cube) {\n yield(square)\n }\n square = iter2.next()\n }\n }\n\nfun main(args: Array) {\n val squares = generatePowers(2)\n val cubes = generatePowers(3)\n val ncs = generateNonCubicSquares(squares, cubes)\n print(\"Non-cubic squares (21st to 30th) : \")\n ncs.drop(20).take(10).forEach { print(\"$it \") } // print 21st to 30th items\n println()\n}"} {"title": "Get system command output", "language": "Kotlin", "task": "Task\nExecute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). \n\n;Related task\n* Execute a system command\n\n", "solution": "// version 1.0.6\n\nimport java.util.Scanner\n\nfun main(args: Array) {\n val command = \"cmd /c chcp\"\n val p = Runtime.getRuntime().exec(command)\n val sc = Scanner(p.inputStream)\n println(sc.nextLine())\n sc.close()\n}"} {"title": "Globally replace text in several files", "language": "Kotlin", "task": "Replace every occurring instance of a piece of text in a group of text files with another one. \n\n\nFor this task we want to replace the text \"'''Goodbye London!'''\" with \"'''Hello New York!'''\" for a list of files.\n\n", "solution": "// version 1.2.0\n\nimport java.io.File\n\nfun main(args: Array) {\n val files = arrayOf(\"file1.txt\", \"file2.txt\")\n for (file in files) {\n val f = File(file)\n var text = f.readText()\n println(text)\n text = text.replace(\"Goodbye London!\", \"Hello New York!\")\n f.writeText(text)\n println(f.readText())\n }\n}"} {"title": "Gray code", "language": "Kotlin", "task": "Karnaugh maps in order from left to right or top to bottom.\nCreate functions to encode a number to and decode a number from Gray code. \n\nDisplay the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).\n\nThere are many possible Gray codes. The following encodes what is called \"binary reflected Gray code.\"\n\nEncoding (MSB is bit 0, b is binary, g is Gray code):\n\nif b[i-1] = 1\n g[i] = not b[i]\nelse\n g[i] = b[i]\n\nOr:\n\ng = b xor (b logically right shifted 1 time)\n\nDecoding (MSB is bit 0, b is binary, g is Gray code):\n\nb[0] = g[0]\n\nfor other bits:\nb[i] = g[i] xor b[i-1]\n\n;Reference\n* Converting Between Gray and Binary Codes. It includes step-by-step animations.\n\n", "solution": "// version 1.0.6\n\nobject Gray {\n fun encode(n: Int) = n xor (n shr 1)\n\n fun decode(n: Int): Int {\n var p = n\n var nn = n\n while (nn != 0) {\n nn = nn shr 1\n p = p xor nn\n }\n return p\n }\n}\n\nfun main(args: Array) {\n println(\"Number\\tBinary\\tGray\\tDecoded\")\n for (i in 0..31) {\n print(\"$i\\t${Integer.toBinaryString(i)}\\t\")\n val g = Gray.encode(i)\n println(\"${Integer.toBinaryString(g)}\\t${Gray.decode(g)}\")\n }\n}"} {"title": "Greatest subsequential sum", "language": "Kotlin", "task": "Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. \n\n\nAn empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.\n\n", "solution": "// version 1.1\n\nfun gss(seq: IntArray): Triple {\n if (seq.isEmpty()) throw IllegalArgumentException(\"Array cannot be empty\")\n var sum: Int\n var maxSum = seq[0]\n var first = 0\n var last = 0\n for (i in 1 until seq.size) {\n sum = 0\n for (j in i until seq.size) {\n sum += seq[j]\n if (sum > maxSum) {\n maxSum = sum\n first = i\n last = j\n }\n }\n }\n return Triple(maxSum, first, last)\n}\n\nfun main(args: Array) {\n val seq = intArrayOf(-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1)\n val(maxSum, first, last) = gss(seq)\n if (maxSum > 0) {\n println(\"Maximum subsequence is from indices $first to $last\")\n print(\"Elements are : \")\n for (i in first .. last) print(\"${seq[i]} \")\n println(\"\\nSum is $maxSum\")\n }\n else\n println(\"Maximum subsequence is the empty sequence which has a sum of 0\")\n}"} {"title": "Greedy algorithm for Egyptian fractions", "language": "Kotlin", "task": "An Egyptian fraction is the sum of distinct unit fractions such as: \n\n:::: \\tfrac{1}{2} + \\tfrac{1}{3} + \\tfrac{1}{16} \\,(= \\tfrac{43}{48}) \n\nEach fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). \n\nFibonacci's Greedy algorithm for Egyptian fractions expands the fraction \\tfrac{x}{y} to be represented by repeatedly performing the replacement\n\n:::: \\frac{x}{y} = \\frac{1}{\\lceil y/x\\rceil} + \\frac{(-y)\\!\\!\\!\\!\\mod x}{y\\lceil y/x\\rceil} \n\n\n(simplifying the 2nd term in this replacement as necessary, and where \\lceil x \\rceil is the ''ceiling'' function).\n\n\n\nFor this task, Proper and improper fractions must be able to be expressed.\n\n\nProper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that a < b, and \n\nimproper fractions are of the form \\tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. \n\n\n(See the REXX programming example to view one method of expressing the whole number part of an improper fraction.)\n\nFor improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n''].\n\n\n;Task requirements:\n* show the Egyptian fractions for: \\tfrac{43}{48} and \\tfrac{5}{121} and \\tfrac{2014}{59} \n* for all proper fractions, \\tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has:\n::* the largest number of terms,\n::* the largest denominator.\n* for all one-, two-, and three-digit integers, find and show (as above). {extra credit}\n\n\n;Also see:\n* Wolfram MathWorld(tm) entry: Egyptian fraction\n\n", "solution": "// version 1.2.10\n\nimport java.math.BigInteger\nimport java.math.BigDecimal\nimport java.math.MathContext\n\nval bigZero = BigInteger.ZERO\nval bigOne = BigInteger.ONE\nval bdZero = BigDecimal.ZERO\nval context = MathContext.UNLIMITED\n\nfun gcd(a: BigInteger, b: BigInteger): BigInteger\n = if (b == bigZero) a else gcd(b, a % b)\n\nclass Frac : Comparable {\n val num: BigInteger\n val denom: BigInteger\n\n constructor(n: BigInteger, d: BigInteger) {\n require(d != bigZero)\n var nn = n\n var dd = d\n if (nn == bigZero) {\n dd = bigOne\n }\n else if (dd < bigZero) {\n nn = -nn\n dd = -dd\n }\n val g = gcd(nn, dd).abs()\n if (g > bigOne) {\n nn /= g\n dd /= g\n }\n num = nn\n denom = dd\n }\n\n constructor(n: Int, d: Int) : this(n.toBigInteger(), d.toBigInteger())\n\n operator fun plus(other: Frac) =\n Frac(num * other.denom + denom * other.num, other.denom * denom)\n\n operator fun unaryMinus() = Frac(-num, denom)\n\n operator fun minus(other: Frac) = this + (-other)\n\n override fun compareTo(other: Frac): Int {\n val diff = this.toBigDecimal() - other.toBigDecimal()\n return when {\n diff < bdZero -> -1\n diff > bdZero -> +1\n else -> 0\n }\n }\n\n override fun equals(other: Any?): Boolean {\n if (other == null || other !is Frac) return false\n return this.compareTo(other) == 0\n }\n\n override fun toString() = if (denom == bigOne) \"$num\" else \"$num/$denom\"\n\n fun toBigDecimal() = num.toBigDecimal() / denom.toBigDecimal()\n\n fun toEgyptian(): List {\n if (num == bigZero) return listOf(this)\n val fracs = mutableListOf()\n if (num.abs() >= denom.abs()) {\n val div = Frac(num / denom, bigOne)\n val rem = this - div\n fracs.add(div)\n toEgyptian(rem.num, rem.denom, fracs)\n }\n else {\n toEgyptian(num, denom, fracs)\n }\n return fracs \n }\n\n private tailrec fun toEgyptian(\n n: BigInteger, \n d: BigInteger,\n fracs: MutableList\n ) {\n if (n == bigZero) return\n val n2 = n.toBigDecimal()\n val d2 = d.toBigDecimal()\n var divRem = d2.divideAndRemainder(n2, context)\n var div = divRem[0].toBigInteger()\n if (divRem[1] > bdZero) div++\n fracs.add(Frac(bigOne, div))\n var n3 = (-d) % n\n if (n3 < bigZero) n3 += n\n val d3 = d * div\n val f = Frac(n3, d3)\n if (f.num == bigOne) {\n fracs.add(f)\n return\n }\n toEgyptian(f.num, f.denom, fracs)\n }\n}\n\nfun main(args: Array) {\n val fracs = listOf(Frac(43, 48), Frac(5, 121), Frac(2014,59))\n for (frac in fracs) {\n val list = frac.toEgyptian()\n if (list[0].denom == bigOne) {\n val first = \"[${list[0]}]\"\n println(\"$frac -> $first + ${list.drop(1).joinToString(\" + \")}\")\n }\n else {\n println(\"$frac -> ${list.joinToString(\" + \")}\")\n }\n }\n\n for (r in listOf(98, 998)) {\n if (r == 98)\n println(\"\\nFor proper fractions with 1 or 2 digits:\")\n else\n println(\"\\nFor proper fractions with 1, 2 or 3 digits:\")\n var maxSize = 0\n var maxSizeFracs = mutableListOf()\n var maxDen = bigZero\n var maxDenFracs = mutableListOf()\n val sieve = List(r + 1) { BooleanArray(r + 2) } // to eliminate duplicates\n for (i in 1..r) {\n for (j in (i + 1)..(r + 1)) {\n if (sieve[i][j]) continue\n val f = Frac(i, j)\n val list = f.toEgyptian()\n val listSize = list.size\n if (listSize > maxSize) {\n maxSize = listSize\n maxSizeFracs.clear()\n maxSizeFracs.add(f)\n }\n else if (listSize == maxSize) {\n maxSizeFracs.add(f)\n }\n val listDen = list[list.lastIndex].denom\n if (listDen > maxDen) {\n maxDen = listDen\n maxDenFracs.clear()\n maxDenFracs.add(f)\n }\n else if (listDen == maxDen) {\n maxDenFracs.add(f)\n }\n if (i < r / 2) {\n var k = 2\n while (true) {\n if (j * k > r + 1) break\n sieve[i * k][j * k] = true\n k++\n }\n }\n } \n }\n println(\" largest number of items = $maxSize\")\n println(\" fraction(s) with this number : $maxSizeFracs\")\n val md = maxDen.toString()\n print(\" largest denominator = ${md.length} digits, \")\n println(\"${md.take(20)}...${md.takeLast(20)}\")\n println(\" fraction(s) with this denominator : $maxDenFracs\")\n }\n}"} {"title": "Greyscale bars/Display", "language": "Kotlin from Java", "task": "The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. \n\nFor the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars)\n\nFor the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars).\n\nHalfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.\n\n", "solution": "// version 1.1\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport javax.swing.JFrame\n\nclass GreyBars : JFrame(\"grey bars example!\") {\n private val w: Int\n private val h: Int\n\n init {\n w = 640\n h = 320\n setSize(w, h)\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n isVisible = true\n }\n\n override fun paint(g: Graphics) {\n var run = 0\n var colorComp: Double // component of the color\n var columnCount = 8\n while (columnCount < 128) {\n var colorGap = 255.0 / (columnCount - 1) // by this gap we change the background color\n val columnWidth = w / columnCount\n val columnHeight = h / 4\n if (run % 2 == 0) // switches color directions with each iteration of while loop\n colorComp = 0.0\n else {\n colorComp = 255.0\n colorGap *= -1.0\n }\n val ystart = columnHeight * run\n var xstart = 0\n for (i in 0 until columnCount) {\n val iColor = Math.round(colorComp).toInt()\n val nextColor = Color(iColor, iColor, iColor)\n g.color = nextColor\n g.fillRect(xstart, ystart, columnWidth, columnHeight)\n xstart += columnWidth\n\t colorComp += colorGap\n\t }\n run++\n columnCount *= 2\n }\n }\n}\n\nfun main(args: Array) {\n GreyBars()\n}"} {"title": "Hailstone sequence", "language": "Kotlin", "task": "The Hailstone sequence of numbers can be generated from a starting positive integer, n by:\n* If n is '''1''' then the sequence ends.\n* If n is '''even''' then the next n of the sequence = n/2 \n* If n is '''odd''' then the next n of the sequence = (3 * n) + 1 \n\n\nThe (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.\n\n\nThis sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the):\n:::* hailstone sequence, hailstone numbers\n:::* 3x + 2 mapping, 3n + 1 problem\n:::* Collatz sequence\n:::* Hasse's algorithm\n:::* Kakutani's problem\n:::* Syracuse algorithm, Syracuse problem\n:::* Thwaites conjecture \n:::* Ulam's problem\n\n\nThe hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud).\n\n\n;Task:\n# Create a routine to generate the hailstone sequence for a number.\n# Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1\n# Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!)\n\n\n;See also:\n* xkcd (humourous).\n* The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf).\n* The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).\n\n", "solution": "import java.util.ArrayDeque\n\nfun hailstone(n: Int): ArrayDeque {\n val hails = when {\n n == 1 -> ArrayDeque()\n n % 2 == 0 -> hailstone(n / 2)\n else -> hailstone(3 * n + 1)\n }\n hails.addFirst(n)\n return hails\n}\n\nfun main(args: Array) {\n val hail27 = hailstone(27)\n fun showSeq(s: List) = s.map { it.toString() }.reduce { a, b -> a + \", \" + b }\n println(\"Hailstone sequence for 27 is \" + showSeq(hail27.take(3)) + \" ... \"\n + showSeq(hail27.drop(hail27.size - 3)) + \" with length ${hail27.size}.\")\n\n var longestHail = hailstone(1)\n for (x in 1..99999)\n longestHail = arrayOf(hailstone(x), longestHail).maxBy { it.size } ?: longestHail\n println(\"${longestHail.first} is the number less than 100000 with \" +\n \"the longest sequence, having length ${longestHail.size}.\")\n}"} {"title": "Harshad or Niven series", "language": "Kotlin", "task": "The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. \n\nFor example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder.\n\nAssume that the series is defined as the numbers in increasing order.\n\n\n;Task:\nThe task is to create a function/method/procedure to generate successive members of the Harshad sequence. \n\nUse it to:\n::* list the first '''20''' members of the sequence, and\n::* list the first Harshad number greater than '''1000'''.\n\n\nShow your output here.\n\n\n;Related task\n:* Increasing gaps between consecutive Niven numbers\n\n\n;See also\n* OEIS: A005349\n\n", "solution": "// version 1.1\n\nfun sumDigits(n: Int): Int = when {\n n <= 0 -> 0\n else -> {\n var sum = 0\n var nn = n\n while (nn > 0) {\n sum += nn % 10\n nn /= 10\n }\n sum\n }\n }\n\nfun isHarshad(n: Int): Boolean = (n % sumDigits(n) == 0)\n\nfun main(args: Array) {\n println(\"The first 20 Harshad numbers are:\")\n var count = 0\n var i = 0\n\n while (true) {\n if (isHarshad(++i)) {\n print(\"$i \")\n if (++count == 20) break\n }\n }\n\n println(\"\\n\\nThe first Harshad number above 1000 is:\")\n i = 1000\n\n while (true) {\n if (isHarshad(++i)) {\n println(i)\n return\n }\n }\n}"} {"title": "Hash join", "language": "Kotlin", "task": "{| class=\"wikitable\"\n|-\n! Input\n! Output\n|-\n|\n\n{| style=\"border:none; border-collapse:collapse;\"\n|-\n| style=\"border:none\" | ''A'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Age !! Name\n|-\n| 27 || Jonah\n|-\n| 18 || Alan\n|-\n| 28 || Glory\n|-\n| 18 || Popeye\n|-\n| 28 || Alan\n|}\n\n| style=\"border:none; padding-left:1.5em;\" rowspan=\"2\" |\n| style=\"border:none\" | ''B'' = \n| style=\"border:none\" |\n\n{| class=\"wikitable\"\n|-\n! Character !! Nemesis\n|-\n| Jonah || Whales\n|-\n| Jonah || Spiders\n|-\n| Alan || Ghosts\n|-\n| Alan || Zombies\n|-\n| Glory || Buffy\n|}\n\n|-\n| style=\"border:none\" | ''jA'' =\n| style=\"border:none\" | Name (i.e. column 1)\n\n| style=\"border:none\" | ''jB'' =\n| style=\"border:none\" | Character (i.e. column 0)\n|}\n\n|\n\n{| class=\"wikitable\" style=\"margin-left:1em\"\n|-\n! A.Age !! A.Name !! B.Character !! B.Nemesis\n|-\n| 27 || Jonah || Jonah || Whales\n|-\n| 27 || Jonah || Jonah || Spiders\n|-\n| 18 || Alan || Alan || Ghosts\n|-\n| 18 || Alan || Alan || Zombies\n|-\n| 28 || Glory || Glory || Buffy\n|-\n| 28 || Alan || Alan || Ghosts\n|-\n| 28 || Alan || Alan || Zombies\n|}\n\n|}\n\nThe order of the rows in the output table is not significant.\nIf you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, \"Jonah\"], [\"Jonah\", \"Whales\"]].\n\n\n", "solution": "data class A(val age: Int, val name: String)\n\ndata class B(val character: String, val nemesis: String)\n\ndata class C(val rowA: A, val rowB: B)\n\nfun hashJoin(tableA: List, tableB: List): List {\n val mm = tableB.groupBy { it.character }\n val tableC = mutableListOf()\n for (a in tableA) {\n val value = mm[a.name] ?: continue\n for (b in value) tableC.add(C(a, b))\n }\n return tableC.toList()\n}\n\nfun main(args: Array) {\n val tableA = listOf(\n A(27, \"Jonah\"),\n A(18, \"Alan\"),\n A(28, \"Glory\"),\n A(18, \"Popeye\"),\n A(28, \"Alan\")\n )\n val tableB = listOf(\n B(\"Jonah\", \"Whales\"),\n B(\"Jonah\", \"Spiders\"),\n B(\"Alan\", \"Ghosts\"),\n B(\"Alan\", \"Zombies\"),\n B(\"Glory\", \"Buffy\")\n )\n val tableC = hashJoin(tableA, tableB)\n println(\"A.Age A.Name B.Character B.Nemesis\")\n println(\"----- ------ ----------- ---------\")\n for (c in tableC) {\n print(\"${c.rowA.age} ${c.rowA.name.padEnd(6)} \")\n println(\"${c.rowB.character.padEnd(6)} ${c.rowB.nemesis}\")\n }\n}"} {"title": "Haversine formula", "language": "Kotlin from Groovy", "task": "{{Wikipedia}}\n\n\nThe '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. \n\nIt is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical \"triangles\".\n\n\n;Task:\nImplement a great-circle distance function, or use a library function, \nto show the great-circle distance between:\n* Nashville International Airport (BNA) in Nashville, TN, USA, which is: \n '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-\n* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:\n '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) \n\n\nUser Kaimbridge clarified on the Talk page:\n\n -- 6371.0 km is the authalic radius based on/extracted from surface area;\n -- 6372.8 km is an approximation of the radius of the average circumference\n (i.e., the average great-elliptic or great-circle radius), where the\n boundaries are the meridian (6367.45 km) and the equator (6378.14 km).\n\nUsing either of these values results, of course, in differing distances:\n\n 6371.0 km -> 2886.44444283798329974715782394574671655 km;\n 6372.8 km -> 2887.25995060711033944886005029688505340 km;\n (results extended for accuracy check: Given that the radii are only\n approximations anyways, .01' 1.0621333 km and .001\" .00177 km,\n practical precision required is certainly no greater than about\n .0000001----i.e., .1 mm!)\n\nAs distances are segments of great circles/circumferences, it is\nrecommended that the latter value (r = 6372.8 km) be used (which\nmost of the given solutions have already adopted, anyways). \n\n\nMost of the examples below adopted Kaimbridge's recommended value of\n6372.8 km for the earth radius. However, the derivation of this\nellipsoidal quadratic mean radius\nis wrong (the averaging over azimuth is biased). When applying these\nexamples in real applications, it is better to use the\nmean earth radius,\n6371 km. This value is recommended by the International Union of\nGeodesy and Geophysics and it minimizes the RMS relative error between the\ngreat circle and geodesic distance.\n\n", "solution": "import java.lang.Math.*\n\nconst val R = 6372.8 // in kilometers\n\nfun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {\n val \u03bb1 = toRadians(lat1)\n val \u03bb2 = toRadians(lat2)\n val \u0394\u03bb = toRadians(lat2 - lat1)\n val \u0394\u03c6 = toRadians(lon2 - lon1)\n return 2 * R * asin(sqrt(pow(sin(\u0394\u03bb / 2), 2.0) + pow(sin(\u0394\u03c6 / 2), 2.0) * cos(\u03bb1) * cos(\u03bb2)))\n}\n\nfun main(args: Array) = println(\"result: \" + haversine(36.12, -86.67, 33.94, -118.40))"} {"title": "Hello world/Newbie", "language": "Kotlin", "task": "Guide a new user of a language through the steps necessary \nto install the programming language and selection of a text editor if needed, \nto run the languages' example in the [[Hello world/Text]] task.\n* Assume the language-newbie is a programmer in another language.\n* Assume the language-newbie is competent in installing software for the platform.\n* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).\n* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).\n* Remember to state where to view the output.\n* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.\n\n\n;Note:\n* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.\n* You may use sub-headings if giving instructions for multiple platforms.\n\n", "solution": "fun main(args: Array) {\n println(\"Hello, World!\")\n}"} {"title": "Here document", "language": "Kotlin", "task": "A ''here document'' (or \"heredoc\") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. \n\nDepending on the language being used, a ''here document'' is constructed using a command followed by \"<<\" (or some other symbol) followed by a token string. \n\nThe text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.\n\n\n;Task:\nDemonstrate the use of ''here documents'' within the language.\n\n;Related task:\n* [[Documentation]]\n\n", "solution": "// version 1.1.0\n\nfun main(args: Array) {\n val ev = \"embed variables\"\n\n val here = \"\"\"\n This is a raw string literal \n which does not treat escaped characters \n (\\t, \\b, \\n, \\r, \\', \\\", \\\\, \\$ and \\u)\n specially and can contain new lines,\n indentation and other whitespace\n within the string.\n \n\"Quotes\" or doubled \"\"quotes\"\" can\nbe included without problem but not\ntripled quotes.\n\n It's also possible to $ev\n in a raw string literal using string\n interpolation. \n\n If you need to include a\n literal ${'$'} sign in a raw string literal then\n don't worry you've just done it!\n \"\"\"\n\n println(here)\n}"} {"title": "Heronian triangles", "language": "Kotlin from Scala", "task": "Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:\n\n:::: A = \\sqrt{s(s-a)(s-b)(s-c)},\n\nwhere ''s'' is half the perimeter of the triangle; that is,\n\n:::: s=\\frac{a+b+c}{2}.\n\n'''Heronian triangles'''\nare triangles whose sides ''and area'' are all integers.\n: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). \n\n\nNote that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.\n\nDefine a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor \nof all three sides is '''1''' (unity). \n\nThis will exclude, for example, triangle '''6, 8, 10.'''\n\n\n;Task:\n# Create a named function/method/procedure/... that implements Hero's formula.\n# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.\n# Show the count of how many triangles are found.\n# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths\n# Show the first ten ordered triangles in a table of sides, perimeter, and area.\n# Show a similar ordered table for those triangles with area = 210\n\n\nShow all output here.\n\n'''Note''': when generating triangles it may help to restrict a <= b <= c\n", "solution": "import java.util.ArrayList\n\nobject Heron {\n private val n = 200\n\n fun run() {\n val l = ArrayList()\n for (c in 1..n)\n for (b in 1..c)\n for (a in 1..b)\n if (gcd(gcd(a, b), c) == 1) {\n val p = a + b + c\n val s = p / 2.0\n val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))\n if (isHeron(area))\n l.add(intArrayOf(a, b, c, p, area.toInt()))\n }\n print(\"Number of primitive Heronian triangles with sides up to $n: \" + l.size)\n\n sort(l)\n print(\"\\n\\nFirst ten when ordered by increasing area, then perimeter:\" + header)\n for (i in 0 until 10) {\n print(format(l[i]))\n }\n val a = 210\n print(\"\\n\\nArea = $a\" + header)\n l.filter { it[4] == a }.forEach { print(format(it)) }\n }\n\n private fun gcd(a: Int, b: Int): Int {\n var leftover = 1\n var dividend = if (a > b) a else b\n var divisor = if (a > b) b else a\n while (leftover != 0) {\n leftover = dividend % divisor\n if (leftover > 0) {\n dividend = divisor\n divisor = leftover\n }\n }\n return divisor\n }\n\n fun sort(l: MutableList) {\n var swapped = true\n while (swapped) {\n swapped = false\n for (i in 1 until l.size)\n if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) {\n val temp = l[i]\n l[i] = l[i - 1]\n l[i - 1] = temp\n swapped = true\n }\n }\n }\n\n private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0\n\n private val header = \"\\nSides Perimeter Area\"\n private fun format(a: IntArray) = \"\\n%3d x %3d x %3d %5d %10d\".format(a[0], a[1], a[2], a[3], a[4])\n}\n\nfun main(args: Array) = Heron.run()"} {"title": "Hickerson series of almost integers", "language": "Kotlin from Java", "task": "The following function, due to D. Hickerson, is said to generate \"Almost integers\" by the \n\"Almost Integer\" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.)\n\n\nThe function is: h(n) = {\\operatorname{n}!\\over2(\\ln{2})^{n+1}}\n\n\nIt is said to produce \"almost integers\" for '''n''' between '''1''' and '''17'''. \nThe purpose of the task is to verify this assertion.\n\nAssume that an \"almost integer\" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation\n\n\n;Task:\nCalculate all values of the function checking and stating which are \"almost integers\".\n\nNote: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:\n h(18) = 3385534663256845326.39...\n\n", "solution": "// version 1.1.4\n\nimport java.math.BigDecimal\nimport java.math.BigInteger\nimport java.math.MathContext\n\nobject Hickerson {\n private const val LN2 = \"0.693147180559945309417232121458\"\n\n fun almostInteger(n: Int): Boolean {\n val a = BigDecimal(LN2).pow(n + 1) * BigDecimal(2)\n var nn = n\n var f = n.toLong()\n while (--nn > 1) f *= nn\n val b = BigDecimal(f).divide(a, MathContext.DECIMAL128)\n val c = b.movePointRight(1).toBigInteger() % BigInteger.TEN\n return c.toString().matches(Regex(\"[09]\"))\n }\n}\n\nfun main(args: Array) {\n for (n in 1..17) println(\"${\"%2d\".format(n)} is almost integer: ${Hickerson.almostInteger(n)}\")\n}"} {"title": "History variables", "language": "Kotlin", "task": "''Storing the history of objects in a program is a common task. \nMaintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''\n\n''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.\n'' \n\n\"History Variables: \nThe Semantics, Formal Correctness, and Implementation of History Variables \nin an Imperative Programming Language\" by Mallon and Takaoka\n\nConcept also discussed on LtU and Patents.com.\n\n;Task: \nDemonstrate History variable support: \n* enable history variable support (if needed) \n* define a history variable\n* assign three values\n* non-destructively display the history\n* recall the three values. \n\nFor extra points, if the language of choice does not support history variables, \ndemonstrate how this might be implemented.\n\n", "solution": "// version 1.1.4\n\nclass HistoryVariable(initialValue: T) {\n private val history = mutableListOf()\n\n var currentValue: T\n get() = history[history.size - 1]\n set(value) {\n history.add(value)\n }\n\n init {\n currentValue = initialValue\n }\n\n fun showHistory() {\n println(\"The variable's history, oldest values first, is:\")\n for (item in history) println(item)\n }\n}\n\nfun main(args: Array) {\n val v = HistoryVariable(1)\n v.currentValue = 2\n v.currentValue = 3\n v.showHistory()\n println(\"\\nCurrentvalue is ${v.currentValue}\")\n}"} {"title": "Hofstadter-Conway $10,000 sequence", "language": "Kotlin", "task": "The definition of the sequence is colloquially described as:\n* Starting with the list [1,1],\n* Take the last number in the list so far: 1, I'll call it x.\n* Count forward x places from the beginning of the list to find the first number to add (1)\n* Count backward x places from the end of the list to find the second number to add (1)\n* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)\n* This would then produce [1,1,2] where 2 is the third element of the sequence.\n\nNote that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.\n\nA less wordy description of the sequence is:\n a(1)=a(2)=1\n a(n)=a(a(n-1))+a(n-a(n-1))\n\nThe sequence begins:\n 1, 1, 2, 2, 3, 4, 4, 4, 5, ...\n\nInteresting features of the sequence are that:\n* a(n)/n tends to 0.5 as n grows towards infinity.\n* a(n)/n where n is a power of 2 is 0.5\n* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.\n\na(n) / n for n in 1..256 \n\n\nThe sequence is so named because John Conway offered a prize of $10,000 to the first person who could\nfind the first position, p in the sequence where \n |a(n)/n| < 0.55 for all n > p\nIt was later found that Hofstadter had also done prior work on the sequence.\n\nThe 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).\n\n\n;Task:\n# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.\n# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20\n# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20\n\n\n\n;Also see:\n* Conways Challenge Sequence, Mallows' own account.\n* Mathworld Article.\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n val limit = (1 shl 20) + 1\n val a = IntArray(limit)\n a[1] = 1\n a[2] = 1\n for (n in 3 until limit) {\n val p = a[n - 1]\n a[n] = a[p] + a[n - p]\n }\n\n println(\" Range Maximum\")\n println(\"---------------- --------\")\n var pow2 = 1\n var p = 1\n var max = a[1].toDouble()\n for (n in 2 until limit) {\n val r = a[n].toDouble() / n\n if (r > max) max = r\n if (n == pow2 * 2) {\n println(\"2 ^ ${\"%2d\".format(p - 1)} to 2 ^ ${\"%2d\".format(p)} ${\"%f\".format(max)}\")\n pow2 *= 2\n p++\n max = r\n }\n }\n\n var prize = 0\n for (n in limit - 1 downTo 1) {\n if (a[n].toDouble() / n >= 0.55) {\n prize = n\n break\n }\n }\n println(\"\\nMallows' number = $prize\")\n}"} {"title": "Hofstadter Figure-Figure sequences", "language": "Kotlin", "task": "These two sequences of positive integers are defined as:\n:::: \\begin{align}\nR(1)&=1\\ ;\\ S(1)=2 \\\\\nR(n)&=R(n-1)+S(n-1), \\quad n>1.\n\\end{align}\n\nThe sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).\n\nSequence R starts: \n 1, 3, 7, 12, 18, ...\nSequence S starts: \n 2, 4, 5, 6, 8, ...\n\n\n;Task:\n# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).\n# No maximum value for '''n''' should be assumed.\n# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69\n# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.\n\n\n;References:\n* Sloane's A005228 and A030124.\n* Wolfram MathWorld\n* Wikipedia: Hofstadter Figure-Figure sequences.\n\n", "solution": "fun ffr(n: Int) = get(n, 0)[n - 1]\n\nfun ffs(n: Int) = get(0, n)[n - 1]\n\ninternal fun get(rSize: Int, sSize: Int): List {\n val rlist = arrayListOf(1, 3, 7)\n val slist = arrayListOf(2, 4, 5, 6)\n val list = if (rSize > 0) rlist else slist\n val targetSize = if (rSize > 0) rSize else sSize\n\n while (list.size > targetSize)\n list.removeAt(list.size - 1)\n while (list.size < targetSize) {\n val lastIndex = rlist.lastIndex\n val lastr = rlist[lastIndex]\n val r = lastr + slist[lastIndex]\n rlist += r\n var s = lastr + 1\n while (s < r && list.size < targetSize)\n slist += s++\n }\n return list\n}\n\nfun main(args: Array) {\n print(\"R():\")\n (1..10).forEach { print(\" \" + ffr(it)) }\n println()\n\n val first40R = (1..40).map { ffr(it) }\n val first960S = (1..960).map { ffs(it) }\n val indices = (1..1000).filter { it in first40R == it in first960S }\n indices.forEach { println(\"Integer $it either in both or neither set\") }\n println(\"Done\")\n}"} {"title": "Hofstadter Q sequence", "language": "Kotlin", "task": "The Hofstadter Q sequence is defined as:\n:: \\begin{align}\nQ(1)&=Q(2)=1, \\\\\nQ(n)&=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)\\big), \\quad n>2.\n\\end{align}\n\n\nIt is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.\n\n\n;Task:\n* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 \n* Confirm and display that the 1000th term is: 502\n\n\n;Optional extra credit\n* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.\n* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.\n(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).\n\n", "solution": "// version 1.1.4\n\nfun main(args: Array) {\n val q = IntArray(100_001)\n q[1] = 1\n q[2] = 1\n for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]]\n print(\"The first 10 terms are : \")\n for (i in 1..10) print(\"${q[i]} \")\n println(\"\\n\\nThe 1000th term is : ${q[1000]}\")\n val flips = (2..100_000).count { q[it] < q[it - 1] }\n println(\"\\nThe number of flips for the first 100,000 terms is : $flips\")\n}"} {"title": "Honeycombs", "language": "Kotlin", "task": "The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five\ncolumns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should\ndisplay a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen.\n\nOptionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.)\n\n[[image:honeycomb.gif]]\n\n", "solution": "// version 1.1.4\n\nimport java.awt.BasicStroke\nimport java.awt.BorderLayout\nimport java.awt.Color\nimport java.awt.Dimension\nimport java.awt.Font\nimport java.awt.Graphics\nimport java.awt.Graphics2D\nimport java.awt.Polygon\nimport java.awt.RenderingHints\nimport java.awt.event.KeyAdapter\nimport java.awt.event.KeyEvent\nimport java.awt.event.MouseAdapter\nimport java.awt.event.MouseEvent\nimport java.awt.event.WindowEvent\nimport javax.swing.JFrame\nimport javax.swing.JPanel\nimport javax.swing.SwingUtilities\n\nclass Honeycombs : JPanel() {\n private val comb: Array = arrayOfNulls(20)\n\n init {\n preferredSize = Dimension(600, 500)\n background = Color.white\n isFocusable = true\n\n addMouseListener(object : MouseAdapter() {\n override fun mousePressed(e: MouseEvent) {\n for (hex in comb)\n if (hex!!.contains(e.x, e.y)) {\n hex.setSelected()\n checkForClosure()\n break\n }\n repaint()\n }\n })\n\n addKeyListener(object : KeyAdapter() {\n override fun keyPressed(e: KeyEvent) {\n for (hex in comb)\n if (hex!!.letter == e.keyChar.toUpperCase()) {\n hex.setSelected()\n checkForClosure()\n break\n }\n repaint()\n }\n })\n\n val letters = \"LRDGITPFBVOKANUYCESM\".toCharArray()\n val x1 = 150\n val y1 = 100\n val x2 = 225\n val y2 = 143\n val w = 150\n val h = 87\n\n for (i in 0 until comb.size) {\n var x: Int\n var y: Int\n if (i < 12) {\n x = x1 + (i % 3) * w\n y = y1 + (i / 3) * h\n }\n else {\n x = x2 + (i % 2) * w\n y = y2 + ((i - 12) / 2) * h\n }\n comb[i] = Hexagon(x, y, w / 3, letters[i])\n }\n\n requestFocus()\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n g.font = Font(\"SansSerif\", Font.BOLD, 30)\n g.stroke = BasicStroke(3.0f)\n for (hex in comb) hex!!.draw(g)\n }\n\n private fun checkForClosure() {\n if (comb.all { it!!.hasBeenSelected } ) {\n val f = SwingUtilities.getWindowAncestor(this) as JFrame\n f.dispatchEvent(WindowEvent(f, WindowEvent.WINDOW_CLOSING))\n }\n }\n}\n\nclass Hexagon(x: Int, y: Int, halfWidth: Int, c: Char) : Polygon() {\n private val baseColor = Color.yellow\n private val selectedColor = Color.magenta\n var hasBeenSelected = false\n val letter = c\n\n init {\n for (i in 0..5)\n addPoint((x + halfWidth * Math.cos(i * Math.PI / 3.0)).toInt(),\n (y + halfWidth * Math.sin(i * Math.PI / 3.0)).toInt())\n getBounds()\n }\n\n fun setSelected() {\n hasBeenSelected = true\n }\n\n fun draw(g: Graphics2D) {\n with(g) {\n color = if (hasBeenSelected) selectedColor else baseColor\n fillPolygon(this@Hexagon)\n color = Color.black\n drawPolygon(this@Hexagon)\n color = if (hasBeenSelected) Color.black else Color.red\n drawCenteredString(g, letter.toString())\n }\n }\n\n private fun drawCenteredString(g: Graphics2D, s: String) {\n val fm = g.fontMetrics\n val asc = fm.ascent\n val dec = fm.descent\n val x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2\n val y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2)\n g.drawString(s, x, y)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with(f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n add(Honeycombs(), BorderLayout.CENTER)\n title = \"Honeycombs\"\n isResizable = false\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "Horner's rule for polynomial evaluation", "language": "Kotlin", "task": "A fast scheme for evaluating a polynomial such as:\n: -19+7x-4x^2+6x^3\\,\nwhen\n: x=3\\;.\nis to arrange the computation as follows:\n: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\\;\nAnd compute the result from the innermost brackets outwards as in this pseudocode:\n coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''\n x ''':=''' 3\n accumulator ''':=''' 0\n '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''\n ''# Assumes 1-based indexing for arrays''\n accumulator ''':=''' ( accumulator * x ) + coefficients[i]\n '''done'''\n ''# accumulator now has the answer''\n\n'''Task Description'''\n:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.\n\nCf. [[Formal power series]]\n\n", "solution": "// version 1.1.2\n\nfun horner(coeffs: DoubleArray, x: Double): Double {\n var sum = 0.0\n for (i in coeffs.size - 1 downTo 0) sum = sum * x + coeffs[i]\n return sum\n}\n\nfun main(args: Array) {\n val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0)\n println(horner(coeffs, 3.0))\n}"} {"title": "ISBN13 check digit", "language": "Kotlin", "task": "Validate the check digit of an ISBN-13 code:\n::* Multiply every other digit by '''3'''.\n::* Add these numbers and the other digits.\n::* Take the remainder of this number after division by '''10'''.\n::* If it is '''0''', the ISBN-13 check digit is correct.\n\n\nYou might use the following codes for testing:\n::::* 978-0596528126 (good)\n::::* 978-0596528120 (bad)\n::::* 978-1788399081 (good)\n::::* 978-1788399083 (bad)\n\n\nShow output here, on this page\n\n\n;See also:\n:* for details: 13-digit ISBN method of validation. (installs cookies.)\n\n", "solution": "describe(\"ISBN Utilities\") {\n mapOf(\n \"978-1734314502\" to true,\n \"978-1734314509\" to false,\n \"978-1788399081\" to true,\n \"978-1788399083\" to false\n ).forEach { (input, expected) ->\n it(\"returns $expected for $input\") {\n println(\"$input: ${when(isValidISBN13(input)) { \n true -> \"good\"\n else -> \"bad\"\n }}\")\n assert(isValidISBN13(input) == expected)\n }\n }\n}\n"} {"title": "I before E except after C", "language": "Kotlin", "task": "The phrase \"I before E, except after C\" is a \nwidely known mnemonic which is supposed to help when spelling English words.\n\n\n;Task:\nUsing the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, \ncheck if the two sub-clauses of the phrase are plausible individually:\n:::# ''\"I before E when not preceded by C\"''\n:::# ''\"E before I when preceded by C\"''\n\n\nIf both sub-phrases are plausible then the original phrase can be said to be plausible.\n\nSomething is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).\n \n\n;Stretch goal:\nAs a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.\n\n\n''Show your output here as well as your program.''\n\n\n\n\n;cf.:\n* Schools to rethink 'i before e' - BBC news, 20 June 2009\n* I Before E Except After C - QI Series 8 Ep 14, (humorous)\n* Companion website for the book: \"Word Frequencies in Written and Spoken English: based on the British National Corpus\".\n\n", "solution": "// version 1.0.6\n\nimport java.net.URL\nimport java.io.InputStreamReader\nimport java.io.BufferedReader\n\nfun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2\n\nfun printResults(source: String, counts: IntArray) {\n println(\"Results for $source\")\n println(\" i before e except after c\")\n println(\" for ${counts[0]}\")\n println(\" against ${counts[1]}\")\n val plausible1 = isPlausible(counts[0], counts[1])\n println(\" sub-rule is${if (plausible1) \"\" else \" not\"} plausible\\n\")\n println(\" e before i when preceded by c\")\n println(\" for ${counts[2]}\")\n println(\" against ${counts[3]}\")\n val plausible2 = isPlausible(counts[2], counts[3])\n println(\" sub-rule is${if (plausible2) \"\" else \" not\"} plausible\\n\")\n val plausible = plausible1 && plausible2\n println(\" rule is${if (plausible) \"\" else \" not\"} plausible\")\n}\n\nfun main(args: Array) {\n val url = URL(\"http://wiki.puzzlers.org/pub/wordlists/unixdict.txt\")\n val isr = InputStreamReader(url.openStream())\n val reader = BufferedReader(isr)\n val regexes = arrayOf(\n Regex(\"(^|[^c])ie\"), // i before e when not preceded by c (includes words starting with ie)\n Regex(\"(^|[^c])ei\"), // e before i when not preceded by c (includes words starting with ei)\n Regex(\"cei\"), // e before i when preceded by c\n Regex(\"cie\") // i before e when preceded by c \n )\n val counts = IntArray(4) // corresponding counts of occurrences\n var word = reader.readLine()\n while (word != null) {\n for (i in 0..3) counts[i] += regexes[i].findAll(word).toList().size\n word = reader.readLine()\n }\n reader.close()\n printResults(\"unixdict.txt\", counts)\n\n val url2 = URL(\"http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt\")\n val isr2 = InputStreamReader(url2.openStream())\n val reader2 = BufferedReader(isr2)\n val counts2 = IntArray(4) \n reader2.readLine() // read header line\n var line = reader2.readLine() // read first line and store it\n var words: List\n val splitter = Regex(\"\"\"(\\t+|\\s+)\"\"\")\n while (line != null) {\n words = line.split(splitter)\n if (words.size == 4) // first element is empty\n for (i in 0..3) counts2[i] += regexes[i].findAll(words[1]).toList().size * words[3].toInt()\n line = reader2.readLine()\n }\n reader2.close()\n println()\n printResults(\"British National Corpus\", counts2)\n}"} {"title": "Identity matrix", "language": "Kotlin", "task": "Build an identity matrix of a size known at run-time. \n\n\nAn ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', \nwhere the diagonal elements are all '''1'''s (ones), \nand all the other elements are all '''0'''s (zeroes).\n\n\nI_n = \\begin{bmatrix}\n 1 & 0 & 0 & \\cdots & 0 \\\\\n 0 & 1 & 0 & \\cdots & 0 \\\\\n 0 & 0 & 1 & \\cdots & 0 \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n 0 & 0 & 0 & \\cdots & 1 \\\\\n\\end{bmatrix}\n\n\n;Related tasks:\n* [[Spiral matrix]]\n* [[Zig-zag matrix]] \n* [[Ulam_spiral_(for_primes)]]\n\n", "solution": "// version 1.0.6\n\nfun main(args: Array) {\n print(\"Enter size of matrix : \")\n val n = readLine()!!.toInt()\n println()\n val identity = Array(n) { IntArray(n) } // create n x n matrix of integers\n\n // enter 1s in diagonal elements\n for(i in 0 until n) identity[i][i] = 1\n\n // print identity matrix if n <= 40\n if (n <= 40) \n for (i in 0 until n) println(identity[i].joinToString(\" \"))\n else \n println(\"Matrix is too big to display on 80 column console\")\n}"} {"title": "Idiomatically determine all the characters that can be used for symbols", "language": "Kotlin from Java", "task": "Idiomatically determine all the characters that can be used for ''symbols''.\nThe word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.\n\nThe method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n\n;Task requirements\n\nDisplay the set of all the characters that can be used for symbols which can be used (allowed) by the computer program. \nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\nNote that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).\n\n;See also\n* Idiomatically determine all the lowercase and uppercase letters.\n\n", "solution": "// version 1.1.4-3\n\ntypealias CharPredicate = (Char) -> Boolean\n\nfun printChars(msg: String, start: Int, end: Int, limit: Int, p: CharPredicate, asInt: Boolean) {\n print(msg)\n (start until end).map { it.toChar() }\n .filter { p(it) }\n .take(limit)\n .forEach { print(if (asInt) \"[${it.toInt()}]\" else it) }\n println(\"...\")\n}\n\nfun main(args: Array) {\n printChars(\"Kotlin Identifier start: \", 0, 0x10FFFF, 72,\n Char::isJavaIdentifierStart, false)\n\n printChars(\"Kotlin Identifier part: \", 0, 0x10FFFF, 25,\n Character::isJavaIdentifierPart, true)\n\n printChars(\"Kotlin Identifier ignorable: \", 0, 0x10FFFF, 25,\n Character::isIdentifierIgnorable, true)\n}"} {"title": "Idiomatically determine all the lowercase and uppercase letters", "language": "Kotlin", "task": "Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.\nThe method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).\n \n\n;Task requirements\n\nDisplay the set of all:\n::::::* lowercase letters \n::::::* uppercase letters\n\nthat can be used (allowed) by the computer program,\n\nwhere ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. \n\n\nYou may want to mention what hardware architecture is being used, and if applicable, the operating system.\n\n\n;See also\n* Idiomatically determine all the characters that can be used for symbols.\n\n", "solution": "// version 1.0.6\n\nfun main(args: Array) {\n print(\"Lower case : \")\n for (ch in 'a'..'z') print(ch)\n print(\"\\nUpper case : \")\n for (ch in 'A'..'Z') print(ch)\n println()\n}"} {"title": "Imaginary base numbers", "language": "Kotlin", "task": "Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i. \n\n''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''\n\nOther imaginary bases are possible too but are not as widely discussed and aren't specifically named.\n\n'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back. \n\nAt a minimum, support quater-imaginary (base 2i).\n\nFor extra kudos, support positive or negative bases 2i through 6i (or higher).\n\nAs a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.\n\nSee Wikipedia: Quater-imaginary_base for more details. \n\nFor reference, here are some some decimal and complex numbers converted to quater-imaginary.\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1\n 1\n\n\n2\n 2\n\n\n3\n 3\n\n\n4\n 10300\n\n\n5\n 10301\n\n\n6\n 10302\n\n\n7\n 10303\n\n\n8\n 10200\n\n\n9\n 10201\n\n\n10\n 10202\n\n\n11\n 10203\n\n\n12\n 10100\n\n\n13\n 10101\n\n\n14\n 10102\n\n\n15\n 10103\n\n\n16\n 10000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1\n 103\n\n\n-2\n 102\n\n\n-3\n 101\n\n\n-4\n 100\n\n\n-5\n 203\n\n\n-6\n 202\n\n\n-7\n 201\n\n\n-8\n 200\n\n\n-9\n 303\n\n\n-10\n 302\n\n\n-11\n 301\n\n\n-12\n 300\n\n\n-13\n 1030003\n\n\n-14\n 1030002\n\n\n-15\n 1030001\n\n\n-16\n 1030000\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n1i\n10.2\n\n\n2i\n10.0\n\n\n3i\n20.2\n\n\n4i\n20.0\n\n\n5i\n30.2\n\n\n6i\n30.0\n\n\n7i\n103000.2\n\n\n8i\n103000.0\n\n\n9i\n103010.2\n\n\n10i\n103010.0\n\n\n11i\n103020.2\n\n\n12i\n103020.0\n\n\n13i\n103030.2\n\n\n14i\n103030.0\n\n\n15i\n102000.2\n\n\n16i\n102000.0\n\n\n\n\n\n\nBase 10\nBase 2i\n\n\n-1i\n0.2\n\n\n-2i\n1030.0\n\n\n-3i\n1030.2\n\n\n-4i\n1020.0\n\n\n-5i\n1020.2\n\n\n-6i\n1010.0\n\n\n-7i\n1010.2\n\n\n-8i\n1000.0\n\n\n-9i\n1000.2\n\n\n-10i\n2030.0\n\n\n-11i\n2030.2\n\n\n-12i\n2020.0\n\n\n-13i\n2020.2\n\n\n-14i\n2010.0\n\n\n-15i\n2010.2\n\n\n-16i\n2000.0\n\n\n\n\n\n", "solution": "// version 1.2.10\n\nimport kotlin.math.ceil\n\nclass Complex(val real: Double, val imag: Double) {\n\n constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())\n\n operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)\n\n operator fun times(other: Complex) = Complex(\n real * other.real - imag * other.imag,\n real * other.imag + imag * other.real\n )\n\n operator fun times(other: Double) = Complex(real * other, imag * other)\n\n fun inv(): Complex {\n val denom = real * real + imag * imag\n return Complex(real / denom, -imag / denom)\n }\n\n operator fun unaryMinus() = Complex(-real, -imag)\n\n operator fun minus(other: Complex) = this + (-other)\n\n operator fun div(other: Complex) = this * other.inv()\n\n // only works properly if 'real' and 'imag' are both integral\n fun toQuaterImaginary(): QuaterImaginary {\n if (real == 0.0 && imag == 0.0) return QuaterImaginary(\"0\")\n var re = real.toInt()\n var im = imag.toInt()\n var fi = -1\n val sb = StringBuilder()\n while (re != 0) {\n var rem = re % -4\n re /= -4\n if (rem < 0) {\n rem = 4 + rem\n re++\n }\n sb.append(rem)\n sb.append(0)\n }\n if (im != 0) {\n var f = (Complex(0.0, imag) / Complex(0.0, 2.0)).real\n im = ceil(f).toInt()\n f = -4.0 * (f - im.toDouble())\n var index = 1\n while (im != 0) {\n var rem = im % -4\n im /= -4\n if (rem < 0) {\n rem = 4 + rem\n im++\n }\n if (index < sb.length) {\n sb[index] = (rem + 48).toChar()\n }\n else {\n sb.append(0)\n sb.append(rem)\n }\n index += 2\n }\n fi = f.toInt()\n }\n sb.reverse()\n if (fi != -1) sb.append(\".$fi\")\n var s = sb.toString().trimStart('0')\n if (s.startsWith(\".\")) s = \"0$s\"\n return QuaterImaginary(s)\n }\n\n override fun toString(): String {\n val real2 = if (real == -0.0) 0.0 else real // get rid of negative zero\n val imag2 = if (imag == -0.0) 0.0 else imag // ditto\n var result = if (imag2 >= 0.0) \"$real2 + ${imag2}i\" else \"$real2 - ${-imag2}i\"\n result = result.replace(\".0 \", \" \").replace(\".0i\", \"i\").replace(\" + 0i\", \"\")\n if (result.startsWith(\"0 + \")) result = result.drop(4)\n if (result.startsWith(\"0 - \")) result = \"-\" + result.drop(4)\n return result\n }\n}\n\nclass QuaterImaginary(val b2i: String) {\n\n init {\n if (b2i == \"\" || !b2i.all { it in \"0123.\" } || b2i.count { it == '.'} > 1 )\n throw RuntimeException(\"Invalid Base 2i number\")\n }\n\n fun toComplex(): Complex {\n val pointPos = b2i.indexOf(\".\")\n var posLen = if (pointPos != -1) pointPos else b2i.length\n var sum = Complex(0.0, 0.0)\n var prod = Complex(1.0, 0.0)\n for (j in 0 until posLen) {\n val k = (b2i[posLen - 1 - j] - '0').toDouble()\n if (k > 0.0) sum += prod * k\n prod *= twoI\n }\n if (pointPos != -1) {\n prod = invTwoI\n for (j in posLen + 1 until b2i.length) {\n val k = (b2i[j] - '0').toDouble()\n if (k > 0.0) sum += prod * k\n prod *= invTwoI\n }\n }\n return sum\n }\n\n override fun toString() = b2i\n\n companion object {\n val twoI = Complex(0.0, 2.0)\n val invTwoI = twoI.inv()\n }\n}\n\nfun main(args: Array) { \n val fmt = \"%4s -> %8s -> %4s\" \n for (i in 1..16) {\n var c1 = Complex(i, 0)\n var qi = c1.toQuaterImaginary()\n var c2 = qi.toComplex()\n print(\"$fmt \".format(c1, qi, c2))\n c1 = -c1\n qi = c1.toQuaterImaginary()\n c2 = qi.toComplex()\n println(fmt.format(c1, qi, c2))\n }\n println()\n for (i in 1..16) {\n var c1 = Complex(0, i)\n var qi = c1.toQuaterImaginary()\n var c2 = qi.toComplex()\n print(\"$fmt \".format(c1, qi, c2))\n c1 = -c1\n qi = c1.toQuaterImaginary()\n c2 = qi.toComplex()\n println(fmt.format(c1, qi, c2))\n }\n}"} {"title": "Include a file", "language": "Kotlin", "task": "Demonstrate the language's ability to include source code from other files.\n\n\n;See Also\n\n* [[Compiler/Simple file inclusion pre processor]]\n\n\n", "solution": "// version 1.1.2\n\nimport package1.f // import f from package `package1`\n\nfun main(args: Array) {\n f() // invoke f without qualification\n}"} {"title": "Index finite lists of positive integers", "language": "Kotlin", "task": "It is known that the set of finite lists of positive integers is countable. \n\nThis means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers. \n\n\n;Task:\nImplement such a mapping:\n:* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.\n:* write a function ''unrank'' which is the ''rank'' inverse function.\n\n\nDemonstrate your solution by:\n:* picking a random-length list of random positive integers\n:* turn it into an integer, and \n:* get the list back.\n\n\nThere are many ways to do this. Feel free to choose any one you like.\n\n\n;Extra credit:\nMake the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.\n\n", "solution": "// version 1.1.2\n\nimport java.math.BigInteger\n\n/* Separates each integer in the list with an 'a' then encodes in base 11. Empty list mapped to '-1' */\nfun rank(li: List) = when (li.size) {\n 0 -> -BigInteger.ONE\n else -> BigInteger(li.joinToString(\"a\"), 11)\n}\n\nfun unrank(r: BigInteger) = when (r) {\n -BigInteger.ONE -> emptyList()\n else -> r.toString(11).split('a').map { if (it != \"\") it.toInt() else 0 }\n}\n\n\n/* Each integer n in the list mapped to '1' plus n '0's. Empty list mapped to '0' */\nfun rank2(li:List): BigInteger {\n if (li.isEmpty()) return BigInteger.ZERO\n val sb = StringBuilder()\n for (i in li) sb.append(\"1\" + \"0\".repeat(i))\n return BigInteger(sb.toString(), 2)\n}\n\nfun unrank2(r: BigInteger) = when (r) {\n BigInteger.ZERO -> emptyList()\n else -> r.toString(2).drop(1).split('1').map { it.length }\n}\n\nfun main(args: Array) {\n var li: List\n var r: BigInteger\n li = listOf(0, 1, 2, 3, 10, 100, 987654321)\n println(\"Before ranking : $li\")\n r = rank(li)\n println(\"Rank = $r\")\n li = unrank(r)\n println(\"After unranking : $li\")\n\n println(\"\\nAlternative approach (not suitable for large numbers)...\\n\")\n li = li.dropLast(1)\n println(\"Before ranking : $li\")\n r = rank2(li)\n println(\"Rank = $r\")\n li = unrank2(r)\n println(\"After unranking : $li\")\n\n println()\n for (i in 0..10) {\n val bi = BigInteger.valueOf(i.toLong())\n li = unrank2(bi)\n println(\"${\"%2d\".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}\")\n }\n}"} {"title": "Integer overflow", "language": "Kotlin", "task": "Some languages support one or more integer types of the underlying processor.\n\nThis integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.\nThe integers supported by such a type can be ''signed'' or ''unsigned''.\n\nArithmetic for machine level integers can often be done by single CPU instructions.\nThis allows high performance and is the main reason to support machine level integers.\n\n\n;Definition:\nAn integer overflow happens when the result of a computation does not fit into the fixed size integer.\nThe result can be too small or too big to be representable in the fixed size integer.\n\n\n;Task:\nWhen a language has fixed size integer types, create a program that\ndoes arithmetic computations for the fixed size integers of the language.\n\nThese computations must be done such that the result would overflow.\n\nThe program should demonstrate what the following expressions do.\n\n\nFor 32-bit signed integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit signed integer\n|-\n| -(-2147483647-1)\n| 2147483648\n|-\n| 2000000000 + 2000000000\n| 4000000000\n|-\n| -2147483647 - 2147483647\n| -4294967294\n|-\n| 46341 * 46341\n| 2147488281\n|-\n| (-2147483647-1) / -1\n| 2147483648\n|}\n\nFor 64-bit signed integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit signed integer\n|-\n| -(-9223372036854775807-1)\n| 9223372036854775808\n|-\n| 5000000000000000000+5000000000000000000\n| 10000000000000000000\n|-\n| -9223372036854775807 - 9223372036854775807\n| -18446744073709551614\n|-\n| 3037000500 * 3037000500\n| 9223372037000250000\n|-\n| (-9223372036854775807-1) / -1\n| 9223372036854775808\n|}\n\nFor 32-bit unsigned integers:\n::::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 32-bit unsigned integer\n|-\n| -4294967295\n| -4294967295\n|-\n| 3000000000 + 3000000000\n| 6000000000\n|-\n| 2147483647 - 4294967295\n| -2147483648\n|-\n| 65537 * 65537\n| 4295098369\n|}\n\nFor 64-bit unsigned integers:\n::: {|class=\"wikitable\"\n!Expression\n!Result that does not fit into a 64-bit unsigned integer\n|-\n| -18446744073709551615\n| -18446744073709551615\n|-\n| 10000000000000000000 + 10000000000000000000\n| 20000000000000000000\n|-\n| 9223372036854775807 - 18446744073709551615\n| -9223372036854775808\n|-\n| 4294967296 * 4294967296\n| 18446744073709551616\n|}\n\n\n;Notes:\n:* When the integer overflow does trigger an exception show how the exception is caught.\n:* When the integer overflow produces some value, print it.\n:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.\n:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.\n:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.\n:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.\n\n", "solution": "// The Kotlin compiler can detect expressions of signed constant integers that will overflow.\n// It cannot detect unsigned integer overflow, however.\n@Suppress(\"INTEGER_OVERFLOW\")\nfun main() {\n println(\"*** Signed 32 bit integers ***\\n\")\n println(-(-2147483647 - 1))\n println(2000000000 + 2000000000)\n println(-2147483647 - 2147483647)\n println(46341 * 46341)\n println((-2147483647 - 1) / -1)\n println(\"\\n*** Signed 64 bit integers ***\\n\")\n println(-(-9223372036854775807 - 1))\n println(5000000000000000000 + 5000000000000000000)\n println(-9223372036854775807 - 9223372036854775807)\n println(3037000500 * 3037000500)\n println((-9223372036854775807 - 1) / -1)\n println(\"\\n*** Unsigned 32 bit integers ***\\n\")\n// println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator\n// println(0U - 4294967295U) // this works\n println((-4294967295).toUInt()) // converting from the signed Int type also produces the overflow; this is intended behavior of toUInt()\n println(3000000000U + 3000000000U)\n println(2147483647U - 4294967295U)\n println(65537U * 65537U)\n println(\"\\n*** Unsigned 64 bit integers ***\\n\")\n println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction\n println(10000000000000000000U + 10000000000000000000U)\n println(9223372036854775807U - 18446744073709551615U)\n println(4294967296U * 4294967296U)\n}"} {"title": "Integer sequence", "language": "Kotlin", "task": "Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.\n\n\nAn example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.\n\nIf appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.\n\n", "solution": "import java.math.BigInteger\n\n// version 1.0.5-2\n\nfun main(args: Array) {\n // print until 2147483647\n (0..Int.MAX_VALUE).forEach { println(it) }\n\n // print forever\n var n = BigInteger.ZERO\n while (true) {\n println(n)\n n += BigInteger.ONE\n }\n}"} {"title": "Intersecting number wheels", "language": "Kotlin from Java", "task": "A number wheel has:\n* A ''name'' which is an uppercase letter.\n* A set of ordered ''values'' which are either ''numbers'' or ''names''.\n\nA ''number'' is generated/yielded from a named wheel by:\n:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a \"wheel\":\n::1.a If the value is a number, yield it.\n::1.b If the value is a name, yield the next value from the named wheel\n::1.c Advance the position of this wheel.\n\nGiven the wheel\n: A: 1 2 3\nthe number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...\n\n'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the \nfirst named wheel is assumed to be the one that values are generated from.\n\n;Examples:\nGiven the wheels:\n A: 1 B 2\n B: 3 4\nThe series of numbers generated starts:\n 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...\n\nThe intersections of number wheels can be more complex, (and might loop forever),\nand wheels may be multiply connected. \n\n'''Note:''' If a named wheel is referenced more than \nonce by one or many other wheels, then there is only one position of the wheel \nthat is advanced by each and all references to it.\n\nE.g.\n A: 1 D D\n D: 6 7 8\n Generates:\n 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... \n\n;Task:\nGenerate and show the first twenty terms of the sequence of numbers generated \nfrom these groups:\n\n Intersecting Number Wheel group:\n A: 1 2 3\n \n Intersecting Number Wheel group:\n A: 1 B 2\n B: 3 4\n \n Intersecting Number Wheel group:\n A: 1 D D\n D: 6 7 8\n \n Intersecting Number Wheel group:\n A: 1 B C\n B: 3 4\n C: 5 B\n\nShow your output here, on this page.\n\n\n", "solution": "import java.util.Collections\nimport java.util.stream.IntStream\n\nobject WheelController {\n private val IS_NUMBER = \"[0-9]\".toRegex()\n private const val TWENTY = 20\n private var wheelMap = mutableMapOf()\n\n private fun advance(wheel: String) {\n val w = wheelMap[wheel]\n if (w!!.list[w.position].matches(IS_NUMBER)) {\n w.printThePosition()\n } else {\n val wheelName = w.list[w.position]\n advance(wheelName)\n }\n w.advanceThePosition()\n }\n\n private fun run() {\n println(wheelMap)\n IntStream.rangeClosed(1, TWENTY)\n .forEach { advance(\"A\") }\n println()\n wheelMap.clear()\n }\n\n @JvmStatic\n fun main(args: Array) {\n wheelMap[\"A\"] = WheelModel(\"1\", \"2\", \"3\")\n run()\n wheelMap[\"A\"] = WheelModel(\"1\", \"B\", \"2\")\n wheelMap[\"B\"] = WheelModel(\"3\", \"4\")\n run()\n wheelMap[\"A\"] = WheelModel(\"1\", \"D\", \"D\")\n wheelMap[\"D\"] = WheelModel(\"6\", \"7\", \"8\")\n run()\n wheelMap[\"A\"] = WheelModel(\"1\", \"B\", \"C\")\n wheelMap[\"B\"] = WheelModel(\"3\", \"4\")\n wheelMap[\"C\"] = WheelModel(\"5\", \"B\")\n run()\n }\n}\n\ninternal class WheelModel(vararg values: String?) {\n var list = mutableListOf()\n var position: Int\n private var endPosition: Int\n\n override fun toString(): String {\n return list.toString()\n }\n\n fun advanceThePosition() {\n if (position == endPosition) {\n position = INITIAL // new beginning\n } else {\n position++ // advance position\n }\n }\n\n fun printThePosition() {\n print(\" ${list[position]}\")\n }\n\n companion object {\n private const val INITIAL = 0\n }\n\n init {\n Collections.addAll(list, *values)\n position = INITIAL\n endPosition = list.size - 1\n }\n}"} {"title": "Inverted syntax", "language": "Kotlin", "task": "'''Inverted syntax with conditional expressions'''\n\nIn traditional syntax conditional expressions are usually shown before the action within a statement or code block:\n\n IF raining=true THEN needumbrella=true \n\nIn inverted syntax, the action is listed before the conditional expression in the statement or code block:\n\n needumbrella=true IF raining=true \n\n'''Inverted syntax with assignment'''\n\nIn traditional syntax, assignments are usually expressed with the variable appearing before the expression:\n\n a = 6\n\nIn inverted syntax, the expression appears before the variable:\n 6 = a\n\n'''Task'''\n\nThe task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.\n", "solution": "// version 1.0.6\n\ninfix fun Boolean.iif(cond: Boolean) = if (cond) this else !this\n\nfun main(args: Array) {\n val raining = true\n val needUmbrella = true iif (raining)\n println(\"Do I need an umbrella? ${if(needUmbrella) \"Yes\" else \"No\"}\")\n}"} {"title": "Isqrt (integer square root) of X", "language": "Kotlin from Go", "task": "Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a\nreal non-negative number.\n\nOften '''X''' is actually a non-negative integer.\n\nFor the purposes of this task, '''X''' can be an integer or a real number, but if it\nsimplifies things in your computer programming language, assume it's an integer.\n\n\nOne of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or\nprimes) up to the \n X of that\ninteger, either to find the factors of that integer, or to determine primality.\n\n\nAn alternative method for finding the '''Isqrt''' of a number is to\ncalculate: floor( sqrt(X) ) \n::* where '''sqrt''' is the square root function for non-negative real numbers, and\n::* where '''floor''' is the floor function for real numbers.\n\n\nIf the hardware supports the computation of (real) square roots, the above method might be a faster method for\nsmall numbers that don't have very many significant (decimal) digits.\n\nHowever, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.\n\n\n;Pseudo-code using quadratic residue:\nFor this task, the integer square root of a non-negative number will be computed using a version\nof ''quadratic residue'', which has the advantage that no ''floating point'' calculations are\nused, only integer arithmetic. \n\nFurthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.\n\nThe disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.\n\n\nPseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):\n q <-- 1 /*initialize Q to unity. */\n /*find a power of 4 that's greater than X.*/\n perform while q <= x /*perform while Q <= X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n /*Q is now greater than X.*/\n z <-- x /*set Z to the value of X.*/\n r <-- 0 /*initialize R to zero. */\n perform while q > 1 /*perform while Q > unity. */\n q <-- q / 4 /*integer divide by four. */\n t <-- z - r - q /*compute value of T. */\n r <-- r / 2 /*integer divide by two. */\n if t >= 0 then do \n z <-- t /*set Z to value of T. */\n r <-- r + q /*compute new value of R. */\n end\n end /*perform*/\n /*R is now the Isqrt(X). */\n \n /* Sidenote: Also, Z is now the remainder after square root (i.e. */\n /* R^2 + Z = X, so if Z = 0 then X is a perfect square). */\n\nAnother version for the (above) 1st '''perform''' is:\n perform until q > X /*perform until Q > X. */\n q <-- q * 4 /*multiply Q by four. */\n end /*perform*/\n\n\nInteger square roots of some values:\n Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9\n Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10\n Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10\n Isqrt( 3) is 1 Isqrt(63) is 7\n Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10\n Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11\n Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11\n Isqrt( 7) is 2 Isqrt(67) is 8\n Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11\n Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12\n Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12\n\n\n;Task:\nCompute and show all output here (on this page) for:\n::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.\n::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.\n::* use commas in the displaying of larger numbers.\n\n\nYou can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.\nIf your computer programming language only supports smaller integers, show what you can.\n\n\n;Related tasks:\n:* sequence of non-squares\n:* integer roots\n:* square root by hand\n\n", "solution": "import java.math.BigInteger\n\nfun isqrt(x: BigInteger): BigInteger {\n if (x < BigInteger.ZERO) {\n throw IllegalArgumentException(\"Argument cannot be negative\")\n }\n var q = BigInteger.ONE\n while (q <= x) {\n q = q.shiftLeft(2)\n }\n var z = x\n var r = BigInteger.ZERO\n while (q > BigInteger.ONE) {\n q = q.shiftRight(2)\n var t = z\n t -= r\n t -= q\n r = r.shiftRight(1)\n if (t >= BigInteger.ZERO) {\n z = t\n r += q\n }\n }\n return r\n}\n\nfun main() {\n println(\"The integer square root of integers from 0 to 65 are:\")\n for (i in 0..65) {\n print(\"${isqrt(BigInteger.valueOf(i.toLong()))} \")\n }\n println()\n\n println(\"The integer square roots of powers of 7 from 7^1 up to 7^73 are:\")\n println(\"power 7 ^ power integer square root\")\n println(\"----- --------------------------------------------------------------------------------- -----------------------------------------\")\n var pow7 = BigInteger.valueOf(7)\n val bi49 = BigInteger.valueOf(49)\n for (i in (1..73).step(2)) {\n println(\"%2d %,84d %,41d\".format(i, pow7, isqrt(pow7)))\n pow7 *= bi49\n }\n}"} {"title": "Iterated digits squaring", "language": "Kotlin from FreeBASIC", "task": "If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:\n15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89\n7 -> 49 -> 97 -> 130 -> 10 -> 1\n\nAn example in Python:\n\n>>> step = lambda x: sum(int(d) ** 2 for d in str(x))\n>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))\n>>> [iterate(x) for x in xrange(1, 20)]\n[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]\n\n\n;Task:\n: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.\nOr, for much less credit - (showing that your algorithm and/or language is slow):\n: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.\n\nThis problem derives from the Project Euler problem 92.\n\nFor a quick algorithm for this task see the talk page\n\n\n;Related tasks:\n* [[Combinations with repetitions]]\n* [[Digital root]]\n* [[Digital root/Multiplicative digital root]]\n\n", "solution": "// version 1.0.6\n\nfun endsWith89(n: Int): Boolean {\n var digit: Int\n var sum = 0\n var nn = n\n while (true) {\n while (nn > 0) {\n digit = nn % 10\n sum += digit * digit\n nn /= 10\n }\n if (sum == 89) return true\n if (sum == 1) return false\n nn = sum\n sum = 0\n }\n}\n\nfun main(args: Array) {\n val sums = IntArray(8 * 81 + 1)\n sums[0] = 1\n sums[1] = 0\n var s: Int\n for (n in 1 .. 8)\n for (i in n * 81 downTo 1) \n for (j in 1 .. 9) {\n s = j * j\n if (s > i) break\n sums[i] += sums[i - s]\n }\n var count89 = 0 \n for (i in 1 .. 8 * 81) \n if (endsWith89(i)) count89 += sums[i]\n println(\"There are $count89 numbers from 1 to 100 million ending with 89\")\n}"} {"title": "JSON", "language": "Kotlin", "task": "Load a JSON string into a data structure. \nAlso, create a new data structure and serialize it into JSON.\n\nUse objects and arrays (as appropriate for your language) \nand make sure your JSON is valid (https://jsonformatter.org).\n\n", "solution": "// version 1.2.21\n\ndata class JsonObject(val foo: Int, val bar: Array)\n\ndata class JsonObject2(val ocean: String, val blue: Array)\n\nfun main(args: Array) {\n // JSON to object\n val data: JsonObject = JSON.parse(\"\"\"{ \"foo\": 1, \"bar\": [\"10\", \"apples\"] }\"\"\")\n println(JSON.stringify(data))\n\n // object to JSON\n val data2 = JsonObject2(\"water\", arrayOf(1, 2))\n println(JSON.stringify(data2))\n}"} {"title": "Jacobi symbol", "language": "Kotlin", "task": "The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)\n* (a | p) 1 if a is a square (mod p)\n* (a | p) -1 if a is not a square (mod p)\n* (a | p) 0 if a 0 \n\nIf n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).\n\n;Task:\nCalculate the Jacobi symbol (a | n).\n\n;Reference:\n* Wikipedia article on Jacobi symbol.\n\n", "solution": "fun jacobi(A: Int, N: Int): Int {\n assert(N > 0 && N and 1 == 1)\n var a = A % N\n var n = N\n var result = 1\n while (a != 0) {\n var aMod4 = a and 3\n while (aMod4 == 0) { // remove factors of four\n a = a shr 2\n aMod4 = a and 3\n }\n if (aMod4 == 2) { // if even\n a = a shr 1 // remove factor 2 and possibly change sign\n if ((n and 7).let { it == 3 || it == 5 })\n result = -result\n aMod4 = a and 3\n }\n if (aMod4 == 3 && n and 3 == 3)\n result = -result\n a = (n % a).also { n = a }\n }\n return if (n == 1) result else 0\n}"} {"title": "Jaro similarity", "language": "Kotlin from Java", "task": "The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.\n\n\n;;Definition\n\nThe Jaro similarity d_j of two given strings s_1 and s_2 is\n\n: d_j = \\left\\{\n\n\\begin{array}{l l}\n 0 & \\text{if }m = 0\\\\\n \\frac{1}{3}\\left(\\frac{m}{|s_1|} + \\frac{m}{|s_2|} + \\frac{m-t}{m}\\right) & \\text{otherwise} \\end{array} \\right.\n\nWhere:\n\n* m is the number of ''matching characters'';\n* t is half the number of ''transpositions''.\n\n\nTwo characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \\left\\lfloor\\frac{\\max(|s_1|,|s_2|)}{2}\\right\\rfloor-1 characters.\n\nEach character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.\n\n\n;;Example\n\nGiven the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:\n\n* m = 4\n* |s_1| = 6\n* |s_2| = 5\n* t = 0\n\n\nWe find a Jaro score of:\n\n: d_j = \\frac{1}{3}\\left(\\frac{4}{6} + \\frac{4}{5} + \\frac{4-0}{4}\\right) = 0.822\n\n\n;Task\n\nImplement the Jaro algorithm and show the similarity scores for each of the following pairs:\n\n* (\"MARTHA\", \"MARHTA\")\n* (\"DIXON\", \"DICKSONX\")\n* (\"JELLYFISH\", \"SMELLYFISH\")\n\n\n; See also\n* Jaro-Winkler distance on Wikipedia.\n\n", "solution": "object Jaro {\n fun distance(s1: String, s2: String): Double {\n val s1_len = s1.length\n val s2_len = s2.length\n if (s1_len == 0 && s2_len == 0) return 1.0\n val match_distance = Math.max(s1_len, s2_len) / 2 - 1\n val s1_matches = BooleanArray(s1_len)\n val s2_matches = BooleanArray(s2_len)\n var matches = 0\n for (i in 0..s1_len - 1) {\n val start = Math.max(0, i - match_distance)\n val end = Math.min(i + match_distance + 1, s2_len)\n (start..end - 1).find { j -> !s2_matches[j] && s1[i] == s2[j] } ?. let {\n s1_matches[i] = true\n s2_matches[it] = true\n matches++\n }\n }\n if (matches == 0) return 0.0\n var t = 0.0\n var k = 0\n (0..s1_len - 1).filter { s1_matches[it] }.forEach { i ->\n while (!s2_matches[k]) k++\n if (s1[i] != s2[k]) t += 0.5\n k++\n }\n\n val m = matches.toDouble()\n return (m / s1_len + m / s2_len + (m - t) / m) / 3.0\n }\n}\n\nfun main(args: Array) {\n println(Jaro.distance(\"MARTHA\", \"MARHTA\"))\n println(Jaro.distance(\"DIXON\", \"DICKSONX\"))\n println(Jaro.distance(\"JELLYFISH\", \"SMELLYFISH\"))\n}"} {"title": "Jewels and stones", "language": "Kotlin", "task": "Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.\n\nBoth strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.\n\nThe function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.\n\n\nNote that:\n:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. \n:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.\n:# The parameters do not need to have exactly the same names.\n:# Validating the arguments is unnecessary. \n\nSo, for example, if passed \"aAAbbbb\" for 'stones' and \"aA\" for 'jewels', the function should return 3.\n\nThis task was inspired by this problem.\n\n\n\n", "solution": "// Version 1.2.40\n\nfun countJewels(s: String, j: String) = s.count { it in j }\n\nfun main(args: Array) {\n println(countJewels(\"aAAbbbb\", \"aA\"))\n println(countJewels(\"ZZ\", \"z\"))\n}"} {"title": "Julia set", "language": "Kotlin", "task": "Task\nGenerate and draw a Julia set. \n\n\n;Related tasks\n* Mandelbrot Set\n\n", "solution": "import java.awt.*\nimport java.awt.image.BufferedImage\nimport javax.swing.JFrame\nimport javax.swing.JPanel\n\nclass JuliaPanel : JPanel() {\n init {\n preferredSize = Dimension(800, 600)\n background = Color.white\n }\n\n private val maxIterations = 300\n private val zoom = 1\n private val moveX = 0.0\n private val moveY = 0.0\n private val cX = -0.7\n private val cY = 0.27015\n\n public override fun paintComponent(graphics: Graphics) {\n super.paintComponent(graphics)\n with(graphics as Graphics2D) {\n setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)\n (0 until width).forEach { x ->\n (0 until height).forEach { y ->\n var zx = 1.5 * (x - width / 2) / (0.5 * zoom * width) + moveX\n var zy = (y - height / 2) / (0.5 * zoom * height) + moveY\n var i = maxIterations.toFloat()\n while (zx * zx + zy * zy < 4 && i > 0) {\n val tmp = zx * zx - zy * zy + cX\n zy = 2.0 * zx * zy + cY\n zx = tmp\n i--\n }\n image.setRGB(x, y, Color.HSBtoRGB(maxIterations / i % 1, 1f, (if (i > 0) 1 else 0).toFloat()))\n }\n }\n drawImage(image, 0, 0, null)\n }\n }\n}\n\nfun main() {\n with(JFrame()) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Julia Set\"\n isResizable = false\n add(JuliaPanel(), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n}"} {"title": "Jump anywhere", "language": "Kotlin", "task": "Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.\n\nThis task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. \nFor the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. \nThis task provides a \"grab bag\" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!\n\n* Some languages can ''go to'' any global label in a program.\n* Some languages can break multiple function calls, also known as ''unwinding the call stack''.\n* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).\n\nThese jumps are not all alike. \nA simple ''goto'' never touches the call stack. \nA continuation saves the call stack, so you can continue a function call after it ends.\n\n\n;Task:\nUse your language to demonstrate the various types of jumps that it supports. \n\nBecause the possibilities vary by language, this task is not specific. \nYou have the freedom to use these jumps for different purposes. \nYou may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].\n\n", "solution": "// version 1.0.6\n\nfun main(args: Array) {\n intArrayOf(4, 5, 6).forEach lambda@ {\n if (it == 5) return@lambda\n println(it)\n }\n println()\n loop@ for (i in 0 .. 3) {\n for (j in 0 .. 3) {\n if (i + j == 4) continue@loop\n if (i + j == 5) break@loop\n println(i + j)\n }\n }\n}"} {"title": "K-d tree", "language": "Kotlin from Go", "task": "{{wikipedia|K-d tree}}\n\nA k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). \nk-d trees are a special case of binary space partitioning trees.\n\nk-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. \nOtherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.\n\n'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:\n\n# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].\n# 1000 3-d points uniformly distributed in a 3-d cube.\n\nFor the Wikipedia example, find the nearest neighbor to point (9, 2)\nFor the random data, pick a random location and find the nearest neighbor.\n\nIn addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.\n\nOutput should show the point searched for, the point found, \nthe distance to the point, and the number of nodes visited.\n\nThere are variant algorithms for constructing the tree. \nYou can use a simple median strategy or implement something more efficient. \nVariants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. \nYou do not have to implement these. \nThe requirement for this task is specifically the nearest single neighbor. \nAlso there are algorithms for inserting, deleting, and balancing k-d trees. \nThese are also not required for the task.\n\n", "solution": "// version 1.1.51\n\nimport java.util.Random\n\ntypealias Point = DoubleArray\n\nfun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()\n\nclass HyperRect (val min: Point, val max: Point) {\n fun copy() = HyperRect(min.copyOf(), max.copyOf())\n}\n\ndata class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodesVisited: Int)\n\nclass KdNode(\n val domElt: Point,\n val split: Int,\n var left: KdNode?,\n var right: KdNode?\n)\n\nclass KdTree {\n val n: KdNode?\n val bounds: HyperRect\n\n constructor(pts: MutableList, bounds: HyperRect) {\n fun nk2(exset: MutableList, split: Int): KdNode? {\n if (exset.size == 0) return null\n val exset2 = exset.sortedBy { it[split] }\n for (i in 0 until exset.size) exset[i] = exset2[i]\n var m = exset.size / 2\n val d = exset[m]\n while (m + 1 < exset.size && exset[m + 1][split] == d[split]) m++\n var s2 = split + 1\n if (s2 == d.size) s2 = 0\n return KdNode(\n d,\n split,\n nk2(exset.subList(0, m), s2),\n nk2(exset.subList(m + 1, exset.size), s2)\n )\n }\n this.n = nk2(pts, 0)\n this.bounds = bounds\n }\n\n fun nearest(p: Point) = nn(n, p, bounds, Double.POSITIVE_INFINITY)\n\n private fun nn(\n kd: KdNode?,\n target: Point, \n hr: HyperRect,\n maxDistSqd: Double\n ): NearestNeighbor {\n if (kd == null) return NearestNeighbor(null, Double.POSITIVE_INFINITY, 0)\n var nodesVisited = 1\n val s = kd.split\n val pivot = kd.domElt\n val leftHr = hr.copy()\n val rightHr = hr.copy()\n leftHr.max[s] = pivot[s]\n rightHr.min[s] = pivot[s]\n val targetInLeft = target[s] <= pivot[s]\n val nearerKd = if (targetInLeft) kd.left else kd.right\n val nearerHr = if (targetInLeft) leftHr else rightHr\n val furtherKd = if (targetInLeft) kd.right else kd.left\n val furtherHr = if (targetInLeft) rightHr else leftHr\n var (nearest, distSqd, nv) = nn(nearerKd, target, nearerHr, maxDistSqd)\n nodesVisited += nv\n var maxDistSqd2 = if (distSqd < maxDistSqd) distSqd else maxDistSqd\n var d = pivot[s] - target[s]\n d *= d\n if (d > maxDistSqd2) return NearestNeighbor(nearest, distSqd, nodesVisited)\n d = pivot.sqd(target)\n if (d < distSqd) {\n nearest = pivot\n distSqd = d\n maxDistSqd2 = distSqd\n }\n val temp = nn(furtherKd, target, furtherHr, maxDistSqd2)\n nodesVisited += temp.nodesVisited\n if (temp.distSqd < distSqd) {\n nearest = temp.nearest\n distSqd = temp.distSqd\n }\n return NearestNeighbor(nearest, distSqd, nodesVisited)\n }\n}\n\nval rand = Random()\n\nfun randomPt(dim: Int) = Point(dim) { rand.nextDouble() }\n\nfun randomPts(dim: Int, n: Int) = MutableList(n) { randomPt(dim) }\n\nfun showNearest(heading: String, kd: KdTree, p: Point) {\n println(\"$heading:\")\n println(\"Point : ${p.asList()}\")\n val (nn, ssq, nv) = kd.nearest(p)\n println(\"Nearest neighbor : ${nn?.asList()}\")\n println(\"Distance : ${Math.sqrt(ssq)}\")\n println(\"Nodes visited : $nv\")\n println()\n}\n\nfun main(args: Array) {\n val points = mutableListOf(\n doubleArrayOf(2.0, 3.0),\n doubleArrayOf(5.0, 4.0),\n doubleArrayOf(9.0, 6.0),\n doubleArrayOf(4.0, 7.0),\n doubleArrayOf(8.0, 1.0),\n doubleArrayOf(7.0, 2.0)\n )\n var hr = HyperRect(doubleArrayOf(0.0, 0.0), doubleArrayOf(10.0, 10.0))\n var kd = KdTree(points, hr)\n showNearest(\"WP example data\", kd, doubleArrayOf(9.0, 2.0))\n\n hr = HyperRect(doubleArrayOf(0.0, 0.0, 0.0), doubleArrayOf(1.0, 1.0, 1.0))\n kd = KdTree(randomPts(3, 1000), hr)\n showNearest(\"1000 random 3D points\", kd, randomPt(3))\n\n hr = hr.copy()\n kd = KdTree(randomPts(3, 400_000), hr)\n showNearest(\"400,000 random 3D points\", kd, randomPt(3))\n}"} {"title": "Kaprekar numbers", "language": "Kotlin from Java", "task": "A positive integer is a Kaprekar number if:\n* It is '''1''' (unity)\n* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. \nNote that a split resulting in a part consisting purely of 0s is not valid, \nas 0 is not considered positive.\n\n\n;Example Kaprekar numbers:\n* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.\n* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....\n\n\n;Example process:\n10000 (1002) splitting from left to right:\n* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.\n* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.\n\n\n;Task:\nGenerate and show all Kaprekar numbers less than 10,000. \n\n\n;Extra credit:\nOptionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.\n\n\n;Extra extra credit:\nThe concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); \nif you can, show that Kaprekar numbers exist in other bases too. \n\n\nFor this purpose, do the following:\n* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);\n* Display each of them in base 10 representation;\n* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. \n \nFor example, 225(10) is \"d4\" in base 17, its square \"a52g\", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g\n\n\n;Reference:\n* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version\n\n\n;Related task:\n* [[Casting out nines]]\n\n", "solution": "import java.lang.Long.parseLong\nimport java.lang.Long.toString\n\nfun String.splitAt(idx: Int): Array {\n val ans = arrayOf(substring(0, idx), substring(idx))\n if (ans.first() == \"\") ans[0] = \"0\" // parsing \"\" throws an exception\n return ans\n}\n\nfun Long.getKaprekarParts(sqrStr: String, base: Int): Array? {\n for (j in 0..sqrStr.length / 2) {\n val parts = sqrStr.splitAt(j)\n val (first, second) = parts.map { parseLong(it, base) }\n\n // if the right part is all zeroes, then it will be forever, so break\n if (second == 0L) return null\n if (first + second == this) return parts\n }\n return null\n}\n\nfun main(args: Array) {\n val base = if (args.isNotEmpty()) args[0].toInt() else 10\n var count = 0\n val max = 1000000L\n for (i in 1..max) {\n val s = toString(i * i, base)\n val p = i.getKaprekarParts(s, base)\n if (p != null) {\n println(\"%6d\\t%6s\\t%12s\\t%7s + %7s\".format(i, toString(i, base), s, p[0], p[1]))\n count++\n }\n }\n println(\"$count Kaprekar numbers < $max (base 10) in base $base\")\n}"} {"title": "Kernighans large earthquake problem", "language": "Kotlin", "task": "Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.\n\n;Problem:\nYou are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.\n\nExample lines from the file would be lines like:\n8/27/1883 Krakatoa 8.8\n5/18/1980 MountStHelens 7.6\n3/13/2009 CostaRica 5.1\n\n;Task:\n* Create a program or script invocation to find all the events with magnitude greater than 6\n* Assuming an appropriate name e.g. \"data.txt\" for the file:\n:# Either: Show how your program is invoked to process a data file of that name.\n:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).\n\n", "solution": "// Version 1.2.40\n\nimport java.io.File\n\nfun main(args: Array) {\n val r = Regex(\"\"\"\\s+\"\"\")\n println(\"Those earthquakes with a magnitude > 6.0 are:\\n\")\n File(\"data.txt\").forEachLine {\n if (it.split(r)[2].toDouble() > 6.0) println(it)\n } \n}"} {"title": "Keyboard input/Obtain a Y or N response", "language": "Kotlin", "task": "Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. \n\nThe keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. \n\nThe response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.\n\n", "solution": "// version 1.0.6\n\nimport java.awt.event.KeyAdapter\nimport java.awt.event.KeyEvent\nimport javax.swing.JFrame\nimport javax.swing.SwingUtilities\n\nclass Test: JFrame() {\n init {\n while (System.`in`.available() > 0) System.`in`.read()\n println(\"Do you want to quit Y/N\")\n addKeyListener(object: KeyAdapter() {\n override fun keyPressed(e: KeyEvent) {\n if (e.keyCode == KeyEvent.VK_Y) {\n println(\"OK, quitting\")\n quit()\n } else if (e.keyCode == KeyEvent.VK_N) {\n println(\"N was pressed but the program is about to end anyway\")\n quit()\n } else {\n println(\"Only Y/N are acceptable, please try again\")\n }\n }\n })\n }\n\n private fun quit() {\n isVisible = false\n dispose()\n System.exit(0)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = Test()\n f.isFocusable = true\n f.isVisible = true\n }\n}"} {"title": "Knight's tour", "language": "Kotlin from Haskell", "task": "Task\nProblem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be \"closed\"; that is, the knight need not end within a single move of its start position.\n\nInput and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.\n\nInput: starting square\n\nOutput: move sequence\n\n\n;Related tasks\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "data class Square(val x : Int, val y : Int)\n\nval board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) })\nval axisMoves = arrayOf(1, 2, -1, -2)\n\nfun allPairs(a: Array) = a.flatMap { i -> a.map { j -> Pair(i, j) } }\n\nfun knightMoves(s : Square) : List {\n val moves = allPairs(axisMoves).filter{ Math.abs(it.first) != Math.abs(it.second) }\n fun onBoard(s : Square) = board.any {it == s}\n return moves.map { Square(s.x + it.first, s.y + it.second) }.filter(::onBoard)\n}\n\nfun knightTour(moves : List) : List {\n fun findMoves(s: Square) = knightMoves(s).filterNot { m -> moves.any { it == m } }\n val newSquare = findMoves(moves.last()).minBy { findMoves(it).size }\n return if (newSquare == null) moves else knightTour(moves + newSquare)\n}\n\nfun knightTourFrom(start : Square) = knightTour(listOf(start))\n\nfun main(args : Array) {\n var col = 0\n for ((x, y) in knightTourFrom(Square(1, 1))) {\n System.out.print(\"$x,$y\")\n System.out.print(if (col == 7) \"\\n\" else \" \")\n col = (col + 1) % 8\n }\n}"} {"title": "Knuth's algorithm S", "language": "Kotlin from Java", "task": "This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.\nThis means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).\n\n\n;The algorithm:\n:* Select the first n items as the sample as they become available;\n:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.\n:* Repeat 2nd step for any subsequent items.\n\n\n;The Task:\n:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.\n:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.\n:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:\n:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.\n:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.\n\n\nNote: A class taking n and generating a callable instance/function might also be used.\n\n\n;Reference:\n* The Art of Computer Programming, Vol 2, 3.4.2 p.142\n\n\n;Related tasks: \n* [[One of n lines in a file]] \n* [[Accumulator factory]]\n\n", "solution": "// version 1.2.51\n\nimport java.util.Random\n\nval rand = Random()\n\nclass SOfN(val n: Int) {\n private val sample = ArrayList(n)\n private var i = 0\n\n fun process(item: T): List {\n if (++i <= n)\n sample.add(item)\n else if (rand.nextInt(i) < n)\n sample[rand.nextInt(n)] = item\n return sample\n }\n}\n \nfun main(args: Array) {\n val bin = IntArray(10)\n (1..100_000).forEach {\n val sOfn = SOfN(3)\n for (d in 0..8) sOfn.process(d)\n for (s in sOfn.process(9)) bin[s]++\n }\n println(bin.contentToString())\n}"} {"title": "Koch curve", "language": "Kotlin from Ring", "task": "Draw a Koch curve. See details: Koch curve\n\n", "solution": "// Version 1.2.41\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.image.BufferedImage\nimport kotlin.math.*\nimport java.io.File\nimport javax.imageio.ImageIO\n\nval Double.asI get() = this.toInt()\n\nclass Point(var x: Int, var y: Int)\n\nclass BasicBitmapStorage(width: Int, height: Int) {\n val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)\n\n fun fill(c: Color) {\n val g = image.graphics\n g.color = c\n g.fillRect(0, 0, image.width, image.height)\n }\n\n fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())\n\n fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))\n\n fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) {\n val dx = abs(x1 - x0)\n val dy = abs(y1 - y0)\n val sx = if (x0 < x1) 1 else -1\n val sy = if (y0 < y1) 1 else -1\n var xx = x0\n var yy = y0\n var e1 = (if (dx > dy) dx else -dy) / 2\n var e2: Int\n while (true) {\n setPixel(xx, yy, c)\n if (xx == x1 && yy == y1) break\n e2 = e1\n if (e2 > -dx) { e1 -= dy; xx += sx }\n if (e2 < dy) { e1 += dx; yy += sy }\n }\n }\n\n fun koch(x1: Double, y1: Double, x2: Double, y2: Double, it: Int) {\n val angle = PI / 3.0 // 60 degrees\n val clr = Color.blue\n var iter = it\n val x3 = (x1 * 2.0 + x2) / 3.0\n val y3 = (y1 * 2.0 + y2) / 3.0\n val x4 = (x1 + x2 * 2.0) / 3.0\n val y4 = (y1 + y2 * 2.0) / 3.0\n val x5 = x3 + (x4 - x3) * cos(angle) + (y4 - y3) * sin(angle)\n val y5 = y3 - (x4 - x3) * sin(angle) + (y4 - y3) * cos(angle)\n\n if (iter > 0) {\n iter--\n koch(x1, y1, x3, y3, iter)\n koch(x3, y3, x5, y5, iter)\n koch(x5, y5, x4, y4, iter)\n koch(x4, y4, x2, y2, iter)\n }\n else {\n drawLine(x1.asI, y1.asI, x3.asI, y3.asI, clr)\n drawLine(x3.asI, y3.asI, x5.asI, y5.asI, clr)\n drawLine(x5.asI, y5.asI, x4.asI, y4.asI, clr)\n drawLine(x4.asI, y4.asI, x2.asI, y2.asI, clr)\n }\n }\n}\n\nfun main(args: Array) {\n val width = 512\n val height = 512\n val bbs = BasicBitmapStorage(width, height)\n with (bbs) {\n fill(Color.white)\n koch(100.0, 100.0, 400.0, 400.0, 4)\n val kFile = File(\"koch_curve.jpg\")\n ImageIO.write(image, \"jpg\", kFile)\n }\n}"} {"title": "Kolakoski sequence", "language": "Kotlin", "task": "The natural numbers, (excluding zero); with the property that:\n: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.\n\n;Example:\nThis is ''not'' a Kolakoski sequence:\n1,1,2,2,2,1,2,2,1,2,...\nIts sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:\n\n: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...\n\nThe above gives the RLE of:\n2, 3, 1, 2, 1, ...\n\nThe original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.\n\n;Creating a Kolakoski sequence:\n\nLets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....\n\n# We start the sequence s with the first item from the cycle c: 1\n# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate. \nWe will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.\n\nWe started s with 1 and therefore s[k] states that it should appear only the 1 time.\n\nIncrement k\nGet the next item from c and append it to the end of sequence s. s will then become: 1, 2\nk was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2\nIncrement k\nAppend the next item from the cycle to the list: 1, 2,2, 1\nk is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1\nincrement k\n\n...\n\n'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.\n\n;Task:\n# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.\n# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.\n# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).\n# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 20 members of the sequence generated from (2, 1)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)\n# Check the sequence againt its RLE.\n# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)\n# Check the sequence againt its RLE.\n(There are rules on generating Kolakoski sequences from this method that are broken by the last example)\n\n", "solution": "// Version 1.2.41\n\nfun IntArray.nextInCycle(index: Int) = this[index % this.size]\n\nfun IntArray.kolakoski(len: Int): IntArray {\n val s = IntArray(len)\n var i = 0\n var k = 0\n while (true) {\n s[i] = this.nextInCycle(k)\n if (s[k] > 1) {\n repeat(s[k] - 1) {\n if (++i == len) return s\n s[i] = s[i - 1]\n }\n }\n if (++i == len) return s\n k++\n }\n}\n\nfun IntArray.possibleKolakoski(): Boolean {\n val len = this.size\n val rle = mutableListOf()\n var prev = this[0]\n var count = 1\n for (i in 1 until len) {\n if (this[i] == prev) {\n count++\n }\n else {\n rle.add(count)\n count = 1\n prev = this[i]\n } \n }\n // no point adding final 'count' to rle as we're not going to compare it anyway\n for (i in 0 until rle.size) {\n if (rle[i] != this[i]) return false\n }\n return true\n}\n\nfun main(args: Array) {\n val ias = listOf(\n intArrayOf(1, 2), intArrayOf(2, 1),\n intArrayOf(1, 3, 1, 2), intArrayOf(1, 3, 2, 1)\n )\n val lens = intArrayOf(20, 20, 30, 30)\n for ((i, ia) in ias.withIndex()) {\n val len = lens[i]\n val kol = ia.kolakoski(len)\n println(\"First $len members of the sequence generated by ${ia.asList()}:\")\n println(kol.asList())\n val p = kol.possibleKolakoski()\n println(\"Possible Kolakoski sequence? ${if (p) \"Yes\" else \"No\"}\\n\")\n }\n}"} {"title": "Kosaraju", "language": "Kotlin from Go", "task": "{{wikipedia|Graph}}\n\n\nKosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.\n\nFor this task consider the directed graph with these connections:\n 0 -> 1\n 1 -> 2\n 2 -> 0\n 3 -> 1, 3 -> 2, 3 -> 4\n 4 -> 3, 4 -> 5\n 5 -> 2, 5 -> 6\n 6 -> 5\n 7 -> 4, 7 -> 6, 7 -> 7\n\nAnd report the kosaraju strongly connected component for each node.\n\n;References:\n* The article on Wikipedia.\n\n", "solution": "// version 1.1.3\n\n/* the list index is the first vertex in the edge(s) */\nval g = listOf(\n intArrayOf(1), // 0\n intArrayOf(2), // 1\n intArrayOf(0), // 2\n intArrayOf(1, 2, 4), // 3\n intArrayOf(3, 5), // 4\n intArrayOf(2, 6), // 5\n intArrayOf(5), // 6\n intArrayOf(4, 6, 7) // 7\n)\n \nfun kosaraju(g: List): List> {\n // 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.\n val size = g.size\n val vis = BooleanArray(size) // all false by default\n val l = IntArray(size) // all zero by default\n var x = size // index for filling l in reverse order\n val t = List(size) { mutableListOf() } // transpose graph\n \n // Recursive subroutine 'visit':\n fun visit(u: Int) {\n if (!vis[u]) {\n vis[u] = true\n for (v in g[u]) { \n visit(v)\n t[v].add(u) // construct transpose \n }\n l[--x] = u\n }\n }\n\n // 2. For each vertex u of the graph do visit(u)\n for (u in g.indices) visit(u)\n val c = IntArray(size) // used for component assignment \n\n // Recursive subroutine 'assign':\n fun assign(u: Int, root: Int) {\n if (vis[u]) { // repurpose vis to mean 'unassigned'\n vis[u] = false\n c[u] = root\n for (v in t[u]) assign(v, root)\n }\n }\n\n // 3: For each element u of l in order, do assign(u, u)\n for (u in l) assign(u, u)\n\n // Obtain list of SCC's from 'c' and return it \n return c.withIndex()\n .groupBy { it.value }.values\n .map { ivl -> ivl.map { it.index } }\n}\n\nfun main(args: Array) {\n println(kosaraju(g).joinToString(\"\\n\"))\n}"} {"title": "Lah numbers", "language": "Kotlin from Perl", "task": "Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.\n\nUnsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.\n\nLah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.\n\nLah numbers obey the identities and relations:\n L(n, 0), L(0, k) = 0 # for n, k > 0\n L(n, n) = 1\n L(n, 1) = n!\n L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers\n ''or''\n L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers\n\n;Task:\n:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Lah number'''\n:* '''OEIS:A105278 - Unsigned Lah numbers'''\n:* '''OEIS:A008297 - Signed Lah numbers'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Stirling numbers of the second kind'''\n:* '''Bell numbers'''\n\n\n", "solution": "import java.math.BigInteger\n\nfun factorial(n: BigInteger): BigInteger {\n if (n == BigInteger.ZERO) return BigInteger.ONE\n if (n == BigInteger.ONE) return BigInteger.ONE\n var prod = BigInteger.ONE\n var num = n\n while (num > BigInteger.ONE) {\n prod *= num\n num--\n }\n return prod\n}\n\nfun lah(n: BigInteger, k: BigInteger): BigInteger {\n if (k == BigInteger.ONE) return factorial(n)\n if (k == n) return BigInteger.ONE\n if (k > n) return BigInteger.ZERO\n if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO\n return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k)\n}\n\nfun main() {\n println(\"Unsigned Lah numbers: L(n, k):\")\n print(\"n/k \")\n for (i in 0..12) {\n print(\"%10d \".format(i))\n }\n println()\n for (row in 0..12) {\n print(\"%-3d\".format(row))\n for (i in 0..row) {\n val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong()))\n print(\"%11d\".format(l))\n }\n println()\n }\n println(\"\\nMaximum value from the L(100, *) row:\")\n println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max())\n}"} {"title": "Largest int from concatenated ints", "language": "Kotlin from C#", "task": "Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.\n\nUse the following two sets of integers as tests and show your program output here.\n\n:::::* {1, 34, 3, 98, 9, 76, 45, 4}\n:::::* {54, 546, 548, 60}\n\n\n;Possible algorithms:\n# A solution could be found by trying all combinations and return the best. \n# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.\n# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.\n\n\n;See also:\n* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?\n* Constructing the largest number possible by rearranging a list\n\n", "solution": "import kotlin.Comparator\n\nfun main(args: Array) {\n val comparator = Comparator { x, y -> \"$x$y\".compareTo(\"$y$x\") }\n\n fun findLargestSequence(array: IntArray): String {\n return array.sortedWith(comparator.reversed()).joinToString(\"\") { it.toString() }\n }\n\n for (array in listOf(\n intArrayOf(1, 34, 3, 98, 9, 76, 45, 4),\n intArrayOf(54, 546, 548, 60),\n )) {\n println(\"%s -> %s\".format(array.contentToString(), findLargestSequence(array)))\n }\n}"} {"title": "Largest number divisible by its digits", "language": "Kotlin", "task": "Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.\n\n\nThese numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the\n(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. \n\n\n;Example:\n'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.\n\n\nNote that the digit zero (0) can not be in the number as integer division by zero is undefined. \n\nThe digits must all be unique so a base ten number will have at most '''9''' digits.\n\nFeel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)\n\n\n;Stretch goal:\nDo the same thing for hexadecimal.\n\n\n;Related tasks:\n:* gapful numbers.\n:* palindromic gapful numbers. \n\n\n;Also see:\n:* The OEIS sequence: A115569: Lynch-Bell numbers. \n\n", "solution": "// version 1.1.4-3\n\nfun Int.divByAll(digits: List) = digits.all { this % (it - '0') == 0 }\n\nfun main(args: Array) {\n val magic = 9 * 8 * 7\n val high = 9876432 / magic * magic\n for (i in high downTo magic step magic) {\n if (i % 10 == 0) continue // can't end in '0'\n val s = i.toString()\n if ('0' in s || '5' in s) continue // can't contain '0' or '5'\n val sd = s.toCharArray().distinct()\n if (sd.size != s.length) continue // digits must be unique\n if (i.divByAll(sd)) {\n println(\"Largest decimal number is $i\")\n return\n }\n }\n}"} {"title": "Last Friday of each month", "language": "Kotlin", "task": "Write a program or a script that returns the date of the last Fridays of each month of a given year. \n\nThe year may be given through any simple input method in your language (command line, std in, etc).\n\n\nExample of an expected output:\n./last_fridays 2012\n2012-01-27\n2012-02-24\n2012-03-30\n2012-04-27\n2012-05-25\n2012-06-29\n2012-07-27\n2012-08-31\n2012-09-28\n2012-10-26\n2012-11-30\n2012-12-28\n\n\n;Related tasks\n* [[Five weekends]]\n* [[Day of the week]]\n* [[Find the last Sunday of each month]]\n\n", "solution": "// version 1.0.6\n\nimport java.util.*\n\nfun main(args: Array) {\n print(\"Enter a year : \")\n val year = readLine()!!.toInt()\n \n println(\"The last Fridays of each month in $year are as follows:\")\n val calendar = GregorianCalendar(year, 0, 31)\n for (month in 1..12) {\n val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)\n var offset = calendar[Calendar.DAY_OF_WEEK] - Calendar.FRIDAY\n if (offset < 0) offset += 7\n val lastFriday = daysInMonth - offset\n println(\"$year-\" + \"%02d-\".format(month) + \"%02d\".format(lastFriday))\n if (month < 12) {\n calendar.add(Calendar.DAY_OF_MONTH, 1)\n calendar.add(Calendar.MONTH, 1)\n calendar.add(Calendar.DAY_OF_MONTH, -1)\n }\n }\n}"} {"title": "Last letter-first letter", "language": "Kotlin from Java", "task": "A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. \n\n\nFor example, with \"animals\" as the category,\n\nChild 1: dog \nChild 2: goldfish\nChild 1: hippopotamus\nChild 2: snake\n...\n\n\n\n;Task:\nTake the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. \n\nNo Pokemon name is to be repeated.\n\n\naudino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon\ncresselia croagunk darmanitan deino emboar emolga exeggcute gabite\ngirafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan\nkricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine\nnosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2\nporygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking\nsealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko\ntyrogue vigoroth vulpix wailord wartortle whismur wingull yamask\n\n\n\nExtra brownie points for dealing with the full list of 646 names.\n\n", "solution": "// version 1.1.2\n\nvar maxPathLength = 0\nvar maxPathLengthCount = 0\nval maxPathExample = StringBuilder(500)\n\nval names = arrayOf(\n \"audino\", \"bagon\", \"baltoy\", \"banette\", \"bidoof\", \n \"braviary\", \"bronzor\", \"carracosta\", \"charmeleon\", \"cresselia\", \n \"croagunk\", \"darmanitan\", \"deino\", \"emboar\", \"emolga\", \n \"exeggcute\", \"gabite\", \"girafarig\", \"gulpin\", \"haxorus\", \n \"heatmor\", \"heatran\", \"ivysaur\", \"jellicent\", \"jumpluff\", \n \"kangaskhan\", \"kricketune\", \"landorus\", \"ledyba\", \"loudred\", \n \"lumineon\", \"lunatone\", \"machamp\", \"magnezone\", \"mamoswine\", \n \"nosepass\", \"petilil\", \"pidgeotto\", \"pikachu\", \"pinsir\", \n \"poliwrath\", \"poochyena\", \"porygon2\", \"porygonz\", \"registeel\", \n \"relicanth\", \"remoraid\", \"rufflet\", \"sableye\", \"scolipede\", \n \"scrafty\", \"seaking\", \"sealeo\", \"silcoon\", \"simisear\", \n \"snivy\", \"snorlax\", \"spoink\", \"starly\", \"tirtouga\",\n \"trapinch\", \"treecko\", \"tyrogue\", \"vigoroth\", \"vulpix\",\n \"wailord\", \"wartortle\", \"whismur\", \"wingull\", \"yamask\"\n)\n\nfun search(part: Array, offset: Int) {\n if (offset > maxPathLength) {\n maxPathLength = offset\n maxPathLengthCount = 1\n }\n else if (offset == maxPathLength) {\n maxPathLengthCount++\n maxPathExample.setLength(0)\n for (i in 0 until offset) {\n maxPathExample.append(if (i % 5 == 0) \"\\n \" else \" \")\n maxPathExample.append(part[i])\n } \n }\n val lastChar = part[offset - 1].last()\n for (i in offset until part.size) {\n if (part[i][0] == lastChar) {\n val tmp = names[offset]\n names[offset] = names[i]\n names[i] = tmp\n search(names, offset + 1)\n names[i] = names[offset]\n names[offset] = tmp\n }\n }\n}\n\nfun main(args: Array) {\n for (i in 0 until names.size) {\n val tmp = names[0]\n names[0] = names[i]\n names[i] = tmp\n search(names, 1)\n names[i] = names[0]\n names[0] = tmp\n }\n println(\"Maximum path length : $maxPathLength\")\n println(\"Paths of that length : $maxPathLengthCount\")\n println(\"Example path of that length : $maxPathExample\")\n}"} {"title": "Latin Squares in reduced form", "language": "Kotlin from D", "task": "A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.\n\nFor a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.\n\nDemonstrate by:\n* displaying the four reduced Latin Squares of order 4.\n* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.\n\n", "solution": "typealias Matrix = MutableList>\n\nfun dList(n: Int, sp: Int): Matrix {\n val start = sp - 1 // use 0 basing\n\n val a = generateSequence(0) { it + 1 }.take(n).toMutableList()\n a[start] = a[0].also { a[0] = a[start] }\n a.subList(1, a.size).sort()\n\n val first = a[1]\n // recursive closure permutes a[1:]\n val r = mutableListOf>()\n fun recurse(last: Int) {\n if (last == first) {\n // bottom of recursion. you get here once for each permutation.\n // test if permutation is deranged\n for (jv in a.subList(1, a.size).withIndex()) {\n if (jv.index + 1 == jv.value) {\n return // no, ignore it\n }\n }\n // yes, save a copy with 1 based indexing\n val b = a.map { it + 1 }\n r.add(b.toMutableList())\n return\n }\n for (i in last.downTo(1)) {\n a[i] = a[last].also { a[last] = a[i] }\n recurse(last - 1)\n a[i] = a[last].also { a[last] = a[i] }\n }\n }\n recurse(n - 1)\n return r\n}\n\nfun reducedLatinSquares(n: Int, echo: Boolean): Long {\n if (n <= 0) {\n if (echo) {\n println(\"[]\\n\")\n }\n return 0\n } else if (n == 1) {\n if (echo) {\n println(\"[1]\\n\")\n }\n return 1\n }\n\n val rlatin = MutableList(n) { MutableList(n) { it } }\n // first row\n for (j in 0 until n) {\n rlatin[0][j] = j + 1\n }\n\n var count = 0L\n fun recurse(i: Int) {\n val rows = dList(n, i)\n\n outer@\n for (r in 0 until rows.size) {\n rlatin[i - 1] = rows[r].toMutableList()\n for (k in 0 until i - 1) {\n for (j in 1 until n) {\n if (rlatin[k][j] == rlatin[i - 1][j]) {\n if (r < rows.size - 1) {\n continue@outer\n }\n if (i > 2) {\n return\n }\n }\n }\n }\n if (i < n) {\n recurse(i + 1)\n } else {\n count++\n if (echo) {\n printSquare(rlatin)\n }\n }\n }\n }\n\n // remaining rows\n recurse(2)\n return count\n}\n\nfun printSquare(latin: Matrix) {\n for (row in latin) {\n println(row)\n }\n println()\n}\n\nfun factorial(n: Long): Long {\n if (n == 0L) {\n return 1\n }\n var prod = 1L\n for (i in 2..n) {\n prod *= i\n }\n return prod\n}\n\nfun main() {\n println(\"The four reduced latin squares of order 4 are:\\n\")\n reducedLatinSquares(4, true)\n\n println(\"The size of the set of reduced latin squares for the following orders\")\n println(\"and hence the total number of latin squares of these orders are:\\n\")\n for (n in 1 until 7) {\n val size = reducedLatinSquares(n, false)\n var f = factorial(n - 1.toLong())\n f *= f * n * size\n println(\"Order $n: Size %-4d x $n! x ${n - 1}! => Total $f\".format(size))\n }\n}"} {"title": "Law of cosines - triples", "language": "Kotlin from Go", "task": "The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:\n A2 + B2 - 2ABcos(g) = C2 \n\n;Specific angles:\nFor an angle of of '''90o''' this becomes the more familiar \"Pythagoras equation\":\n A2 + B2 = C2 \n\nFor an angle of '''60o''' this becomes the less familiar equation:\n A2 + B2 - AB = C2 \n\nAnd finally for an angle of '''120o''' this becomes the equation:\n A2 + B2 + AB = C2 \n\n\n;Task:\n* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.\n* Restrain all sides to the integers '''1..13''' inclusive.\n* Show how many results there are for each of the three angles mentioned above.\n* Display results on this page.\n\n\nNote: Triangles with the same length sides but different order are to be treated as the same. \n\n;Optional Extra credit:\n* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.\n\n\n;Related Task\n* [[Pythagorean triples]]\n\n\n;See also:\n* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video\n\n", "solution": "// Version 1.2.70\n\nval squares13 = mutableMapOf()\nval squares10000 = mutableMapOf()\n\nclass Trio(val a: Int, val b: Int, val c: Int) {\n override fun toString() = \"($a $b $c)\"\n}\n\nfun init() {\n for (i in 1..13) squares13.put(i * i, i)\n for (i in 1..10000) squares10000.put(i * i, i)\n}\n\nfun solve(angle :Int, maxLen: Int, allowSame: Boolean): List {\n val solutions = mutableListOf()\n for (a in 1..maxLen) {\n inner@ for (b in a..maxLen) {\n var lhs = a * a + b * b\n if (angle != 90) {\n when (angle) {\n 60 -> lhs -= a * b\n 120 -> lhs += a * b\n else -> throw RuntimeException(\"Angle must be 60, 90 or 120 degrees\")\n }\n }\n when (maxLen) {\n 13 -> {\n val c = squares13[lhs]\n if (c != null) {\n if (!allowSame && a == b && b == c) continue@inner\n solutions.add(Trio(a, b, c))\n }\n }\n\n 10000 -> {\n val c = squares10000[lhs]\n if (c != null) {\n if (!allowSame && a == b && b == c) continue@inner\n solutions.add(Trio(a, b, c))\n }\n }\n\n else -> throw RuntimeException(\"Maximum length must be either 13 or 10000\")\n }\n }\n }\n return solutions\n}\n\nfun main(args: Array) {\n init()\n print(\"For sides in the range [1, 13] \")\n println(\"where they can all be of the same length:-\\n\")\n val angles = intArrayOf(90, 60, 120)\n lateinit var solutions: List\n for (angle in angles) {\n solutions = solve(angle, 13, true)\n print(\" For an angle of ${angle} degrees\")\n println(\" there are ${solutions.size} solutions, namely:\")\n println(\" ${solutions.joinToString(\" \", \"[\", \"]\")}\\n\")\n }\n print(\"For sides in the range [1, 10000] \")\n println(\"where they cannot ALL be of the same length:-\\n\")\n solutions = solve(60, 10000, false)\n print(\" For an angle of 60 degrees\")\n println(\" there are ${solutions.size} solutions.\")\n}"} {"title": "Least common multiple", "language": "Kotlin", "task": "Compute the least common multiple (LCM) of two integers.\n\nGiven ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. \n\n\n;Example:\nThe least common multiple of '''12''' and '''18''' is '''36''', because:\n:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and \n:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and \n:* there is no positive integer less than '''36''' that has both factors. \n\n\nAs a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.\n\n\nOne way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.\n\nIf you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.\n\n\n:::: \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)}\n\n\nOne can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.\n\n\n;Related task\n:* greatest common divisor.\n\n\n;See also:\n* MathWorld entry: Least Common Multiple.\n* Wikipedia entry: Least common multiple.\n\n", "solution": "fun main(args: Array) {\n fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)\n fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b\n println(lcm(15, 9))\n}\n"} {"title": "Left factorials", "language": "Kotlin", "task": "'''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums''; \nthe same notation can be confusingly seen being used for the two different definitions.\n\nSometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations: \n:::::::* !''n''` \n:::::::* !''n'' \n:::::::* ''n''! \n\n\n(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)\n\n\nThis Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':\n\n::::: !n = \\sum_{k=0}^{n-1} k! \n\n:::: where\n\n::::: !0 = 0\n\n\n\n;Task\nDisplay the left factorials for:\n* zero through ten (inclusive)\n* 20 through 110 (inclusive) by tens\n\n\nDisplay the length (in decimal digits) of the left factorials for:\n* 1,000 through 10,000 (inclusive), by thousands.\n\n\n;Also see:\n* The OEIS entry: A003422 left factorials\n* The MathWorld entry: left factorial\n* The MathWorld entry: factorial sums\n* The MathWorld entry: subfactorial\n\n\n;Related task:\n* permutations/derangements (subfactorials)\n\n", "solution": "// version 1.0.6\n\nimport java.math.BigInteger\n\nfun leftFactorial(n: Int): BigInteger {\n if (n == 0) return BigInteger.ZERO\n var fact = BigInteger.ONE\n var sum = fact\n for (i in 1 until n) {\n fact *= BigInteger.valueOf(i.toLong())\n sum += fact\n } \n return sum\n}\n \nfun main(args: Array) {\n for (i in 0..110) \n if (i <= 10 || (i % 10) == 0) \n println(\"!${i.toString().padEnd(3)} = ${leftFactorial(i)}\")\n println(\"\\nLength of the following left factorials:\")\n for (i in 1000..10000 step 1000) \n println(\"!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits\")\n}"} {"title": "Levenshtein distance", "language": "Kotlin", "task": "{{Wikipedia}}\n\nIn information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. \n\n\n;Example:\nThe Levenshtein distance between \"'''kitten'''\" and \"'''sitting'''\" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:\n::# '''k'''itten '''s'''itten (substitution of 'k' with 's')\n::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')\n::# sittin sittin'''g''' (insert 'g' at the end).\n\n\n''The Levenshtein distance between \"'''rosettacode'''\", \"'''raisethysword'''\" is '''8'''.\n\n''The distance between two strings is same as that when both strings are reversed.''\n\n\n;Task:\nImplements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between \"kitten\" and \"sitting\". \n\n\n;Related task:\n* [[Longest common subsequence]]\n\n\n\n", "solution": "// version 1.0.6\n\n// Uses the \"iterative with two matrix rows\" algorithm referred to in the Wikipedia article.\n\nfun levenshtein(s: String, t: String): Int {\n // degenerate cases\n if (s == t) return 0\n if (s == \"\") return t.length\n if (t == \"\") return s.length\n\n // create two integer arrays of distances and initialize the first one\n val v0 = IntArray(t.length + 1) { it } // previous\n val v1 = IntArray(t.length + 1) // current\n\n var cost: Int\n for (i in 0 until s.length) {\n // calculate v1 from v0\n v1[0] = i + 1\n for (j in 0 until t.length) {\n cost = if (s[i] == t[j]) 0 else 1\n v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost)) \n }\n // copy v1 to v0 for next iteration\n for (j in 0 .. t.length) v0[j] = v1[j]\n }\n return v1[t.length]\n}\n\nfun main(args: Array) {\n println(\"'kitten' to 'sitting' => ${levenshtein(\"kitten\", \"sitting\")}\")\n println(\"'rosettacode' to 'raisethysword' => ${levenshtein(\"rosettacode\", \"raisethysword\")}\") \n println(\"'sleep' to 'fleeting' => ${levenshtein(\"sleep\", \"fleeting\")}\")\n}"} {"title": "Levenshtein distance/Alignment", "language": "Kotlin from Java", "task": "The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.\n\nAn alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is:\n\n\nP-LACE\nPALACE\n\n\n\n;Task:\nWrite a function that shows the alignment of two strings for the corresponding levenshtein distance. \n\nAs an example, use the words \"rosettacode\" and \"raisethysword\".\n\nYou can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).\n\n", "solution": "// version 1.1.3\n\nfun levenshteinAlign(a: String, b: String): Array {\n val aa = a.toLowerCase()\n val bb = b.toLowerCase()\n val costs = Array(a.length + 1) { IntArray(b.length + 1) }\n for (j in 0..b.length) costs[0][j] = j\n for (i in 1..a.length) {\n costs[i][0] = i\n for (j in 1..b.length) {\n val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1) \n costs[i][j] = minOf(1 + minOf(costs[i - 1][j], costs[i][j - 1]), temp)\n }\n }\n\n // walk back through matrix to figure out path\n val aPathRev = StringBuilder()\n val bPathRev = StringBuilder()\n var i = a.length\n var j = b.length\n while (i != 0 && j != 0) {\n val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1)\n when (costs[i][j]) {\n temp -> {\n aPathRev.append(aa[--i])\n bPathRev.append(bb[--j])\n }\n\n 1 + costs[i-1][j] -> {\n aPathRev.append(aa[--i])\n bPathRev.append('-')\n }\n\n 1 + costs[i][j-1] -> {\n aPathRev.append('-')\n bPathRev.append(bb[--j])\n }\n }\n }\n return arrayOf(aPathRev.reverse().toString(), bPathRev.reverse().toString())\n}\n\nfun main(args: Array) {\n var result = levenshteinAlign(\"place\", \"palace\")\n println(result[0])\n println(result[1])\n println() \n result = levenshteinAlign(\"rosettacode\",\"raisethysword\")\n println(result[0])\n println(result[1])\n}"} {"title": "List rooted trees", "language": "Kotlin from C", "task": "You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.\n\nIf we use a matching pair of parentheses to represent a bag, the ways are:\n\nFor 1 bag, there's one way:\n ()\t<- a bag\n\nfor 2 bags, there's one way:\n (())\t<- one bag in another\n\nfor 3 bags, there are two:\n ((())) <- 3 bags nested Russian doll style\n (()()) <- 2 bags side by side, inside the third\n\nfor 4 bags, four:\n (()()())\n ((())())\n ((()()))\n (((())))\n\nNote that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.\n\nIt's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.\n\n\n;Task: \nWrite a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.\n\nThis task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.\n\nAs an example output, run 5 bags. There should be 9 ways.\n\n", "solution": "// version 1.1.3\n\ntypealias Tree = Long\n\nval treeList = mutableListOf()\nval offset = IntArray(32) { if (it == 1) 1 else 0 } \n\nfun append(t: Tree) {\n treeList.add(1L or (t shl 1))\n}\n\nfun show(t: Tree, l: Int) {\n var tt = t\n var ll = l\n while (ll-- > 0) {\n print(if (tt % 2L == 1L) \"(\" else \")\")\n tt = tt ushr 1\n }\n}\n\nfun listTrees(n: Int) {\n for (i in offset[n] until offset[n + 1]) {\n show(treeList[i], n * 2)\n println()\n }\n}\n\n/* assemble tree from subtrees\n\tn: length of tree we want to make\n\tt: assembled parts so far\n\tsl: length of subtree we are looking at\n\tpos: offset of subtree we are looking at\n\trem: remaining length to be put together\n*/\n\nfun assemble(n: Int, t: Tree, sl: Int, pos: Int, rem: Int) {\n if (rem == 0) {\n append(t)\n return\n }\n\n var pp = pos\n var ss = sl\n\n if (sl > rem) { // need smaller subtrees\n ss = rem\n pp = offset[ss]\n }\n else if (pp >= offset[ss + 1]) {\n // used up sl-trees, try smaller ones\n ss--\n if(ss == 0) return\n pp = offset[ss]\n }\n\n assemble(n, (t shl (2 * ss)) or treeList[pp], ss, pp, rem - ss)\n assemble(n, t, ss, pp + 1, rem)\n}\n\nfun makeTrees(n: Int) {\n if (offset[n + 1] != 0) return\n if (n > 0) makeTrees(n - 1)\n assemble(n, 0, n - 1, offset[n - 1], n - 1)\n offset[n + 1] = treeList.size\n}\n\nfun main(args: Array) {\n if (args.size != 1) {\n throw IllegalArgumentException(\"There must be exactly 1 command line argument\")\n }\n val n = args[0].toIntOrNull()\n if (n == null) throw IllegalArgumentException(\"Argument is not a valid number\")\n // n limited to 12 to avoid overflowing default stack \n if (n !in 1..12) throw IllegalArgumentException(\"Argument must be between 1 and 12\")\n\n // init 1-tree\n append(0)\n \n makeTrees(n)\n println(\"Number of $n-trees: ${offset[n + 1] - offset[n]}\") \n listTrees(n)\n}"} {"title": "Long literals, with continuations", "language": "Kotlin", "task": "This task is about writing a computer program that has long literals (character\nliterals that may require specifying the words/tokens on more than one (source)\nline, either with continuations or some other method, such as abutments or\nconcatenations (or some other mechanisms).\n\n\nThe literal is to be in the form of a \"list\", a literal that contains many\nwords (tokens) separated by a blank (space), in this case (so as to have a\ncommon list), the (English) names of the chemical elements of the periodic table.\n\n\nThe list is to be in (ascending) order of the (chemical) element's atomic number:\n\n ''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''\n\n... up to the last known (named) chemical element (at this time).\n\n\nDo not include any of the \"unnamed\" chemical element names such as:\n\n ''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''\n\n\nTo make computer programming languages comparable, the statement widths should be\nrestricted to less than '''81''' bytes (characters), or less\nif a computer programming language has more restrictive limitations or standards.\n\nAlso mention what column the programming statements can start in if ''not'' \nin column one.\n\n\nThe list ''may'' have leading/embedded/trailing blanks during the\ndeclaration (the actual program statements), this is allow the list to be\nmore readable. The \"final\" list shouldn't have any leading/trailing or superfluous\nblanks (when stored in the program's \"memory\").\n\nThis list should be written with the idea in mind that the\nprogram ''will'' be updated, most likely someone other than the\noriginal author, as there will be newer (discovered) elements of the periodic\ntable being added (possibly in the near future). These future updates\nshould be one of the primary concerns in writing these programs and it should be \"easy\"\nfor someone else to add chemical elements to the list (within the computer\nprogram).\n\nAttention should be paid so as to not exceed the ''clause length'' of\ncontinued or specified statements, if there is such a restriction. If the\nlimit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.\n\n\n;Task:\n:* Write a computer program (by whatever name) to contain a list of the known elements.\n:* The program should eventually contain a long literal of words (the elements).\n:* The literal should show how one could create a long list of blank-delineated words.\n:* The \"final\" (stored) list should only have a single blank between elements.\n:* Try to use the most idiomatic approach(es) in creating the final list.\n:* Use continuation if possible, and/or show alternatives (possibly using concatenation).\n:* Use a program comment to explain what the continuation character is if it isn't obvious.\n:* The program should contain a variable that has the date of the last update/revision.\n:* The program, when run, should display with verbiage:\n:::* The last update/revision date (and should be unambiguous).\n:::* The number of chemical elements in the list.\n:::* The name of the highest (last) element name.\n\n\nShow all output here, on this page.\n\n\n\n", "solution": "import java.time.Instant\n\nconst val elementsChunk = \"\"\"\nhydrogen helium lithium beryllium\nboron carbon nitrogen oxygen\nfluorine neon sodium magnesium\naluminum silicon phosphorous sulfur\nchlorine argon potassium calcium\nscandium titanium vanadium chromium\nmanganese iron cobalt nickel\ncopper zinc gallium germanium\narsenic selenium bromine krypton\nrubidium strontium yttrium zirconium\nniobium molybdenum technetium ruthenium\nrhodium palladium silver cadmium\nindium tin antimony tellurium\niodine xenon cesium barium\nlanthanum cerium praseodymium neodymium\npromethium samarium europium gadolinium\nterbium dysprosium holmium erbium\nthulium ytterbium lutetium hafnium\ntantalum tungsten rhenium osmium\niridium platinum gold mercury\nthallium lead bismuth polonium\nastatine radon francium radium\nactinium thorium protactinium uranium\nneptunium plutonium americium curium\nberkelium californium einsteinium fermium\nmendelevium nobelium lawrencium rutherfordium\ndubnium seaborgium bohrium hassium\nmeitnerium darmstadtium roentgenium copernicium\nnihonium flerovium moscovium livermorium\ntennessine oganesson\n\"\"\"\n\nconst val unamedElementsChunk = \"\"\"\nununennium unquadnilium triunhexium penthextrium\npenthexpentium septhexunium octenntrium ennennbium\n\"\"\"\n\nfun main() {\n fun String.splitToList() = trim().split(\"\\\\s+\".toRegex());\n val elementsList = \n elementsChunk.splitToList()\n .filterNot(unamedElementsChunk.splitToList().toSet()::contains)\n println(\"Last revision Date: ${Instant.now()}\")\n println(\"Number of elements: ${elementsList.size}\")\n println(\"Last element : ${elementsList.last()}\")\n println(\"The elements are : ${elementsList.joinToString(\" \", limit = 5)}\")\n}"} {"title": "Long year", "language": "Kotlin", "task": "Most years have 52 weeks, some have 53, according to ISO8601.\n\n\n;Task:\nWrite a function which determines if a given year is long (53 weeks) or not, and demonstrate it.\n\n", "solution": "fun main() {\n val has53Weeks = { year: Int -> LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53 }\n println(\"Long years this century:\")\n (2000..2100).filter(has53Weeks)\n .forEach { year -> print(\"$year \")}\n}\n"} {"title": "Longest common subsequence", "language": "Kotlin", "task": "'''Introduction'''\n\nDefine a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.\n\nThe '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.\n\nLet ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.\n\nAn ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.\n\nThe set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.\n\nDefine a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.\n\nWe say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.\n\nDefine the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.\n\nA chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.\n\nA chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].\n\nEvery Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.\n\nAccording to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.\n\n'''Background'''\n\nWhere the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.\n\nThe divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.\n\nThis quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.\n\nIn the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.\n\nA binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').\n\n'''Note'''\n\n[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').\n\n'''Legend'''\n\n A, B are input strings of lengths m, n respectively\n p is the length of the LCS\n M is the set of matches (i, j) such that A[i] = B[j]\n r is the magnitude of M\n s is the magnitude of the alphabet S of distinct symbols in A + B\n\n'''References'''\n\n[Dilworth 1950] \"A decomposition theorem for partially ordered sets\"\nby Robert P. Dilworth, published January 1950,\nAnnals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]\n\n[Goeman and Clausen 2002] \"A New Practical Linear Space Algorithm for the Longest Common\nSubsequence Problem\" by Heiko Goeman and Michael Clausen,\npublished 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]\n\n[Hirschberg 1975] \"A linear space algorithm for computing maximal common subsequences\"\nby Daniel S. Hirschberg, published June 1975\nCommunications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]\n\n[Hunt and McIlroy 1976] \"An Algorithm for Differential File Comparison\"\nby James W. Hunt and M. Douglas McIlroy, June 1976\nComputing Science Technical Report, Bell Laboratories 41\n\n[Hunt and Szymanski 1977] \"A Fast Algorithm for Computing Longest Common Subsequences\"\nby James W. Hunt and Thomas G. Szymanski, published May 1977\nCommunications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]\n\n[Rick 2000] \"Simple and fast linear space computation of longest common subsequences\"\nby Claus Rick, received 17 March 2000, Information Processing Letters,\nElsevier Science [Volume 75, ''pp.'' 275-281]\n\n\n'''Examples'''\n\nThe sequences \"1234\" and \"1224533324\" have an LCS of \"1234\":\n '''1234'''\n '''12'''245'''3'''332'''4'''\n\nFor a string example, consider the sequences \"thisisatest\" and \"testing123testing\". An LCS would be \"tsitest\":\n '''t'''hi'''si'''sa'''test'''\n '''t'''e'''s'''t'''i'''ng123'''test'''ing\n\nIn this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.\n\nFor more information on this problem please see Wikipedia.\n\n\n", "solution": "// version 1.1.2\n\nfun lcs(x: String, y: String): String {\n if (x.length == 0 || y.length == 0) return \"\"\n val x1 = x.dropLast(1) \n val y1 = y.dropLast(1)\n if (x.last() == y.last()) return lcs(x1, y1) + x.last()\n val x2 = lcs(x, y1)\n val y2 = lcs(x1, y)\n return if (x2.length > y2.length) x2 else y2\n}\n\nfun main(args: Array) {\n val x = \"thisisatest\"\n val y = \"testing123testing\"\n println(lcs(x, y))\n}"} {"title": "Longest common substring", "language": "Kotlin from Java", "task": "Write a function that returns the longest common substring of two strings. \n\nUse it within a program that demonstrates sample output from the function, which will consist of the longest common substring between \"thisisatest\" and \"testing123testing\". \n\nNote that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. \n\nHence, the [[longest common subsequence]] between \"thisisatest\" and \"testing123testing\" is \"tsitest\", whereas the longest common sub''string'' is just \"test\".\n\n\n\n\n;References:\n*Generalize Suffix Tree\n*[[Ukkonen's Suffix Tree Construction]]\n\n", "solution": "// version 1.1.2\n\nfun lcs(a: String, b: String): String {\n if (a.length > b.length) return lcs(b, a)\n var res = \"\"\n for (ai in 0 until a.length) {\n for (len in a.length - ai downTo 1) {\n for (bi in 0 until b.length - len) {\n if (a.regionMatches(ai, b, bi,len) && len > res.length) {\n res = a.substring(ai, ai + len)\n }\n }\n }\n }\n return res\n}\n\nfun main(args: Array) = println(lcs(\"testing123testing\", \"thisisatest\"))"} {"title": "Longest increasing subsequence", "language": "Kotlin", "task": "Calculate and show here a longest increasing subsequence of the list:\n:\\{3, 2, 6, 4, 5, 1\\}\nAnd of the list:\n:\\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\\}\n\nNote that a list may have more than one subsequence that is of the maximum length.\n\n\n\n;Ref:\n# Dynamic Programming #1: Longest Increasing Subsequence on YouTube\n# An efficient solution can be based on Patience sorting.\n\n", "solution": "// version 1.1.0\n\nfun longestIncreasingSubsequence(x: IntArray): IntArray = \n when (x.size) {\n 0 -> IntArray(0)\n 1 -> x\n else -> {\n val n = x.size\n val p = IntArray(n) \n val m = IntArray(n + 1)\n var len = 0\n for (i in 0 until n) { \n var lo = 1\n var hi = len\n while (lo <= hi) {\n val mid = Math.ceil((lo + hi) / 2.0).toInt()\n if (x[m[mid]] < x[i]) lo = mid + 1\n else hi = mid - 1\n }\n val newLen = lo \n p[i] = m[newLen - 1]\n m[newLen] = i\n if (newLen > len) len = newLen\n } \n val s = IntArray(len)\n var k = m[len]\n for (i in len - 1 downTo 0) {\n s[i] = x[k]\n k = p[k]\n }\n s \n } \n }\n\nfun main(args: Array) {\n val lists = listOf(\n intArrayOf(3, 2, 6, 4, 5, 1),\n intArrayOf(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)\n )\n lists.forEach { println(longestIncreasingSubsequence(it).asList()) }\n}"} {"title": "Lucky and even lucky numbers", "language": "Kotlin", "task": "Note that in the following explanation list indices are assumed to start at ''one''.\n\n;Definition of lucky numbers\n''Lucky numbers'' are positive integers that are formed by:\n\n# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...\n# Return the first number from the list (which is '''1''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''3''').\n#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''7''').\n#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...\n#* Note then return the 4th number from the list (which is '''9''').\n#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...\n#* Take the 5th, i.e. '''13'''. Remove every 13th.\n#* Take the 6th, i.e. '''15'''. Remove every 15th.\n#* Take the 7th, i.e. '''21'''. Remove every 21th.\n#* Take the 8th, i.e. '''25'''. Remove every 25th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Definition of even lucky numbers\nThis follows the same rules as the definition of lucky numbers above ''except for the very first step'':\n# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...\n# Return the first number from the list (which is '''2''').\n# (Loop begins here)\n#* Note then return the second number from the list (which is '''4''').\n#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...\n# (Expanding the loop a few more times...)\n#* Note then return the third number from the list (which is '''6''').\n#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...\n#* Take the 4th, i.e. '''10'''. Remove every 10th.\n#* Take the 5th, i.e. '''12'''. Remove every 12th.\n# (Rule for the loop)\n#* Note the nth, which is m.\n#* Remove every mth.\n#* Increment n.\n\n;Task requirements\n* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' \n* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:\n** missing arguments\n** too many arguments\n** number (or numbers) aren't legal\n** misspelled argument ('''lucky''' or '''evenLucky''')\n* The command line handling should:\n** support mixed case handling of the (non-numeric) arguments\n** support printing a particular number\n** support printing a range of numbers by their index\n** support printing a range of numbers by their values\n* The resulting list of numbers should be printed on a single line.\n\nThe program should support the arguments:\n\n what is displayed (on a single line)\n argument(s) (optional verbiage is encouraged)\n +-------------------+----------------------------------------------------+\n | j | Jth lucky number |\n | j , lucky | Jth lucky number |\n | j , evenLucky | Jth even lucky number |\n | | |\n | j k | Jth through Kth (inclusive) lucky numbers |\n | j k lucky | Jth through Kth (inclusive) lucky numbers |\n | j k evenLucky | Jth through Kth (inclusive) even lucky numbers |\n | | |\n | j -k | all lucky numbers in the range j --> |k| |\n | j -k lucky | all lucky numbers in the range j --> |k| |\n | j -k evenLucky | all even lucky numbers in the range j --> |k| |\n +-------------------+----------------------------------------------------+\n where |k| is the absolute value of k\n\nDemonstrate the program by:\n* showing the first twenty ''lucky'' numbers\n* showing the first twenty ''even lucky'' numbers\n* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)\n* showing all ''even lucky'' numbers in the same range as above\n* showing the 10,000th ''lucky'' number (extra credit)\n* showing the 10,000th ''even lucky'' number (extra credit)\n\n;See also:\n* This task is related to the [[Sieve of Eratosthenes]] task.\n* OEIS Wiki Lucky numbers.\n* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.\n* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.\n* Entry lucky numbers on The Eric Weisstein's World of Mathematics.\n", "solution": "// version 1.1.51\n\ntypealias IAE = IllegalArgumentException\n\nval luckyOdd = MutableList(100000) { it * 2 + 1 }\nval luckyEven = MutableList(100000) { it * 2 + 2 }\n\nfun filterLuckyOdd() {\n var n = 2\n while (n < luckyOdd.size) {\n val m = luckyOdd[n - 1]\n val end = (luckyOdd.size / m) * m - 1\n for (j in end downTo m - 1 step m) luckyOdd.removeAt(j)\n n++\n }\n}\n\nfun filterLuckyEven() {\n var n = 2\n while (n < luckyEven.size) {\n val m = luckyEven[n - 1]\n val end = (luckyEven.size / m) * m - 1\n for (j in end downTo m - 1 step m) luckyEven.removeAt(j)\n n++\n }\n}\n\nfun printSingle(j: Int, odd: Boolean) {\n if (odd) {\n if (j >= luckyOdd.size) throw IAE(\"Argument is too big\")\n println(\"Lucky number $j = ${luckyOdd[j - 1]}\")\n }\n else {\n if (j >= luckyEven.size) throw IAE(\"Argument is too big\")\n println(\"Lucky even number $j = ${luckyEven[j - 1]}\")\n }\n}\n\nfun printRange(j: Int, k: Int, odd: Boolean) {\n if (odd) {\n if (k >= luckyOdd.size) throw IAE(\"Argument is too big\")\n println(\"Lucky numbers $j to $k are:\\n${luckyOdd.drop(j - 1).take(k - j + 1)}\")\n }\n else {\n if (k >= luckyEven.size) throw IAE(\"Argument is too big\")\n println(\"Lucky even numbers $j to $k are:\\n${luckyEven.drop(j - 1).take(k - j + 1)}\")\n }\n}\n\nfun printBetween(j: Int, k: Int, odd: Boolean) {\n val range = mutableListOf()\n if (odd) {\n val max = luckyOdd[luckyOdd.lastIndex]\n if (j > max || k > max) {\n throw IAE(\"At least one argument is too big\")\n }\n for (num in luckyOdd) {\n if (num < j) continue\n if (num > k) break\n range.add(num)\n }\n println(\"Lucky numbers between $j and $k are:\\n$range\")\n }\n else {\n val max = luckyEven[luckyEven.lastIndex]\n if (j > max || k > max) {\n throw IAE(\"At least one argument is too big\")\n }\n for (num in luckyEven) {\n if (num < j) continue\n if (num > k) break\n range.add(num)\n }\n println(\"Lucky even numbers between $j and $k are:\\n$range\")\n }\n}\n\nfun main(args: Array) {\n if (args.size !in 1..3) throw IAE(\"There must be between 1 and 3 command line arguments\")\n filterLuckyOdd()\n filterLuckyEven()\n val j = args[0].toIntOrNull()\n if (j == null || j < 1) throw IAE(\"First argument must be a positive integer\")\n if (args.size == 1) { printSingle(j, true); return }\n\n if (args.size == 2) {\n val k = args[1].toIntOrNull()\n if (k == null) throw IAE(\"Second argument must be an integer\")\n if (k >= 0) {\n if (j > k) throw IAE(\"Second argument can't be less than first\")\n printRange(j, k, true)\n }\n else {\n val l = -k\n if (j > l) throw IAE(\"The second argument can't be less in absolute value than first\")\n printBetween(j, l, true)\n }\n return\n }\n\n var odd =\n if (args[2].toLowerCase() == \"lucky\") true\n else if (args[2].toLowerCase() == \"evenlucky\") false\n else throw IAE(\"Third argument is invalid\")\n\n if (args[1] == \",\") {\n printSingle(j, odd)\n return\n }\n\n val k = args[1].toIntOrNull()\n if (k == null) throw IAE(\"Second argument must be an integer or a comma\")\n\n if (k >= 0) {\n if (j > k) throw IAE(\"Second argument can't be less than first\")\n printRange(j, k, odd)\n }\n else {\n val l = -k\n if (j > l) throw IAE(\"The second argument can't be less in absolute value than first\")\n printBetween(j, l, odd)\n }\n}"} {"title": "Lychrel numbers", "language": "Kotlin", "task": "::# Take an integer n, greater than zero.\n::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n.\n::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.\n\n\nThe above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.\n\n\n;Example:\nIf n0 = 12 we get\n\n 12\n 12 + 21 = 33, a palindrome!\n\n\nAnd if n0 = 55 we get\n\n 55\n 55 + 55 = 110\n 110 + 011 = 121, a palindrome!\n\n\nNotice that the check for a palindrome happens ''after'' an addition.\n\n\nSome starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. \n\nThese numbers that do not end in a palindrome are called '''Lychrel numbers'''.\n\nFor the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.\n\n\n;Seed and related Lychrel numbers:\nAny integer produced in the sequence of a Lychrel number is also a Lychrel number.\n\nIn general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:\n\n 196\n 196 + 691 = 887\n 887 + 788 = 1675\n 1675 + 5761 = 7436\n 7436 + 6347 = 13783\n 13783 + 38731 = 52514\n 52514 + 41525 = 94039\n ...\n\n\n 689\n 689 + 986 = 1675\n 1675 + 5761 = 7436\n ...\n\nSo we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196. \n\nBecause of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.\n\n\n;Task:\n* Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).\n* Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.\n* Print any seed Lychrel or related number that is itself a palindrome.\n\n\nShow all output here.\n\n\n;References:\n* What's special about 196? Numberphile video.\n* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).\n* Status of the 196 conjecture? Mathoverflow.\n\n", "solution": "// version 1.0.6\n\nimport java.math.BigInteger\n\nconst val ITERATIONS = 500\nconst val LIMIT = 10000\n\nval bigLimit = BigInteger.valueOf(LIMIT.toLong())\n\n// In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel\nval lychrelSieve = IntArray(LIMIT + 1) // all zero by default\nval seedLychrels = mutableListOf()\nval relatedLychrels = mutableSetOf()\n\nfun isPalindrome(bi: BigInteger): Boolean {\n val s = bi.toString()\n return s == s.reversed()\n}\n\nfun lychrelTest(i: Int, seq: MutableList){\n if (i < 1) return\n var bi = BigInteger.valueOf(i.toLong())\n (1 .. ITERATIONS).forEach {\n bi += BigInteger(bi.toString().reversed())\n seq.add(bi)\n if (isPalindrome(bi)) return\n }\n for (j in 0 until seq.size) {\n if (seq[j] <= bigLimit) lychrelSieve[seq[j].toInt()] = 2 \n else break\n } \n val sizeBefore = relatedLychrels.size\n relatedLychrels.addAll(seq) // if all of these can be added 'i' must be a seed Lychrel\n if (relatedLychrels.size - sizeBefore == seq.size) {\n seedLychrels.add(i)\n lychrelSieve[i] = 1 \n }\n else {\n relatedLychrels.add(BigInteger.valueOf(i.toLong()))\n lychrelSieve[i] = 2\n } \n}\n\nfun main(args: Array) { \n val seq = mutableListOf()\n for (i in 1 .. LIMIT) \n if (lychrelSieve[i] == 0) { \n seq.clear() \n lychrelTest(i, seq)\n } \n var related = lychrelSieve.count { it == 2 }\n println(\"Lychrel numbers in the range [1, $LIMIT]\")\n println(\"Maximum iterations = $ITERATIONS\")\n println(\"\\nThere are ${seedLychrels.size} seed Lychrel numbers, namely\")\n println(seedLychrels)\n println(\"\\nThere are also $related related Lychrel numbers in this range\") \n val palindromes = mutableListOf()\n for (i in 1 .. LIMIT)\n if (lychrelSieve[i] > 0 && isPalindrome(BigInteger.valueOf(i.toLong()))) palindromes.add(i)\n println(\"\\nThere are ${palindromes.size} palindromic Lychrel numbers, namely\")\n println(palindromes)\n}"} {"title": "MAC vendor lookup", "language": "Kotlin", "task": "Every connected device around the world comes with a unique Media Access Control address, or a MAC address. \n\nA common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.\n\n\n;Task:\nInterface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.\n\nA MAC address that does not return a valid result should return the String \"N/A\". An error related to the network connectivity or the API should return a null result.\n\nMany implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.\n\n'''{\"errors\":{\"detail\":\"Too Many Requests\",\"message\":\"Please slow down your requests or upgrade your plan at https://macvendors.com\"}}'''\n\n", "solution": "// version 1.1.2\n\nimport java.net.URL\n\nfun lookupVendor(mac: String) = URL(\"http://api.macvendors.com/\" + mac).readText()\n\nfun main(args: Array) {\n val macs = arrayOf(\"FC-A1-3E\", \"FC:FB:FB:01:FA:21\", \"88:53:2E:67:07:BE\", \"D4:F4:6F:C9:EF:8D\")\n for (mac in macs) println(lookupVendor(mac))\n}"} {"title": "MD4", "language": "Kotlin", "task": "Find the MD4 message digest of a string of [[octet]]s. \nUse the ASCII encoded string \"Rosetta Code\" (without quotes). \nYou may either call an MD4 library, or implement MD4 in your language.\n\n'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.\n\nRFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.\n\n", "solution": "// version 1.0.6\n\nimport java.security.MessageDigest\n\nclass MD4() : MessageDigest(\"MD4\"), Cloneable {\n private val blockLength = 64\n private var context = IntArray(4)\n private var count = 0L\n private var buffer = ByteArray(blockLength)\n private var x = IntArray(16)\n \n init {\n engineReset()\n }\n\n private constructor(md: MD4): this() {\n context = md.context.clone()\n buffer = md.buffer.clone()\n count = md.count\n } \n\n override fun clone(): Any = MD4(this)\n\n override fun engineReset() {\n context[0] = 0x67452301\n context[1] = 0xefcdab89.toInt() \n context[2] = 0x98badcfe.toInt()\n context[3] = 0x10325476\n count = 0L\n for (i in 0 until blockLength) buffer[i] = 0\n }\n\n override fun engineUpdate(b: Byte) {\n val i = (count % blockLength).toInt()\n count++ \n buffer[i] = b\n if (i == blockLength - 1) transform(buffer, 0)\n }\n\n override fun engineUpdate(input: ByteArray, offset: Int, len: Int) {\n if (offset < 0 || len < 0 || offset.toLong() + len > input.size.toLong())\n throw ArrayIndexOutOfBoundsException()\n var bufferNdx = (count % blockLength).toInt()\n count += len \n val partLen = blockLength - bufferNdx\n var i = 0\n if (len >= partLen) {\n System.arraycopy(input, offset, buffer, bufferNdx, partLen)\n transform(buffer, 0)\n i = partLen\n while (i + blockLength - 1 < len) {\n transform(input, offset + i)\n i += blockLength\n }\n bufferNdx = 0\n }\n if (i < len) System.arraycopy(input, offset + i, buffer, bufferNdx, len - i)\n }\n\n override fun engineDigest(): ByteArray {\n val bufferNdx = (count % blockLength).toInt()\n val padLen = if (bufferNdx < 56) 56 - bufferNdx else 120 - bufferNdx\n val tail = ByteArray(padLen + 8)\n tail[0] = 0x80.toByte()\n for (i in 0..7) tail[padLen + i] = ((count * 8) ushr (8 * i)).toByte()\n engineUpdate(tail, 0, tail.size)\n val result = ByteArray(16)\n for (i in 0..3)\n for (j in 0..3)\n result[i * 4 + j] = (context[i] ushr (8 * j)).toByte()\n engineReset()\n return result\n }\n\n private fun transform (block: ByteArray, offset: Int) {\n var offset2 = offset\n for (i in 0..15) \n x[i] = ((block[offset2++].toInt() and 0xff) ) or\n ((block[offset2++].toInt() and 0xff) shl 8 ) or\n ((block[offset2++].toInt() and 0xff) shl 16) or\n ((block[offset2++].toInt() and 0xff) shl 24)\n\n var a = context[0]\n var b = context[1]\n var c = context[2]\n var d = context[3]\n\n a = ff(a, b, c, d, x[ 0], 3)\n d = ff(d, a, b, c, x[ 1], 7)\n c = ff(c, d, a, b, x[ 2], 11)\n b = ff(b, c, d, a, x[ 3], 19)\n a = ff(a, b, c, d, x[ 4], 3)\n d = ff(d, a, b, c, x[ 5], 7)\n c = ff(c, d, a, b, x[ 6], 11)\n b = ff(b, c, d, a, x[ 7], 19)\n a = ff(a, b, c, d, x[ 8], 3)\n d = ff(d, a, b, c, x[ 9], 7)\n c = ff(c, d, a, b, x[10], 11)\n b = ff(b, c, d, a, x[11], 19)\n a = ff(a, b, c, d, x[12], 3)\n d = ff(d, a, b, c, x[13], 7)\n c = ff(c, d, a, b, x[14], 11)\n b = ff(b, c, d, a, x[15], 19)\n\n a = gg(a, b, c, d, x[ 0], 3)\n d = gg(d, a, b, c, x[ 4], 5)\n c = gg(c, d, a, b, x[ 8], 9)\n b = gg(b, c, d, a, x[12], 13)\n a = gg(a, b, c, d, x[ 1], 3)\n d = gg(d, a, b, c, x[ 5], 5)\n c = gg(c, d, a, b, x[ 9], 9)\n b = gg(b, c, d, a, x[13], 13)\n a = gg(a, b, c, d, x[ 2], 3)\n d = gg(d, a, b, c, x[ 6], 5)\n c = gg(c, d, a, b, x[10], 9)\n b = gg(b, c, d, a, x[14], 13)\n a = gg(a, b, c, d, x[ 3], 3)\n d = gg(d, a, b, c, x[ 7], 5)\n c = gg(c, d, a, b, x[11], 9)\n b = gg(b, c, d, a, x[15], 13)\n\n a = hh(a, b, c, d, x[ 0], 3)\n d = hh(d, a, b, c, x[ 8], 9)\n c = hh(c, d, a, b, x[ 4], 11)\n b = hh(b, c, d, a, x[12], 15)\n a = hh(a, b, c, d, x[ 2], 3)\n d = hh(d, a, b, c, x[10], 9)\n c = hh(c, d, a, b, x[ 6], 11)\n b = hh(b, c, d, a, x[14], 15)\n a = hh(a, b, c, d, x[ 1], 3)\n d = hh(d, a, b, c, x[ 9], 9)\n c = hh(c, d, a, b, x[ 5], 11)\n b = hh(b, c, d, a, x[13], 15)\n a = hh(a, b, c, d, x[ 3], 3)\n d = hh(d, a, b, c, x[11], 9)\n c = hh(c, d, a, b, x[ 7], 11)\n b = hh(b, c, d, a, x[15], 15)\n\n context[0] += a\n context[1] += b\n context[2] += c\n context[3] += d\n }\n\n private fun ff(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {\n val t = a + ((b and c) or (b.inv() and d)) + x\n return (t shl s) or (t ushr (32 - s))\n }\n\n private fun gg(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {\n val t = a + ((b and (c or d)) or (c and d)) + x + 0x5a827999\n return (t shl s) or (t ushr (32 - s))\n }\n\n private fun hh(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {\n val t = a + (b xor c xor d) + x + 0x6ed9eba1 \n return (t shl s) or (t ushr (32 - s))\n }\n} \n\nfun main(args: Array) {\n val text = \"Rosetta Code\"\n val bytes = text.toByteArray(Charsets.US_ASCII)\n val md: MessageDigest = MD4()\n val digest = md.digest(bytes)\n for (byte in digest) print(\"%02x\".format(byte))\n println() \n}"} {"title": "Machine code", "language": "Kotlin from C", "task": "The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.\n\nFor example, the following assembly language program is given for x86 (32 bit) architectures:\n\nmov EAX, [ESP+4]\nadd EAX, [ESP+8]\nret\n\nThis would translate into the following opcode bytes:\n139 68 36 4 3 68 36 8 195\n\nOr in hexadecimal:\n8B 44 24 04 03 44 24 08 C3\n\n;Task:\nIf different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:\n\n* Poke the necessary opcodes into a memory location.\n* Provide a means to pass two values to the machine code.\n* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.\n* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)\n\n\n", "solution": "// Kotlin Native version 0.3\n\nimport kotlinx.cinterop.*\nimport string.*\nimport mman.*\nimport mcode.*\n\nfun main(args: Array) {\n memScoped { \n val bytes = byteArrayOf(\n 144 - 256, // Align\n 144 - 256,\n 106, 12, // Prepare stack\n 184 - 256, 7, 0, 0, 0, \n 72, 193 - 256, 224 - 256, 32,\n 80,\n 139 - 256, 68, 36, 4, 3, 68, 36, 8, // Rosetta task code\n 76, 137 - 256, 227 - 256, // Get result\n 137 - 256, 195 - 256,\n 72, 193 - 256, 227 - 256, 4,\n 128 - 256, 203 - 256, 2,\n 72, 131 - 256, 196 - 256, 16, // Clean up stack \n 195 - 256 // Return\n )\n val len = bytes.size \n val code = allocArray(len)\n for (i in 0 until len) code[i] = bytes[i]\n val buf = mmap(null, len.toLong(), PROT_READ or PROT_WRITE or PROT_EXEC,\n MAP_PRIVATE or MAP_ANON, -1, 0) \n memcpy(buf, code, len.toLong())\n val a: Byte = 7\n val b: Byte = 12\n val c = runMachineCode(buf, a, b)\n munmap(buf, len.toLong()) \n println(\"$a + $b = ${if(c >= 0) c.toInt() else c + 256}\")\n }\n}"} {"title": "Mad Libs", "language": "Kotlin", "task": "{{wikipedia}}\n\n\nMad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. \n\n\n;Task;\nWrite a program to create a Mad Libs like story. \n\nThe program should read an arbitrary multiline story from input.\n\nThe story will be terminated with a blank line. \n\nThen, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.\n\nStop when there are none left and print the final story.\n\n\nThe input should be an arbitrary story in the form:\n\n went for a walk in the park. \nfound a . decided to take it home.\n\nGiven this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).\n\n\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n println(\"Please enter a multi-line story template terminated by a blank line\\n\")\n val sb = StringBuilder()\n while (true) {\n val line = readLine()!!\n if (line.isEmpty()) break\n sb.append(\"$line\\n\") // preserve line breaks\n }\n var story = sb.toString()\n // identify blanks\n val r = Regex(\"<.*?>\")\n val blanks = r.findAll(story).map { it.value }.distinct()\n println(\"Please enter your replacements for the following 'blanks' in the story:\")\n for (blank in blanks) {\n print(\"${blank.drop(1).dropLast(1)} : \")\n val repl = readLine()!!\n story = story.replace(blank, repl)\n } \n println(\"\\n$story\")\n}"} {"title": "Magic 8-ball", "language": "Kotlin", "task": "Create Magic 8-Ball. \n\n\nSee details at: Magic 8-Ball.\n\n\n\n", "solution": "// Version 1.2.40\n\nimport java.util.Random\n\nfun main(args: Array) {\n val answers = listOf(\n \"It is certain\", \"It is decidedly so\", \"Without a doubt\",\n \"Yes, definitely\", \"You may rely on it\", \"As I see it, yes\",\n \"Most likely\", \"Outlook good\", \"Signs point to yes\", \"Yes\",\n \"Reply hazy, try again\", \"Ask again later\",\n \"Better not tell you now\", \"Cannot predict now\",\n \"Concentrate and ask again\", \"Don't bet on it\",\n \"My reply is no\", \"My sources say no\", \"Outlook not so good\",\n \"Very doubtful\"\n )\n val rand = Random()\n println(\"Please enter your question or a blank line to quit.\")\n while (true) {\n print(\"\\n? : \")\n val question = readLine()!!\n if (question.trim() == \"\") return\n val answer = answers[rand.nextInt(20)]\n println(\"\\n$answer\")\n }\n}"} {"title": "Magic squares of doubly even order", "language": "Kotlin from Java", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12'''). \n\nThis means that the subsquares also have an even size, which plays a role in the construction.\n\n \n{| class=\"wikitable\" style=\"float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%\"\n|-\n|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''\n|-\n|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''\n|-\n|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''\n|-\n|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''\n|-\n|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''\n|-\n|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''\n|-\n|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''\n|-\n|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''\n|}\n\n;Task\nCreate a magic square of '''8 x 8'''.\n\n\n;Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of singly even order]]\n\n\n;See also:\n* Doubly Even Magic Squares (1728.org)\n\n", "solution": "// version 1.1.0\n\nfun magicSquareDoublyEven(n: Int): Array {\n if ( n < 4 || n % 4 != 0) \n throw IllegalArgumentException(\"Base must be a positive multiple of 4\")\n\n // pattern of count-up vs count-down zones\n val bits = 0b1001_0110_0110_1001\n val size = n * n\n val mult = n / 4 // how many multiples of 4 \n val result = Array(n) { IntArray(n) }\n var i = 0\n for (r in 0 until n)\n for (c in 0 until n) {\n val bitPos = c / mult + r / mult * 4\n result[r][c] = if (bits and (1 shl bitPos) != 0) i + 1 else size - i\n i++\n }\n return result\n} \n\nfun main(args: Array) {\n val n = 8\n for (ia in magicSquareDoublyEven(n)) { \n for (i in ia) print(\"%2d \".format(i))\n println()\n }\n println(\"\\nMagic constant ${(n * n + 1) * n / 2}\")\n}"} {"title": "Magic squares of odd order", "language": "Kotlin from C", "task": "A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nThe numbers are usually (but not always) the first '''N'''2 positive integers.\n\nA magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.\n\n{| class=\"wikitable\" style=\"float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%\"\n|-\n| '''8''' || '''1''' || '''6'''\n|-\n| '''3''' || '''5''' || '''7'''\n|-\n| '''4''' || '''9''' || '''2'''\n|}\n\n\n;Task\nFor any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here. \n\nOptionally, show the ''magic number''. \n\nYou should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.\n\n\n; Related tasks\n* [[Magic squares of singly even order]]\n* [[Magic squares of doubly even order]]\n\n\n; See also:\n* MathWorld(tm) entry: Magic_square \n* Odd Magic Squares (1728.org)\n\n", "solution": "// version 1.0.6\n\nfun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n\n\nfun main(args: Array) {\n var n: Int\n while (true) {\n print(\"Enter the order of the magic square : \")\n n = readLine()!!.toInt()\n if (n < 1 || n % 2 == 0) println(\"Must be odd and >= 1, try again\")\n else break\n }\n println() \n for (i in 0 until n) {\n for (j in 0 until n) print(\"%4d\".format(f(n, n - j - 1, i) * n + f(n, j, i) + 1))\n println()\n }\n println(\"\\nThe magic constant is ${(n * n + 1) / 2 * n}\")\n}"} {"title": "Magic squares of singly even order", "language": "Kotlin from Java", "task": "A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant''). \n\nA magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.\n\n;Task\nCreate a magic square of 6 x 6.\n\n\n; Related tasks\n* [[Magic squares of odd order]]\n* [[Magic squares of doubly even order]]\n\n; See also\n* Singly Even Magic Squares (1728.org)\n\n", "solution": "// version 1.0.6\n\nfun magicSquareOdd(n: Int): Array {\n if (n < 3 || n % 2 == 0)\n throw IllegalArgumentException(\"Base must be odd and > 2\")\n\n var value = 0\n val gridSize = n * n\n var c = n / 2\n var r = 0\n val result = Array(n) { IntArray(n) }\n while (++value <= gridSize) {\n result[r][c] = value\n if (r == 0) {\n if (c == n - 1) r++\n else {\n r = n - 1\n c++\n }\n } \n else if (c == n - 1) {\n r--\n c = 0\n } \n else if (result[r - 1][c + 1] == 0) {\n r--\n c++\n } \n else r++\n }\n return result\n}\n \nfun magicSquareSinglyEven(n: Int): Array {\n if (n < 6 || (n - 2) % 4 != 0)\n throw IllegalArgumentException(\"Base must be a positive multiple of 4 plus 2\")\n \n val size = n * n\n val halfN = n / 2\n val subSquareSize = size / 4\n val subSquare = magicSquareOdd(halfN)\n val quadrantFactors = intArrayOf(0, 2, 3, 1)\n val result = Array(n) { IntArray(n) }\n for (r in 0 until n)\n for (c in 0 until n) {\n val quadrant = r / halfN * 2 + c / halfN\n result[r][c] = subSquare[r % halfN][c % halfN]\n result[r][c] += quadrantFactors[quadrant] * subSquareSize\n }\n val nColsLeft = halfN / 2\n val nColsRight = nColsLeft - 1\n for (r in 0 until halfN)\n for (c in 0 until n) \n if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) { \n if (c == 0 && r == nColsLeft) continue\n val tmp = result[r][c]\n result[r][c] = result[r + halfN][c]\n result[r + halfN][c] = tmp\n } \n return result\n}\n\nfun main(args: Array) {\n val n = 6\n for (ia in magicSquareSinglyEven(n)) { \n for (i in ia) print(\"%2d \".format(i))\n println()\n }\n println(\"\\nMagic constant ${(n * n + 1) * n / 2}\")\n}"} {"title": "Map range", "language": "Kotlin", "task": "Given two ranges: \n:::* [a_1,a_2] and \n:::* [b_1,b_2]; \n:::* then a value s in range [a_1,a_2]\n:::* is linearly mapped to a value t in range [b_1,b_2]\n where: \n\n\n:::* t = b_1 + {(s - a_1)(b_2 - b_1) \\over (a_2 - a_1)}\n\n\n;Task:\nWrite a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range. \n\nUse this function to map values from the range [0, 10] to the range [-1, 0]. \n\n\n;Extra credit:\nShow additional idiomatic ways of performing the mapping, using tools available to the language.\n\n", "solution": "// version 1.0.6\n\nclass FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange\n\nfun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float {\n if (value !in range1) throw IllegalArgumentException(\"value is not within the first range\")\n if (range1.endInclusive == range1.start) throw IllegalArgumentException(\"first range cannot be single-valued\")\n return range2.start + (value - range1.start) * (range2.endInclusive - range2.start) / (range1.endInclusive - range1.start)\n}\n \nfun main(args: Array) {\n for (i in 0..10) {\n val mappedValue = mapRange(FloatRange(0.0f, 10.0f), FloatRange(-1.0f, 0.0f), i.toFloat())\n println(String.format(\"%2d maps to %+4.2f\", i, mappedValue))\n }\n}"} {"title": "Maximum triangle path sum", "language": "Kotlin from C", "task": "Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n\n\nOne of such walks is 55 - 94 - 30 - 26. \nYou can compute the total of the numbers you have seen in such walk, \nin this case it's 205.\n\nYour problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.\n\n\n;Task:\nFind the maximum total in the triangle below:\n\n 55\n 94 48\n 95 30 96\n 77 71 26 67\n 97 13 76 38 45\n 07 36 79 16 37 68\n 48 07 09 18 70 26 06\n 18 72 79 46 59 79 29 90\n 20 76 87 11 32 07 07 49 18\n 27 83 58 35 71 11 25 57 29 85\n 14 64 36 96 27 11 58 56 92 18 55\n 02 90 03 60 48 49 41 46 33 36 47 23\n 92 50 48 02 36 59 42 79 72 20 82 77 42\n 56 78 38 80 39 75 02 71 66 66 01 03 55 72\n 44 25 67 84 71 67 11 61 40 57 58 89 40 56 36\n 85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52\n 06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15\n27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93\n\n\nSuch numbers can be included in the solution code, or read from a \"triangle.txt\" file.\n\nThis task is derived from the Euler Problem #18.\n\n", "solution": "// version 1.1.2\n\nval tri = intArrayOf(\n 55,\n 94, 48,\n 95, 30, 96,\n 77, 71, 26, 67,\n 97, 13, 76, 38, 45,\n 7, 36, 79, 16, 37, 68,\n 48, 7, 9, 18, 70, 26, 6,\n 18, 72, 79, 46, 59, 79, 29, 90,\n 20, 76, 87, 11, 32, 7, 7, 49, 18,\n 27, 83, 58, 35, 71, 11, 25, 57, 29, 85,\n 14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,\n 2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,\n 92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,\n 56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,\n 44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,\n 85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,\n 6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,\n 27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93\n)\n\nfun main(args: Array) {\n val triangles = arrayOf(tri.sliceArray(0..9), tri)\n for (triangle in triangles) {\n val size = triangle.size\n val base = ((Math.sqrt(8.0 * size + 1.0) - 1.0)/ 2.0).toInt()\n var step = base - 1\n var stepc = 0\n for (i in (size - base - 1) downTo 0) {\n triangle[i] += maxOf(triangle[i + step], triangle[i + step + 1])\n if (++stepc == step) {\n step--\n stepc = 0\n }\n }\n println(\"Maximum total = ${triangle[0]}\")\n }\n}"} {"title": "McNuggets problem", "language": "Kotlin from Go", "task": "From Wikipedia:\n The McNuggets version of the coin problem was introduced by Henri Picciotto,\n who included it in his algebra textbook co-authored with Anita Wah. Picciotto\n thought of the application in the 1980s while dining with his son at\n McDonald's, working the problem out on a napkin. A McNugget number is\n the total number of McDonald's Chicken McNuggets in any number of boxes.\n In the United Kingdom, the original boxes (prior to the introduction of\n the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.\n\n;Task:\nCalculate (from 0 up to a limit of 100) the largest non-McNuggets\nnumber (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''\nwhere ''x'', ''y'' and ''z'' are natural numbers).\n\n", "solution": "// Version 1.2.71\n\nfun mcnugget(limit: Int) {\n val sv = BooleanArray(limit + 1) // all false by default\n for (s in 0..limit step 6)\n for (n in s..limit step 9)\n for (t in n..limit step 20) sv[t] = true\n\n for (i in limit downTo 0) {\n if (!sv[i]) {\n println(\"Maximum non-McNuggets number is $i\")\n return\n }\n }\n}\n\nfun main(args: Array) {\n mcnugget(100)\n}"} {"title": "Memory layout of a data structure", "language": "Kotlin", "task": "It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.\n Pin Settings for Plug\n (Reverse order for socket.)\n __________________________________________\n 1 2 3 4 5 6 7 8 9 10 11 12 13\n 14 15 16 17 18 19 20 21 22 23 24 25\n _________________\n 1 2 3 4 5\n 6 7 8 9\n 25 pin 9 pin\n 1 - PG Protective ground\n 2 - TD Transmitted data 3\n 3 - RD Received data 2\n 4 - RTS Request to send 7\n 5 - CTS Clear to send 8\n 6 - DSR Data set ready 6\n 7 - SG Signal ground 5\n 8 - CD Carrier detect 1\n 9 - + voltage (testing)\n 10 - - voltage (testing)\n 11 -\n 12 - SCD Secondary CD\n 13 - SCS Secondary CTS\n 14 - STD Secondary TD\n 15 - TC Transmit clock\n 16 - SRD Secondary RD\n 17 - RC Receiver clock\n 18 -\n 19 - SRS Secondary RTS \n 20 - DTR Data terminal ready 4\n 21 - SQD Signal quality detector\n 22 - RI Ring indicator 9\n 23 - DRS Data rate select\n 24 - XTC External clock\n 25 -\n", "solution": "// version 1.0.6\n\nconst val OFF = false\nconst val ON = true\n\nfun toOnOff(b: Boolean) = if (b) \"ON\" else \"OFF\"\n\ndata class Rs232Pins9(\n var carrierDetect : Boolean = OFF,\n var receivedData : Boolean = OFF,\n var transmittedData : Boolean = OFF,\n var dataTerminalReady : Boolean = OFF,\n var signalGround : Boolean = OFF,\n var dataSetReady : Boolean = OFF,\n var requestToSend : Boolean = OFF,\n var clearToSend : Boolean = OFF,\n var ringIndicator : Boolean = OFF\n) {\n fun setPin(n: Int, v: Boolean) {\n when (n) {\n 1 -> carrierDetect = v\n 2 -> receivedData = v\n 3 -> transmittedData = v\n 4 -> dataTerminalReady = v\n 5 -> signalGround = v \n 6 -> dataSetReady = v\n 7 -> requestToSend = v\n 8 -> clearToSend = v\n 9 -> ringIndicator = v \n }\n }\n}\n\nfun main(args: Array) {\n val plug = Rs232Pins9(carrierDetect = ON, receivedData = ON) // set first two pins, say\n println(toOnOff(plug.component2())) // print value of pin 2 by number\n plug.transmittedData = ON // set pin 3 by name\n plug.setPin(4, ON) // set pin 4 by number\n println(toOnOff(plug.component3())) // print value of pin 3 by number\n println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name \n println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name\n}"} {"title": "Metallic ratios", "language": "Kotlin from Go", "task": "Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series\nof related ratios that are referred to as the \"'''Metallic ratios'''\".\n\nThe '''Golden ratio''' was discovered and named by ancient civilizations as it was\nthought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was\nalso known to the early Greeks, though was not named so until later as a nod to\nthe '''Golden ratio''' to which it is closely related. The series has been extended to\nencompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').\n''Somewhat incongruously as the original Golden ratio referred to the adjective \"golden\" rather than the metal \"gold\".''\n\n'''Metallic ratios''' are the real roots of the general form equation:\n\n x2 - bx - 1 = 0 \n\nwhere the integer '''b''' determines which specific one it is.\n\nUsing the quadratic equation:\n\n ( -b +- (b2 - 4ac) ) / 2a = x \n\nSubstitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:\n\n ( b +- (b2 + 4) ) ) / 2 = x \n\nWe only want the real root:\n\n ( b + (b2 + 4) ) ) / 2 = x \n\nWhen we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.\n\n ( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989... \n\nWith '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.\n\n ( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562... \n\nWhen the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''\nare sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as\nstandard. After that there isn't really any attempt at standardized names. They\nare given names here on this page, but consider the names fanciful rather than\ncanonical.\n\nNote that technically, '''b''' can be '''0''' for a \"smaller\" ratio than the '''Golden ratio'''.\nWe will refer to it here as the '''Platinum ratio''', though it is kind-of a\ndegenerate case.\n\n'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:\n\n [b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...] \n\n\nSo, The first ten '''Metallic ratios''' are:\n\n:::::: {| class=\"wikitable\" style=\"text-align: center;\"\n|+ Metallic ratios\n!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link\n|-\n|Platinum||0||(0 + 4) / 2|| 1||-||-\n|-\n|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]\n|-\n|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]\n|-\n|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]\n|-\n|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]\n|-\n|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]\n|-\n|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]\n|-\n|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]\n|-\n|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]\n|-\n|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]\n|}\n\n\n\n\nThere are other ways to find the '''Metallic ratios'''; one, (the focus of this task)\nis through '''successive approximations of Lucas sequences'''.\n\nA traditional '''Lucas sequence''' is of the form:\n\n x''n'' = P * x''n-1'' - Q * x''n-2''\n\nand starts with the first 2 values '''0, 1'''. \n\nFor our purposes in this task, to find the metallic ratios we'll use the form:\n\n x''n'' = b * x''n-1'' + x''n-2''\n\n( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid \"divide by zero\" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.'' \n\nAt any rate, when '''b = 1''' we get:\n\n x''n'' = x''n-1'' + x''n-2''\n\n 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...\n\nmore commonly known as the Fibonacci sequence.\n\nWhen '''b = 2''':\n\n x''n'' = 2 * x''n-1'' + x''n-2''\n\n 1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...\n\n\nAnd so on.\n\n\nTo find the ratio by successive approximations, divide the ('''n+1''')th term by the\n'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.\n\nFor '''b = 1''' (Fibonacci sequence):\n\n 1/1 = 1\n 2/1 = 2\n 3/2 = 1.5\n 5/3 = 1.666667\n 8/5 = 1.6\n 13/8 = 1.625\n 21/13 = 1.615385\n 34/21 = 1.619048\n 55/34 = 1.617647\n 89/55 = 1.618182\n etc.\n\nIt converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest\npossible convergence for any irrational number.\n\n\n;Task\n\nFor each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':\n\n* Generate the corresponding \"Lucas\" sequence.\n* Show here, on this page, at least the first '''15''' elements of the \"Lucas\" sequence.\n* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.\n* Show the '''value''' of the '''approximation''' at the required accuracy.\n* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).\n\nOptional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.\n\nYou may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.\n\n;See also\n* Wikipedia: Metallic mean\n* Wikipedia: Lucas sequence\n\n", "solution": "import java.math.BigDecimal\nimport java.math.BigInteger\n\nval names = listOf(\"Platinum\", \"Golden\", \"Silver\", \"Bronze\", \"Copper\", \"Nickel\", \"Aluminium\", \"Iron\", \"Tin\", \"Lead\")\n\nfun lucas(b: Long) {\n println(\"Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:\")\n print(\"First 15 elements: \")\n var x0 = 1L\n var x1 = 1L\n print(\"$x0, $x1\")\n for (i in 1..13) {\n val x2 = b * x1 + x0\n print(\", $x2\")\n x0 = x1\n x1 = x2\n }\n println()\n}\n\nfun metallic(b: Long, dp:Int) {\n var x0 = BigInteger.ONE\n var x1 = BigInteger.ONE\n var x2: BigInteger\n val bb = BigInteger.valueOf(b)\n val ratio = BigDecimal.ONE.setScale(dp)\n var iters = 0\n var prev = ratio.toString()\n while (true) {\n iters++\n x2 = bb * x1 + x0\n val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()\n if (prev == thiz) {\n var plural = \"s\"\n if (iters == 1) {\n plural = \"\"\n }\n println(\"Value after $iters iteration$plural: $thiz\\n\")\n return\n }\n prev = thiz\n x0 = x1\n x1 = x2\n }\n}\n\nfun main() {\n for (b in 0L until 10L) {\n lucas(b)\n metallic(b, 32)\n }\n println(\"Golden ration, where b = 1:\")\n metallic(1, 256)\n}"} {"title": "Metaprogramming", "language": "Kotlin", "task": "{{omit from|BBC BASIC}}\nName and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation. \n\nFor the purposes of this task, \"support for metaprogramming\" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.\n\n", "solution": "// version 1.0.6\n\ninfix fun Double.pwr(exp: Double) = Math.pow(this, exp)\n\nfun main(args: Array) {\n val d = 2.0 pwr 8.0\n println(d)\n}"} {"title": "Metronome", "language": "Kotlin", "task": "The task is to implement a metronome. \n\nThe metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.\n\nFor the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used. \n\nHowever, the playing of the sounds should not interfere with the timing of the metronome.\n\nThe visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities. \n\nIf the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.\n\n", "solution": "// version 1.1.2\n\nfun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) { \n val delay = 60_000L / bpm\n var beats = 0\n do {\n Thread.sleep(delay)\n if (beats % bpb == 0) print(\"\\nTICK \")\n else print(\"tick \")\n beats++ \n }\n while (beats < maxBeats)\n println()\n}\n\nfun main(args: Array) = metronome(120, 4, 20) // limit to 20 beats "} {"title": "Mian-Chowla sequence", "language": "Kotlin", "task": "The Mian-Chowla sequence is an integer sequence defined recursively.\n\n\nMian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.\n\n\nThe sequence starts with:\n\n::a1 = 1\n\nthen for n > 1, an is the smallest positive integer such that every pairwise sum\n\n::ai + aj \n\nis distinct, for all i and j less than or equal to n.\n\n;The Task:\n\n:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.\n:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.\n\n\nDemonstrating working through the first few terms longhand:\n\n::a1 = 1\n\n::1 + 1 = 2\n\nSpeculatively try a2 = 2\n\n::1 + 1 = 2\n::1 + 2 = 3\n::2 + 2 = 4\n\nThere are no repeated sums so '''2''' is the next number in the sequence.\n\nSpeculatively try a3 = 3\n\n::1 + 1 = 2\n::1 + 2 = 3 \n::1 + 3 = 4\n::2 + 2 = 4\n::2 + 3 = 5\n::3 + 3 = 6\n\nSum of '''4''' is repeated so '''3''' is rejected.\n\nSpeculatively try a3 = 4\n\n::1 + 1 = 2\n::1 + 2 = 3\n::1 + 4 = 5\n::2 + 2 = 4\n::2 + 4 = 6\n::4 + 4 = 8\n\nThere are no repeated sums so '''4''' is the next number in the sequence.\n\nAnd so on...\n\n;See also:\n\n:* OEIS:A005282 Mian-Chowla sequence\n\n", "solution": "// Version 1.3.21\n\nfun mianChowla(n: Int): List {\n val mc = MutableList(n) { 0 }\n mc[0] = 1\n val hs = HashSet(n * (n + 1) / 2)\n hs.add(2)\n val hsx = mutableListOf()\n for (i in 1 until n) {\n hsx.clear()\n var j = mc[i - 1]\n outer@ while (true) {\n j++\n mc[i] = j\n for (k in 0..i) {\n val sum = mc[k] + j\n if (hs.contains(sum)) {\n hsx.clear()\n continue@outer\n }\n hsx.add(sum)\n }\n hs.addAll(hsx)\n break\n }\n }\n return mc\n}\n\nfun main() {\n val mc = mianChowla(100)\n println(\"The first 30 terms of the Mian-Chowla sequence are:\")\n println(mc.subList(0, 30))\n println(\"\\nTerms 91 to 100 of the Mian-Chowla sequence are:\")\n println(mc.subList(90, 100))\n}"} {"title": "Middle three digits", "language": "Kotlin", "task": "Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.\n\nNote: The order of the middle digits should be preserved.\n\nYour function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:\n\n123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345\n1, 2, -1, -10, 2002, -2002, 0\n\nShow your output on this page.\n\n", "solution": "fun middleThree(x: Int): Int? {\n val s = Math.abs(x).toString()\n return when {\n s.length < 3 -> null // throw Exception(\"too short!\")\n s.length % 2 == 0 -> null // throw Exception(\"even number of digits\")\n else -> ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt()\n }\n}\n\nfun main(args: Array) {\n println(middleThree(12345)) // 234\n println(middleThree(1234)) // null\n println(middleThree(1234567)) // 345\n println(middleThree(123))// 123\n println(middleThree(123555)) //null\n}"} {"title": "Mind boggling card trick", "language": "Kotlin from Go", "task": "Matt Parker of the \"Stand Up Maths channel\" has a YouTube video of a card trick that creates a semblance of order from chaos.\n\nThe task is to simulate the trick in a way that mimics the steps shown in the video.\n\n; 1. Cards.\n# Create a common deck of cards of 52 cards (which are half red, half black).\n# Give the pack a good shuffle.\n; 2. Deal from the shuffled deck, you'll be creating three piles.\n# Assemble the cards face down.\n## Turn up the ''top card'' and hold it in your hand. \n### if the card is black, then add the ''next'' card (unseen) to the \"black\" pile. \n### If the card is red, then add the ''next'' card (unseen) to the \"red\" pile.\n## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).\n# Repeat the above for the rest of the shuffled deck.\n; 3. Choose a random number (call it '''X''') that will be used to swap cards from the \"red\" and \"black\" piles.\n# Randomly choose '''X''' cards from the \"red\" pile (unseen), let's call this the \"red\" bunch. \n# Randomly choose '''X''' cards from the \"black\" pile (unseen), let's call this the \"black\" bunch.\n# Put the \"red\" bunch into the \"black\" pile.\n# Put the \"black\" bunch into the \"red\" pile.\n# (The above two steps complete the swap of '''X''' cards of the \"red\" and \"black\" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).\n; 4. Order from randomness?\n# Verify (or not) the mathematician's assertion that: \n '''The number of black cards in the \"black\" pile equals the number of red cards in the \"red\" pile.''' \n\n\n(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)\n\nShow output on this page.\n\n", "solution": "// Version 1.2.61\n\nimport java.util.Random\n\nfun main(args: Array) {\n // Create pack, half red, half black and shuffle it.\n val pack = MutableList(52) { if (it < 26) 'R' else 'B' }\n pack.shuffle()\n\n // Deal from pack into 3 stacks.\n val red = mutableListOf()\n val black = mutableListOf()\n val discard = mutableListOf()\n for (i in 0 until 52 step 2) {\n when (pack[i]) {\n 'B' -> black.add(pack[i + 1])\n 'R' -> red.add(pack[i + 1])\n }\n discard.add(pack[i])\n }\n val sr = red.size\n val sb = black.size\n val sd = discard.size\n println(\"After dealing the cards the state of the stacks is:\")\n System.out.printf(\" Red : %2d cards -> %s\\n\", sr, red)\n System.out.printf(\" Black : %2d cards -> %s\\n\", sb, black)\n System.out.printf(\" Discard: %2d cards -> %s\\n\", sd, discard)\n\n // Swap the same, random, number of cards between the red and black stacks.\n val rand = Random()\n val min = minOf(sr, sb)\n val n = 1 + rand.nextInt(min)\n var rp = MutableList(sr) { it }.shuffled().subList(0, n)\n var bp = MutableList(sb) { it }.shuffled().subList(0, n)\n println(\"\\n$n card(s) are to be swapped\\n\")\n println(\"The respective zero-based indices of the cards(s) to be swapped are:\")\n println(\" Red : $rp\")\n println(\" Black : $bp\")\n for (i in 0 until n) {\n val temp = red[rp[i]]\n red[rp[i]] = black[bp[i]]\n black[bp[i]] = temp\n }\n println(\"\\nAfter swapping, the state of the red and black stacks is:\")\n println(\" Red : $red\")\n println(\" Black : $black\")\n\n // Check that the number of black cards in the black stack equals\n // the number of red cards in the red stack.\n var rcount = 0\n var bcount = 0\n for (c in red) if (c == 'R') rcount++\n for (c in black) if (c == 'B') bcount++\n println(\"\\nThe number of red cards in the red stack = $rcount\")\n println(\"The number of black cards in the black stack = $bcount\")\n if (rcount == bcount) {\n println(\"So the asssertion is correct!\")\n }\n else {\n println(\"So the asssertion is incorrect!\")\n }\n}"} {"title": "Minimum positive multiple in base 10 using only 0 and 1", "language": "Kotlin from Java", "task": "Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.\n\nThis is simple to do, but can be challenging to do efficiently.\n\nTo avoid repeating long, unwieldy phrases, the operation \"minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1\" will hereafter be referred to as \"'''B10'''\".\n\n;Task:\n\nWrite a routine to find the B10 of a given integer. \n\nE.G. \n \n '''n''' '''B10''' '''n''' x '''multiplier'''\n 1 1 ( 1 x 1 )\n 2 10 ( 2 x 5 )\n 7 1001 ( 7 x 143 )\n 9 111111111 ( 9 x 12345679 )\n 10 10 ( 10 x 1 )\n\nand so on.\n\nUse the routine to find and display here, on this page, the '''B10''' value for: \n\n 1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999\n\nOptionally find '''B10''' for:\n\n 1998, 2079, 2251, 2277\n\nStretch goal; find '''B10''' for:\n\n 2439, 2997, 4878\n\nThere are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.\n\n\n;See also:\n\n:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.\n:* How to find Minimum Positive Multiple in base 10 using only 0 and 1\n\n", "solution": "import java.math.BigInteger\n\nfun main() {\n for (n in testCases) {\n val result = getA004290(n)\n println(\"A004290($n) = $result = $n * ${result / n.toBigInteger()}\")\n }\n}\n\nprivate val testCases: List\n get() {\n val testCases: MutableList = ArrayList()\n for (i in 1..10) {\n testCases.add(i)\n }\n for (i in 95..105) {\n testCases.add(i)\n }\n for (i in intArrayOf(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) {\n testCases.add(i)\n }\n return testCases\n }\n\nprivate fun getA004290(n: Int): BigInteger {\n if (n == 1) {\n return BigInteger.ONE\n }\n val arr = Array(n) { IntArray(n) }\n for (i in 2 until n) {\n arr[0][i] = 0\n }\n arr[0][0] = 1\n arr[0][1] = 1\n var m = 0\n val ten = BigInteger.TEN\n val nBi = n.toBigInteger()\n while (true) {\n m++\n if (arr[m - 1][mod(-ten.pow(m), nBi).toInt()] == 1) {\n break\n }\n arr[m][0] = 1\n for (k in 1 until n) {\n arr[m][k] = arr[m - 1][k].coerceAtLeast(arr[m - 1][mod(k.toBigInteger() - ten.pow(m), nBi).toInt()])\n }\n }\n var r = ten.pow(m)\n var k = mod(-r, nBi)\n for (j in m - 1 downTo 1) {\n if (arr[j - 1][k.toInt()] == 0) {\n r += ten.pow(j)\n k = mod(k - ten.pow(j), nBi)\n }\n }\n if (k.compareTo(BigInteger.ONE) == 0) {\n r += BigInteger.ONE\n }\n return r\n}\n\nprivate fun mod(m: BigInteger, n: BigInteger): BigInteger {\n var result = m.mod(n)\n if (result < BigInteger.ZERO) {\n result += n\n }\n return result\n}"} {"title": "Modular arithmetic", "language": "Kotlin", "task": "equivalence relation called ''congruence''. \n\nFor any positive integer p called the ''congruence modulus'', \ntwo numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:\n:a = b + k\\,p\n\nThe corresponding set of multiplicative inverse for this task.\n\nAddition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.\n\nThe purpose of this task is to show, if your programming language allows it, \nhow to redefine operators so that they can be used transparently on modular integers. \nYou can do it either by using a dedicated library, or by implementing your own class.\n\nYou will use the following function for demonstration:\n:f(x) = x^{100} + x + 1\nYou will use 13 as the congruence modulus and you will compute f(10).\n\nIt is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers. \nIn other words, the function is an algebraic expression that could be used with any ring, not just integers.\n\n", "solution": "// version 1.1.3\n\ninterface Ring {\n operator fun plus(other: Ring): Ring\n operator fun times(other: Ring): Ring\n val value: Int\n val one: Ring\n}\n\nfun Ring.pow(p: Int): Ring {\n require(p >= 0)\n var pp = p\n var pwr = this.one\n while (pp-- > 0) pwr *= this\n return pwr\n}\n\nclass ModInt(override val value: Int, val modulo: Int): Ring {\n \n override operator fun plus(other: Ring): ModInt {\n require(other is ModInt && modulo == other.modulo)\n return ModInt((value + other.value) % modulo, modulo)\n }\n \n override operator fun times(other: Ring): ModInt {\n require(other is ModInt && modulo == other.modulo)\n return ModInt((value * other.value) % modulo, modulo)\n }\n\n override val one get() = ModInt(1, modulo)\n\n override fun toString() = \"ModInt($value, $modulo)\"\n}\n\nfun f(x: Ring): Ring = x.pow(100) + x + x.one\n\nfun main(args: Array) {\n val x = ModInt(10, 13)\n val y = f(x)\n println(\"x ^ 100 + x + 1 for x == ModInt(10, 13) is $y\")\n}"} {"title": "Modular exponentiation", "language": "Kotlin", "task": "Find the last '''40''' decimal digits of a^b, where\n\n::* a = 2988348162058574136915891421498819466320163312926952423791023078876139\n::* b = 2351399303373464486466122544523690094744975233415544072992656881240319\n\n\nA computer is too slow to find the entire value of a^b. \n\nInstead, the program must use a fast algorithm for modular exponentiation: a^b \\mod m.\n\nThe algorithm must work for any integers a, b, m, where b \\ge 0 and m > 0.\n\n", "solution": "// version 1.0.6\n\nimport java.math.BigInteger\n\nfun main(args: Array) {\n val a = BigInteger(\"2988348162058574136915891421498819466320163312926952423791023078876139\")\n val b = BigInteger(\"2351399303373464486466122544523690094744975233415544072992656881240319\")\n val m = BigInteger.TEN.pow(40)\n println(a.modPow(b, m))\n}"} {"title": "Modular inverse", "language": "Kotlin", "task": "From Wikipedia:\n\nIn modulo ''m'' is an integer ''x'' such that\n\n::a\\,x \\equiv 1 \\pmod{m}.\n\nOr in other words, such that:\n\n::\\exists k \\in\\Z,\\qquad a\\, x = 1 + k\\,m\n\nIt can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.\n\n\n;Task:\nEither by implementing the algorithm, by using a dedicated library or by using a built-in function in \nyour language, compute the modular inverse of 42 modulo 2017.\n\n", "solution": "// version 1.0.6\n\nimport java.math.BigInteger\n\nfun main(args: Array) {\n val a = BigInteger.valueOf(42)\n val m = BigInteger.valueOf(2017)\n println(a.modInverse(m))\n}"} {"title": "Monads/List monad", "language": "Kotlin", "task": "A Monad is a combination of a data-type with two helper functions written for that type. \n\nThe data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.\n\nThe bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.\n\nA sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. \n\nThe natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.\n\n\nDemonstrate in your programming language the following:\n\n#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String\n#Compose the two functions with bind\n\n", "solution": "// version 1.2.10\n\nclass MList private constructor(val value: List) {\n fun bind(f: (List) -> MList) = f(this.value)\n\n companion object {\n fun unit(lt: List) = MList(lt)\n }\n}\n\nfun doubler(li: List) = MList.unit(li.map { 2 * it } )\n\nfun letters(li: List) = MList.unit(li.map { \"${('@' + it)}\".repeat(it) } )\n\nfun main(args: Array) {\n val iv = MList.unit(listOf(2, 3, 4))\n val fv = iv.bind(::doubler).bind(::letters)\n println(fv.value)\n}"} {"title": "Monads/Maybe monad", "language": "Kotlin", "task": "Demonstrate in your programming language the following:\n\n#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)\n#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String\n#Compose the two functions with bind\n\n\nA Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.\n\nA Maybe Monad is a monad which specifically encapsulates the type of an undefined value.\n\n", "solution": "// version 1.2.10\n\nimport java.util.Optional\n\n/* doubles 'i' before wrapping it */\nfun getOptionalInt(i: Int) = Optional.of(2 * i)\n\n/* returns an 'A' repeated 'i' times wrapped in an Optional */\nfun getOptionalString(i: Int) = Optional.of(\"A\".repeat(i))\n\n/* does same as above if i > 0, otherwise returns an empty Optional */\nfun getOptionalString2(i: Int) =\n Optional.ofNullable(if (i > 0) \"A\".repeat(i) else null)\n\nfun main(args: Array) {\n /* prints 10 'A's */\n println(getOptionalInt(5).flatMap(::getOptionalString).get())\n\n /* prints 4 'A's */\n println(getOptionalInt(2).flatMap(::getOptionalString2).get())\n\n /* prints 'false' as there is no value present in the Optional instance */\n println(getOptionalInt(0).flatMap(::getOptionalString2).isPresent)\n}"} {"title": "Monads/Writer monad", "language": "Kotlin", "task": "The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.\n\nDemonstrate in your programming language the following:\n\n# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)\n# Write three simple functions: root, addOne, and half\n# Derive Writer monad versions of each of these functions\n# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)\n\n", "solution": "// version 1.2.10\n\nimport kotlin.math.sqrt\n\nclass Writer private constructor(val value: T, s: String) {\n var log = \" ${s.padEnd(17)}: $value\\n\"\n private set\n\n fun bind(f: (T) -> Writer): Writer {\n val new = f(this.value)\n new.log = this.log + new.log\n return new\n }\n\n companion object {\n fun unit(t: T, s: String) = Writer(t, s)\n }\n}\n\nfun root(d: Double) = Writer.unit(sqrt(d), \"Took square root\")\n\nfun addOne(d: Double) = Writer.unit(d + 1.0, \"Added one\")\n\nfun half(d: Double) = Writer.unit(d / 2.0, \"Divided by two\")\n\nfun main(args: Array) {\n val iv = Writer.unit(5.0, \"Initial value\")\n val fv = iv.bind(::root).bind(::addOne).bind(::half)\n println(\"The Golden Ratio is ${fv.value}\")\n println(\"\\nThis was derived as follows:-\\n${fv.log}\")\n}"} {"title": "Move-to-front algorithm", "language": "Kotlin", "task": "Given a symbol table of a ''zero-indexed'' array of all possible input symbols\nthis algorithm reversibly transforms a sequence\nof input symbols into an array of output numbers (indices).\n\nThe transform in many cases acts to give frequently repeated input symbols\nlower indices which is useful in some compression algorithms.\n\n\n;Encoding algorithm:\n\n for each symbol of the input sequence:\n output the index of the symbol in the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Decoding algorithm:\n\n # Using the same starting symbol table\n for each index of the input sequence:\n output the symbol at that index of the symbol table\n move that symbol to the front of the symbol table\n\n\n\n;Example:\nEncoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''\n\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''b'''roood\n| 1\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| b'''r'''oood\n| 1 17\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| br'''o'''ood\n| 1 17 15\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| bro'''o'''od\n| 1 17 15 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| broo'''o'''d\n| 1 17 15 0 0\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| brooo'''d'''\n| 1 17 15 0 0 5\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\nDecoding the indices back to the original symbol order:\n:::::{| class=\"wikitable\" border=\"1\"\n|-\n! Input\n! Output\n! SymbolTable\n|-\n| '''1''' 17 15 0 0 5\n| b\n| 'abcdefghijklmnopqrstuvwxyz'\n|-\n| 1 '''17''' 15 0 0 5\n| br\n| 'bacdefghijklmnopqrstuvwxyz'\n|-\n| 1 17 '''15''' 0 0 5\n| bro\n| 'rbacdefghijklmnopqstuvwxyz'\n|-\n| 1 17 15 '''0''' 0 5\n| broo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 '''0''' 5\n| brooo\n| 'orbacdefghijklmnpqstuvwxyz'\n|-\n| 1 17 15 0 0 '''5''' \n| broood\n| 'orbacdefghijklmnpqstuvwxyz'\n|}\n\n\n;Task:\n:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above. \n:* Show the strings and their encoding here.\n:* Add a check to ensure that the decoded string is the same as the original.\n\n\nThe strings are: \n\n broood \n bananaaa \n hiphophiphop \n(Note the misspellings in the above strings.)\n\n", "solution": "// version 1.1.2\n\nfun encode(s: String): IntArray {\n if (s.isEmpty()) return intArrayOf()\n val symbols = \"abcdefghijklmnopqrstuvwxyz\".toCharArray()\n val result = IntArray(s.length)\n for ((i, c) in s.withIndex()) {\n val index = symbols.indexOf(c)\n if (index == -1) \n throw IllegalArgumentException(\"$s contains a non-alphabetic character\")\n result[i] = index\n if (index == 0) continue\n for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j]\n symbols[0] = c\n }\n return result\n}\n\nfun decode(a: IntArray): String {\n if (a.isEmpty()) return \"\"\n val symbols = \"abcdefghijklmnopqrstuvwxyz\".toCharArray()\n val result = CharArray(a.size)\n for ((i, n) in a.withIndex()) {\n if (n !in 0..25)\n throw IllegalArgumentException(\"${a.contentToString()} contains an invalid number\")\n result[i] = symbols[n]\n if (n == 0) continue\n for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j]\n symbols[0] = result[i]\n }\n return result.joinToString(\"\")\n} \n \nfun main(args: Array) { \n val strings = arrayOf(\"broood\", \"bananaaa\", \"hiphophiphop\")\n val encoded = Array(strings.size) { null }\n for ((i, s) in strings.withIndex()) {\n encoded[i] = encode(s)\n println(\"${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}\")\n }\n println()\n val decoded = Array(encoded.size) { null }\n for ((i, a) in encoded.withIndex()) {\n decoded[i] = decode(a!!)\n print(\"${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}\")\n println(\" -> ${if (decoded[i] == strings[i]) \"correct\" else \"incorrect\"}\")\n }\n}"} {"title": "Multi-dimensional array", "language": "Kotlin", "task": "For the purposes of this task, the actual memory layout or access method of this data structure is not mandated. \n\nIt is enough to:\n# State the number and extent of each index to the array.\n# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.\n# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.\n\n\n;Task:\n* State if the language supports multi-dimensional arrays in its syntax and usual implementation.\n* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.\n* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.\n:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).\n* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.\n* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.\n\n\nShow all output here, (but you may judiciously use ellipses to shorten repetitive output text).\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n // create a regular 4 dimensional array and initialize successive elements to the values 1 to 120\n var m = 1\n val a4 = Array>>>(5) {\n Array>>(4) {\n Array>(3) {\n Array(2) { m++ }\n }\n }\n }\n\n println(\"First element = ${a4[0][0][0][0]}\") // access and print value of first element\n a4[0][0][0][0] = 121 // change value of first element\n println()\n\n // access and print values of all elements\n val f = \"%4d\"\n for (i in 0..4)\n for (j in 0..3)\n for (k in 0..2)\n for (l in 0..1)\n print(f.format(a4[i][j][k][l]))\n\n}"} {"title": "Multifactorial", "language": "Kotlin", "task": "The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).\n\nMultifactorials generalize factorials as follows:\n: n! = n(n-1)(n-2)...(2)(1)\n: n!! = n(n-2)(n-4)...\n: n!! ! = n(n-3)(n-6)...\n: n!! !! = n(n-4)(n-8)...\n: n!! !! ! = n(n-5)(n-10)...\n\nIn all cases, the terms in the products are positive integers.\n\nIf we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold: \n# Write a function that given n and the degree, calculates the multifactorial.\n# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.\n\n\n'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.\n\n", "solution": "fun multifactorial(n: Long, d: Int) : Long {\n val r = n % d\n return (1..n).filter { it % d == r } .reduce { i, p -> i * p }\n}\n\nfun main(args: Array) {\n val m = 5\n val r = 1..10L\n for (d in 1..m) {\n print(\"%${m}s:\".format( \"!\".repeat(d)))\n r.forEach { print(\" \" + multifactorial(it, d)) }\n println()\n }\n}"} {"title": "Multiple distinct objects", "language": "Kotlin", "task": "Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.\n\nBy ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.\n\nBy ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to \"zero\" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of \"zero\" for that type.\n\nThis task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.\n\nThis task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).\n\nSee also: [[Closures/Value capture]]\n\n", "solution": "// version 1.1.2\n\nclass Foo {\n val id: Int\n\n init {\n id = ++numCreated // creates a distict id for each object\n }\n\n companion object {\n private var numCreated = 0\n }\n}\n\nfun main(args: Array) {\n val n = 3 // say\n\n /* correct approach - creates references to distinct objects */\n val fooList = List(n) { Foo() }\n for (foo in fooList) println(foo.id)\n\n /* incorrect approach - creates references to same object */\n val f = Foo()\n val fooList2 = List(n) { f }\n for (foo in fooList2) println(foo.id)\n}"} {"title": "Multisplit", "language": "Kotlin", "task": "It is often necessary to split a string into pieces \nbased on several different (potentially multi-character) separator strings, \nwhile still retaining the information about which separators were present in the input. \n\nThis is particularly useful when doing small parsing tasks. \nThe task is to write code to demonstrate this.\n\nThe function (or procedure or method, as appropriate) should \ntake an input string and an ordered collection of separators. \n\nThe order of the separators is significant: \nThe delimiter order represents priority in matching, with the first defined delimiter having the highest priority. \nIn cases where there would be an ambiguity as to \nwhich separator to use at a particular point \n(e.g., because one separator is a prefix of another) \nthe separator with the highest priority should be used. \nDelimiters can be reused and the output from the function should be an ordered sequence of substrings.\n\nTest your code using the input string \"a!===b=!=c\" and the separators \"==\", \"!=\" and \"=\".\n\nFor these inputs the string should be parsed as \"a\" (!=) \"\" (==) \"b\" (=) \"\" (!=) \"c\", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is \"a\", empty string, \"b\", empty string, \"c\". \nNote that the quotation marks are shown for clarity and do not form part of the output.\n\n'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.\n\n", "solution": "// version 1.0.6\n\nfun main(args: Array) {\n val input = \"a!===b=!=c\"\n val delimiters = arrayOf(\"==\", \"!=\", \"=\")\n val output = input.split(*delimiters).toMutableList()\n for (i in 0 until output.size) {\n if (output[i].isEmpty()) output[i] = \"empty string\"\n else output[i] = \"\\\"\" + output[i] + \"\\\"\"\n }\n println(\"The splits are:\") \n println(output)\n\n // now find positions of matched delimiters\n val matches = mutableListOf>()\n var index = 0 \n while (index < input.length) {\n var matched = false\n for (d in delimiters) {\n if (input.drop(index).take(d.length) == d) {\n matches.add(d to index)\n index += d.length\n matched = true\n break\n }\n }\n if (!matched) index++\n }\n println(\"\\nThe delimiters matched and the indices at which they occur are:\")\n println(matches)\n}"} {"title": "Munchausen numbers", "language": "Kotlin", "task": "A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.\n\n('''Munchausen''' is also spelled: '''Munchhausen'''.) \n\nFor instance: 3435 = 33 + 44 + 33 + 55 \n\n\n;Task\nFind all Munchausen numbers between '''1''' and '''5000'''.\n\n\n;Also see:\n:* The OEIS entry: A046253\n:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''\n\n", "solution": "// version 1.0.6\n\nval powers = IntArray(10)\n\nfun isMunchausen(n: Int): Boolean {\n if (n < 0) return false\n var sum = 0L\n var nn = n\n while (nn > 0) {\n sum += powers[nn % 10]\n if (sum > n.toLong()) return false\n nn /= 10\n }\n return sum == n.toLong() \n}\n\nfun main(args: Array) {\n // cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose\n for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt()\n\n // check numbers 0 to 500 million\n println(\"The Munchausen numbers between 0 and 500 million are:\")\n for (i in 0..500000000) if (isMunchausen(i))print (\"$i \")\n println()\n}"} {"title": "Musical scale", "language": "Kotlin", "task": "Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.\n\nThese are the notes \"C, D, E, F, G, A, B, C(1 octave higher)\", or \"Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)\" on Fixed do Solfege.\n\nFor the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.\n\nFor languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.\n\n", "solution": "// Kotlin Native v0.3\n\nimport kotlinx.cinterop.*\nimport win32.*\n\nfun main(args: Array) {\n val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523) // CDEFGABc\n val dur = 500\n repeat(5) { for (freq in freqs) Beep(freq, dur) } \n}"} {"title": "N-queens problem", "language": "Kotlin from FreeBASIC", "task": "right\n\nSolve the eight queens puzzle. \n\n\nYou can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.\n \nFor the number of solutions for small values of '''N''', see OEIS: A000170.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[Peaceful chess queen armies]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// version 1.1.3\n\nvar count = 0\nvar c = IntArray(0)\nvar f = \"\" \n\nfun nQueens(row: Int, n: Int) {\n outer@ for (x in 1..n) {\n for (y in 1..row - 1) {\n if (c[y] == x) continue@outer\n if (row - y == Math.abs(x - c[y])) continue@outer \n }\n c[row] = x\n if (row < n) nQueens(row + 1, n)\n else if (++count == 1) f = c.drop(1).map { it - 1 }.toString()\n }\n}\n\nfun main(args: Array) {\n for (n in 1..14) { \n count = 0\n c = IntArray(n + 1)\n f = \"\"\n nQueens(1, n)\n println(\"For a $n x $n board:\")\n println(\" Solutions = $count\")\n if (count > 0) println(\" First is $f\")\n println()\n }\n}"} {"title": "Narcissist", "language": "Kotlin", "task": "Quoting from the Esolangs wiki page:\n\n\nA '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].\n\nA quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a \"1\" or \"accept\" if that string matches its own source code, or a \"0\" or \"reject\" if it does not.\n\n\nFor concreteness, in this task we shall assume that symbol = character. \n\nThe narcissist should be able to cope with any finite input, whatever its length. \n\nAny form of output is allowed, as long as the program always halts, and \"accept\", \"reject\" and \"not yet finished\" are distinguishable.\n\n", "solution": "// version 1.1.0 (run on Windows 10)\n\nfun main(args: Array) {\n val text = java.io.File(\"narcissist.kt\").readText()\n println(\"Enter the number of lines to be input followed by those lines:\\n\")\n val n = readLine()!!.toInt()\n val lines = Array(n) { readLine()!! }\n if (lines.joinToString(\"\\r\\n\") == text) println(\"\\naccept\") else println(\"\\nreject\")\n}"} {"title": "Narcissistic decimal number", "language": "Kotlin", "task": "A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.\n\n\nNarcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong. \nThey are also known as '''Plus Perfect''' numbers.\n\n\n;An example:\n::::* if n is '''153''' \n::::* then m, (the number of decimal digits) is '''3''' \n::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153''' \n::::* and so '''153''' is a narcissistic decimal number\n\n\n;Task:\nGenerate and show here the first '''25''' narcissistic decimal numbers.\n\n\n\nNote: 0^1 = 0, the first in the series. \n\n\n;See also:\n* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.\n* MathWorld entry: Narcissistic Number.\n* Wikipedia entry: Narcissistic number.\n\n", "solution": "// version 1.1.0\n\nfun isNarcissistic(n: Int): Boolean {\n if (n < 0) throw IllegalArgumentException(\"Argument must be non-negative\")\n var nn = n\n val digits = mutableListOf()\n val powers = IntArray(10) { 1 } \n while (nn > 0) {\n digits.add(nn % 10)\n for (i in 1..9) powers[i] *= i // no need to calculate powers[0]\n nn /= 10\n }\n val sum = digits.filter { it > 0 }.map { powers[it] }.sum()\n return n == sum\n}\n\nfun main(args: Array) {\n println(\"The first 25 narcissistic (or Armstrong) numbers are:\")\n var i = 0\n var count = 0\n do {\n if (isNarcissistic(i)) {\n print(\"$i \")\n count++\n }\n i++\n }\n while (count < 25) \n}"} {"title": "Nautical bell", "language": "Kotlin from Java", "task": "Task\n\nWrite a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.\n\nThe bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.\n\nIt is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice \"Two Bells Gone\"), if these are more usual for the system type. \n\n\n;Related task:\n* [[Sleep]]\n\n", "solution": "// version 1.1.3\n\nimport java.text.DateFormat\nimport java.text.SimpleDateFormat\nimport java.util.TimeZone\n\nclass NauticalBell: Thread() {\n\n override fun run() {\n val sdf = SimpleDateFormat(\"HH:mm:ss\")\n sdf.timeZone = TimeZone.getTimeZone(\"UTC\")\n var numBells = 0\n var time = System.currentTimeMillis()\n var next = time - (time % (24 * 60 * 60 * 1000)) // midnight\n\n while (next < time) {\n next += 30 * 60 * 1000 // 30 minutes\n numBells = 1 + (numBells % 8)\n }\n\n while (true) {\n var wait = 100L\n time = System.currentTimeMillis()\n if ((time - next) >= 0) {\n val bells = if (numBells == 1) \"bell\" else \"bells\"\n val timeString = sdf.format(time)\n println(\"%s : %d %s\".format(timeString, numBells, bells))\n next += 30 * 60 * 1000\n wait = next - time\n numBells = 1 + (numBells % 8)\n }\n try {\n Thread.sleep(wait)\n }\n catch (ie: InterruptedException) {\n return\n }\n }\n }\n}\n\nfun main(args: Array) {\n val bells = NauticalBell()\n with (bells) {\n setDaemon(true)\n start()\n try {\n join()\n }\n catch (ie: InterruptedException) {\n println(ie.message)\n }\n }\n}"} {"title": "Negative base numbers", "language": "Kotlin", "task": "Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia\n\n\n;Task:\n\n*Encode the decimal number 10 as negabinary (expect 11110)\n*Encode the decimal number 146 as negaternary (expect 21102)\n*Encode the decimal number 15 as negadecimal (expect 195)\n*In each of the above cases, convert the encoded number back to decimal.\n\n\n;extra credit:\n\n* supply an integer, that when encoded to base -62 (or something \"higher\"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.\n\n", "solution": "// version 1.1.2\n\nconst val DIGITS = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"\n\nfun encodeNegBase(n: Long, b: Int): String {\n require(b in -62 .. -1)\n if (n == 0L) return \"0\"\n val out = mutableListOf()\n var nn = n\n while (nn != 0L) {\n var rem = (nn % b).toInt()\n nn /= b\n if (rem < 0) {\n nn++\n rem -= b\n }\n out.add(DIGITS[rem])\n }\n out.reverse()\n return out.joinToString(\"\")\n}\n\nfun decodeNegBase(ns: String, b: Int): Long {\n require(b in -62 .. -1)\n if (ns == \"0\") return 0\n var total = 0L\n var bb = 1L\n for (c in ns.reversed()) {\n total += DIGITS.indexOf(c) * bb\n bb *= b\n }\n return total\n} \n\nfun main(args:Array) {\n val nbl = listOf(10L to -2, 146L to -3, 15L to -10, -17596769891 to -62)\n for (p in nbl) {\n val ns = encodeNegBase(p.first, p.second)\n System.out.printf(\"%12d encoded in base %-3d = %s\\n\", p.first, p.second, ns)\n val n = decodeNegBase(ns, p.second)\n System.out.printf(\"%12s decoded in base %-3d = %d\\n\\n\", ns, p.second, n)\n }\n}"} {"title": "Nested function", "language": "Kotlin", "task": "In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.\n\n\n;Task: \nWrite a program consisting of two nested functions that prints the following text.\n\n 1. first\n 2. second\n 3. third\n\nThe outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator \". \" as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.\n\nThe inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.\n\n\n;References:\n:* Nested function\n\n", "solution": "// version 1.0.6\n\nfun makeList(sep: String): String {\n var count = 0\n fun makeItem(item: String): String {\n count++\n return \"$count$sep$item\\n\"\n } \n return makeItem(\"first\") + makeItem(\"second\") + makeItem(\"third\")\n}\n\nfun main(args: Array) {\n print(makeList(\". \"))\n}"} {"title": "Next highest int from digits", "language": "Kotlin from Java", "task": "Given a zero or positive integer, the task is to generate the next largest\ninteger using only the given digits*1.\n\n* Numbers will not be padded to the left with zeroes.\n* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).\n* If there is no next highest integer return zero.\n\n\n:*1 Alternatively phrased as: \"Find the smallest integer larger than the (positive or zero) integer '''N''' \n:: which can be obtained by reordering the (base ten) digits of '''N'''\".\n\n\n;Algorithm 1:\n# Generate all the permutations of the digits and sort into numeric order.\n# Find the number in the list.\n# Return the next highest number from the list.\n\n\nThe above could prove slow and memory hungry for numbers with large numbers of\ndigits, but should be easy to reason about its correctness.\n\n\n;Algorithm 2:\n# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.\n# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.\n# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)\n\n\n'''E.g.:'''\n\n n = 12453\n\n 12_4_53\n\n 12_5_43\n\n 12_5_34\n\n return: 12534\n\n\nThis second algorithm is faster and more memory efficient, but implementations\nmay be harder to test. \n\nOne method of testing, (as used in developing the task), is to compare results from both\nalgorithms for random numbers generated from a range that the first algorithm can handle.\n\n\n;Task requirements:\nCalculate the next highest int from the digits of the following numbers:\n:* 0\n:* 9\n:* 12\n:* 21\n:* 12453\n:* 738440\n:* 45072010\n:* 95322020\n\n\n;Optional stretch goal:\n:* 9589776899767587796600\n\n", "solution": "import java.math.BigInteger\nimport java.text.NumberFormat\n\nfun main() {\n for (s in arrayOf(\n \"0\",\n \"9\",\n \"12\",\n \"21\",\n \"12453\",\n \"738440\",\n \"45072010\",\n \"95322020\",\n \"9589776899767587796600\",\n \"3345333\"\n )) {\n println(\"${format(s)} -> ${format(next(s))}\")\n }\n testAll(\"12345\")\n testAll(\"11122\")\n}\n\nprivate val FORMAT = NumberFormat.getNumberInstance()\nprivate fun format(s: String): String {\n return FORMAT.format(BigInteger(s))\n}\n\nprivate fun testAll(str: String) {\n var s = str\n println(\"Test all permutations of: $s\")\n val sOrig = s\n var sPrev = s\n var count = 1\n\n // Check permutation order. Each is greater than the last\n var orderOk = true\n val uniqueMap: MutableMap = HashMap()\n uniqueMap[s] = 1\n while (next(s).also { s = it }.compareTo(\"0\") != 0) {\n count++\n if (s.toLong() < sPrev.toLong()) {\n orderOk = false\n }\n uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n sPrev = s\n }\n println(\" Order: OK = $orderOk\")\n\n // Test last permutation\n val reverse = StringBuilder(sOrig).reverse().toString()\n println(\" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}\")\n\n // Check permutations unique\n var unique = true\n for (key in uniqueMap.keys) {\n if (uniqueMap[key]!! > 1) {\n unique = false\n }\n }\n println(\" Permutations unique: OK = $unique\")\n\n // Check expected count.\n val charMap: MutableMap = HashMap()\n for (c in sOrig.toCharArray()) {\n charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }\n }\n var permCount = factorial(sOrig.length.toLong())\n for (c in charMap.keys) {\n permCount /= factorial(charMap[c]!!.toLong())\n }\n println(\" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}\")\n}\n\nprivate fun factorial(n: Long): Long {\n var fact: Long = 1\n for (num in 2..n) {\n fact *= num\n }\n return fact\n}\n\nprivate fun next(s: String): String {\n val sb = StringBuilder()\n var index = s.length - 1\n // Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.\n while (index > 0 && s[index - 1] >= s[index]) {\n index--\n }\n // Reached beginning. No next number.\n if (index == 0) {\n return \"0\"\n }\n\n // Find digit on the right that is both more than it, and closest to it.\n var index2 = index\n for (i in index + 1 until s.length) {\n if (s[i] < s[index2] && s[i] > s[index - 1]) {\n index2 = i\n }\n }\n\n // Found data, now build string\n // Beginning of String\n if (index > 1) {\n sb.append(s.subSequence(0, index - 1))\n }\n\n // Append found, place next\n sb.append(s[index2])\n\n // Get remaining characters\n val chars: MutableList = ArrayList()\n chars.add(s[index - 1])\n for (i in index until s.length) {\n if (i != index2) {\n chars.add(s[i])\n }\n }\n\n // Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.\n chars.sort()\n for (c in chars) {\n sb.append(c)\n }\n return sb.toString()\n}"} {"title": "Nim game", "language": "Kotlin from Go", "task": "Nim is a simple game where the second player-if they know the trick-will always win.\n\n\nThe game has only 3 rules:\n::* start with '''12''' tokens\n::* each player takes '''1, 2, or 3''' tokens in turn\n::* the player who takes the last token wins.\n\n\nTo win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1. \n\n;Task:\nDesign a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.\n\n", "solution": "// Version 1.3.21\n\nfun showTokens(tokens: Int) {\n println(\"Tokens remaining $tokens\\n\")\n}\n\nfun main() {\n var tokens = 12\n while (true) {\n showTokens(tokens)\n print(\" How many tokens 1, 2 or 3? \")\n var t = readLine()!!.toIntOrNull()\n if (t == null || t < 1 || t > 3) {\n println(\"\\nMust be a number between 1 and 3, try again.\\n\")\n } else {\n var ct = 4 - t\n var s = if (ct > 1) \"s\" else \"\"\n println(\" Computer takes $ct token$s\\n\")\n tokens -= 4\n }\n if (tokens == 0) {\n showTokens(0)\n println(\" Computer wins!\")\n return\n }\n }\n}"} {"title": "Non-transitive dice", "language": "Kotlin from Go", "task": "Let our dice select numbers on their faces with equal probability, i.e. fair dice.\nDice may have more or less than six faces. (The possibility of there being a \n3D physical shape that has that many \"faces\" that allow them to be fair dice,\nis ignored for this task - a die with 3 or 33 defined sides is defined by the \nnumber of faces and the numbers on each face).\n\nThrowing dice will randomly select a face on each die with equal probability.\nTo show which die of dice thrown multiple times is more likely to win over the \nothers:\n# calculate all possible combinations of different faces from each die\n# Count how many times each die wins a combination\n# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.\n\n\n'''If two dice X and Y are thrown against each other then X likely to: win, lose, or break-even against Y can be shown as: X > Y, X < Y, or X = Y respectively.\n'''\n;Example 1:\nIf X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its\nfaces then the equal possibility outcomes from throwing both, and the winners \nis:\n \n X Y Winner\n = = ======\n 1 2 Y\n 1 3 Y\n 1 4 Y\n 3 2 X\n 3 3 -\n 3 4 Y\n 6 2 X\n 6 3 X\n 6 4 X\n \n TOTAL WINS: X=4, Y=4\n\nBoth die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y\n\n;Transitivity:\nIn mathematics transitivity are rules like: \n if a op b and b op c then a op c\nIf, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers\nwe get the familiar if a < b and b < c then a < c\n\n;Non-transitive dice\nThese are an ordered list of dice where the '>' operation between successive \ndice pairs applies but a comparison between the first and last of the list\nyields the opposite result, '<'.\n''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''\n\n\nThree dice S, T, U with appropriate face values could satisfy\n\n S < T, T < U and yet S > U\n\nTo be non-transitive.\n\n;Notes:\n\n* The order of numbers on the faces of a die is not relevant. For example, three faced die described with face numbers of 1, 2, 3 or 2, 1, 3 or any other permutation are equivalent. For the purposes of the task '''show only the permutation in lowest-first sorted order i.e. 1, 2, 3''' (and remove any of its perms).\n* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4\n* '''Rotations''': Any rotation of non-transitive dice from an answer is also an answer. You may ''optionally'' compute and show only one of each such rotation sets, ideally the first when sorted in a natural way. If this option is used then prominently state in the output that rotations of results are also solutions.\n\n\n;Task:\n;====\nFind all the ordered lists of ''three'' non-transitive dice S, T, U of the form \nS < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''\n, (unique w.r.t the notes), possible by having selections from the integers \n''one to four'' on any dies face.\n\nSolution can be found by generating all possble individual die then testing all\npossible permutations, (permutations are ordered), of three dice for \nnon-transitivity.\n\n;Optional stretch goal:\nFind lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.\n\n\nShow the results here, on this page.\n\n;References:\n* The Most Powerful Dice - Numberphile Video.\n* Nontransitive dice - Wikipedia.\n\n", "solution": "fun fourFaceCombos(): List> {\n val res = mutableListOf>()\n val found = mutableSetOf()\n for (i in 1..4) {\n for (j in 1..4) {\n for (k in 1..4) {\n for (l in 1..4) {\n val c = arrayOf(i, j, k, l)\n c.sort()\n val key = 64 * (c[0] - 1) + 16 * (c[1] - 1) + 4 * (c[2] - 1) + (c[3] - 1)\n if (!found.contains(key)) {\n found.add(key)\n res.add(c)\n }\n }\n }\n }\n }\n return res\n}\n\nfun cmp(x: Array, y: Array): Int {\n var xw = 0\n var yw = 0\n for (i in 0 until 4) {\n for (j in 0 until 4) {\n if (x[i] > y[j]) {\n xw++\n } else if (y[j] > x[i]) {\n yw++\n }\n }\n }\n if (xw < yw) {\n return -1\n }\n if (xw > yw) {\n return 1\n }\n return 0\n}\n\nfun findIntransitive3(cs: List>): List>> {\n val c = cs.size\n val res = mutableListOf>>()\n\n for (i in 0 until c) {\n for (j in 0 until c) {\n if (cmp(cs[i], cs[j]) == -1) {\n for (k in 0 until c) {\n if (cmp(cs[j], cs[k]) == -1 && cmp(cs[k], cs[i]) == -1) {\n res.add(arrayOf(cs[i], cs[j], cs[k]))\n }\n }\n }\n }\n }\n\n return res\n}\n\nfun findIntransitive4(cs: List>): List>> {\n val c = cs.size\n val res = mutableListOf>>()\n\n for (i in 0 until c) {\n for (j in 0 until c) {\n if (cmp(cs[i], cs[j]) == -1) {\n for (k in 0 until c) {\n if (cmp(cs[j], cs[k]) == -1) {\n for (l in 0 until c) {\n if (cmp(cs[k], cs[l]) == -1 && cmp(cs[l], cs[i]) == -1) {\n res.add(arrayOf(cs[i], cs[j], cs[k], cs[l]))\n }\n }\n }\n }\n }\n }\n }\n\n return res\n}\n\nfun main() {\n val combos = fourFaceCombos()\n println(\"Number of eligible 4-faced dice: ${combos.size}\")\n println()\n\n val it3 = findIntransitive3(combos)\n println(\"${it3.size} ordered lists of 3 non-transitive dice found, namely:\")\n for (a in it3) {\n println(a.joinToString(\", \", \"[\", \"]\") { it.joinToString(\", \", \"[\", \"]\") })\n }\n println()\n\n val it4 = findIntransitive4(combos)\n println(\"${it4.size} ordered lists of 4 non-transitive dice found, namely:\")\n for (a in it4) {\n println(a.joinToString(\", \", \"[\", \"]\") { it.joinToString(\", \", \"[\", \"]\") })\n }\n}"} {"title": "Nonoblock", "language": "Kotlin from Java", "task": "Nonogram puzzle.\n\n\n;Given:\n* The number of cells in a row.\n* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.\n\n\n;Task: \n* show all possible positions. \n* show the number of positions of the blocks for the following cases within the row. \n* show all output on this page. \n* use a \"neat\" diagram of the block positions.\n\n\n;Enumerate the following configurations:\n# '''5''' cells and '''[2, 1]''' blocks\n# '''5''' cells and '''[]''' blocks (no blocks)\n# '''10''' cells and '''[8]''' blocks\n# '''15''' cells and '''[2, 3, 2, 3]''' blocks\n# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)\n\n\n;Example:\nGiven a row of five cells and a block of two cells followed by a block of one cell - in that order, the example could be shown as:\n\n |_|_|_|_|_| # 5 cells and [2, 1] blocks\n\nAnd would expand to the following 3 possible rows of block positions:\n\n |A|A|_|B|_|\n |A|A|_|_|B|\n |_|A|A|_|B|\n\n\nNote how the sets of blocks are always separated by a space.\n\nNote also that it is not necessary for each block to have a separate letter. \nOutput approximating\n\nThis:\n |#|#|_|#|_|\n |#|#|_|_|#|\n |_|#|#|_|#|\n\nThis would also work:\n ##.#.\n ##..#\n .##.#\n\n\n;An algorithm:\n* Find the minimum space to the right that is needed to legally hold all but the leftmost block of cells (with a space between blocks remember).\n* The leftmost cell can legitimately be placed in all positions from the LHS up to a RH position that allows enough room for the rest of the blocks.\n* for each position of the LH block recursively compute the position of the rest of the blocks in the ''remaining'' space to the right of the current placement of the LH block.\n\n(This is the algorithm used in the [[Nonoblock#Python]] solution). \n\n\n;Reference:\n* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.\n\n", "solution": "// version 1.2.0\n\nfun printBlock(data: String, len: Int) {\n val a = data.toCharArray()\n val sumChars = a.map { it.toInt() - 48 }.sum()\n println(\"\\nblocks ${a.asList()}, cells $len\")\n if (len - sumChars <= 0) {\n println(\"No solution\")\n return\n }\n val prep = a.map { \"1\".repeat(it.toInt() - 48) }\n for (r in genSequence(prep, len - sumChars + 1)) println(r.substring(1))\n}\n\nfun genSequence(ones: List, numZeros: Int): List {\n if (ones.isEmpty()) return listOf(\"0\".repeat(numZeros))\n val result = mutableListOf()\n for (x in 1 until numZeros - ones.size + 2) {\n val skipOne = ones.drop(1)\n for (tail in genSequence(skipOne, numZeros - x)) {\n result.add(\"0\".repeat(x) + ones[0] + tail)\n }\n }\n return result\n}\n\nfun main(args: Array) {\n printBlock(\"21\", 5)\n printBlock(\"\", 5)\n printBlock(\"8\", 10)\n printBlock(\"2323\", 15)\n printBlock(\"23\", 5)\n}"} {"title": "Nonogram solver", "language": "Kotlin from Java", "task": "nonogram is a puzzle that provides \nnumeric clues used to fill in a grid of cells, \nestablishing for each cell whether it is filled or not. \nThe puzzle solution is typically a picture of some kind.\n\nEach row and column of a rectangular grid is annotated with the lengths \nof its distinct runs of occupied cells. \nUsing only these lengths you should find one valid configuration \nof empty and occupied cells, or show a failure message.\n\n;Example\nProblem: Solution:\n\n. . . . . . . . 3 . # # # . . . . 3\n. . . . . . . . 2 1 # # . # . . . . 2 1\n. . . . . . . . 3 2 . # # # . . # # 3 2\n. . . . . . . . 2 2 . . # # . . # # 2 2\n. . . . . . . . 6 . . # # # # # # 6\n. . . . . . . . 1 5 # . # # # # # . 1 5\n. . . . . . . . 6 # # # # # # . . 6\n. . . . . . . . 1 . . . . # . . . 1\n. . . . . . . . 2 . . . # # . . . 2\n1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3\n2 1 5 1 2 1 5 1 \nThe problem above could be represented by two lists of lists:\nx = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]\ny = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]\nA more compact representation of the same problem uses strings, \nwhere the letters represent the numbers, A=1, B=2, etc:\nx = \"C BA CB BB F AE F A B\"\ny = \"AB CA AE GA E C D C\"\n\n;Task\nFor this task, try to solve the 4 problems below, read from a \"nonogram_problems.txt\" file that has this content \n(the blank lines are separators):\nC BA CB BB F AE F A B\nAB CA AE GA E C D C\n\nF CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\nD D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\n\nCA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\nBC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC\n\nE BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\nE CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\n\n'''Extra credit''': generate nonograms with unique solutions, of desired height and width.\n\nThis task is the problem n.98 of the \"99 Prolog Problems\" by Werner Hett (also thanks to Paul Singleton for the idea and the examples).\n\n; Related tasks\n* [[Nonoblock]].\n\n;See also\n* Arc Consistency Algorithm\n* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)\n* http://twanvl.nl/blog/haskell/Nonograms (Haskell)\n* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)\n\n", "solution": "// version 1.2.0\n\nimport java.util.BitSet\n\ntypealias BitSets = List>\n\nval rx = Regex(\"\"\"\\s\"\"\")\n\nfun newPuzzle(data: List) {\n val rowData = data[0].split(rx)\n val colData = data[1].split(rx)\n val rows = getCandidates(rowData, colData.size)\n val cols = getCandidates(colData, rowData.size)\n\n do {\n val numChanged = reduceMutual(cols, rows)\n if (numChanged == -1) {\n println(\"No solution\")\n return\n }\n }\n while (numChanged > 0)\n\n for (row in rows) {\n for (i in 0 until cols.size) {\n print(if (row[0][i]) \"# \" else \". \")\n }\n println()\n }\n println()\n}\n\n// collect all possible solutions for the given clues\nfun getCandidates(data: List, len: Int): BitSets {\n val result = mutableListOf>()\n for (s in data) {\n val lst = mutableListOf()\n val a = s.toCharArray()\n val sumChars = a.sumBy { it - 'A' + 1 }\n val prep = a.map { \"1\".repeat(it - 'A' + 1) }\n\n for (r in genSequence(prep, len - sumChars + 1)) {\n val bits = r.substring(1).toCharArray()\n val bitset = BitSet(bits.size)\n for (i in 0 until bits.size) bitset[i] = bits[i] == '1'\n lst.add(bitset)\n }\n result.add(lst)\n }\n return result\n}\n\nfun genSequence(ones: List, numZeros: Int): List {\n if (ones.isEmpty()) return listOf(\"0\".repeat(numZeros))\n val result = mutableListOf()\n for (x in 1 until numZeros - ones.size + 2) {\n val skipOne = ones.drop(1)\n for (tail in genSequence(skipOne, numZeros - x)) {\n result.add(\"0\".repeat(x) + ones[0] + tail)\n }\n }\n return result\n}\n\n/* If all the candidates for a row have a value in common for a certain cell,\n then it's the only possible outcome, and all the candidates from the\n corresponding column need to have that value for that cell too. The ones\n that don't, are removed. The same for all columns. It goes back and forth,\n until no more candidates can be removed or a list is empty (failure).\n*/\n\nfun reduceMutual(cols: BitSets, rows: BitSets): Int {\n val countRemoved1 = reduce(cols, rows)\n if (countRemoved1 == -1) return -1\n val countRemoved2 = reduce(rows, cols)\n if (countRemoved2 == -1) return -1\n return countRemoved1 + countRemoved2\n}\n\nfun reduce(a: BitSets, b: BitSets): Int {\n var countRemoved = 0\n for (i in 0 until a.size) {\n val commonOn = BitSet()\n commonOn[0] = b.size\n val commonOff = BitSet()\n\n // determine which values all candidates of a[i] have in common\n for (candidate in a[i]) {\n commonOn.and(candidate)\n commonOff.or(candidate)\n }\n\n // remove from b[j] all candidates that don't share the forced values\n for (j in 0 until b.size) {\n val fi = i\n val fj = j\n if (b[j].removeIf { cnd ->\n (commonOn[fj] && !cnd[fi]) ||\n (!commonOff[fj] && cnd[fi]) }) countRemoved++\n if (b[j].isEmpty()) return -1\n }\n }\n return countRemoved\n}\n\nval p1 = listOf(\"C BA CB BB F AE F A B\", \"AB CA AE GA E C D C\")\n\nval p2 = listOf(\n \"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC\",\n \"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA\"\n)\n\nval p3 = listOf(\n \"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH \" +\n \"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC\",\n \"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF \" +\n \"AAAAD BDG CEF CBDB BBB FC\"\n)\n\nval p4 = listOf(\n \"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G\",\n \"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ \" +\n \"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM\"\n)\n\nfun main(args: Array) {\n for (puzzleData in listOf(p1, p2, p3, p4)) {\n newPuzzle(puzzleData)\n }\n}"} {"title": "Numeric error propagation", "language": "Kotlin from Java", "task": "If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant; \nthen if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways, \nthen sf can be calculated as follows:\n\n:;Addition/Subtraction\n:* If f = a +- c, or f = c +- a then '''sf = sa'''\n:* If f = a +- b then '''sf2 = sa2 + sb2'''\n\n:;Multiplication/Division\n:* If f = ca or f = ac then '''sf = |csa|'''\n:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''\n\n:;Exponentiation\n:* If f = ac then '''sf = |fc(sa / a)|'''\n\n\nCaution:\n::This implementation of error propagation does not address issues of dependent and independent values. It is assumed that '''a''' and '''b''' are independent and so the formula for multiplication should not be applied to '''a*a''' for example. See the talk page for some of the implications of this issue.\n\n\n;Task details:\n# Add an uncertain number type to your language that can support addition, subtraction, multiplication, division, and exponentiation between numbers with an associated error term together with 'normal' floating point numbers without an associated error term. Implement enough functionality to perform the following calculations.\n# Given coordinates and their errors:x1 = 100 +- 1.1y1 = 50 +- 1.2x2 = 200 +- 2.2y2 = 100 +- 2.3 if point p1 is located at (x1, y1) and p2 is at (x2, y2); calculate the distance between the two points using the classic Pythagorean formula: d = (x1 - x2)2 + (y1 - y2)2 \n# Print and display both '''d''' and its error.\n\n \n\n;References:\n* A Guide to Error Propagation B. Keeney, 2005.\n* Propagation of uncertainty Wikipedia.\n\n\n;Related task:\n* [[Quaternion type]]\n\n", "solution": "import java.lang.Math.*\n\ndata class Approx(val \u03bd: Double, val \u03c3: Double = 0.0) {\n constructor(a: Approx) : this(a.\u03bd, a.\u03c3)\n constructor(n: Number) : this(n.toDouble(), 0.0)\n\n override fun toString() = \"$\u03bd \u00b1$\u03c3\"\n\n operator infix fun plus(a: Approx) = Approx(\u03bd + a.\u03bd, sqrt(\u03c3 * \u03c3 + a.\u03c3 * a.\u03c3))\n operator infix fun plus(d: Double) = Approx(\u03bd + d, \u03c3)\n operator infix fun minus(a: Approx) = Approx(\u03bd - a.\u03bd, sqrt(\u03c3 * \u03c3 + a.\u03c3 * a.\u03c3))\n operator infix fun minus(d: Double) = Approx(\u03bd - d, \u03c3)\n\n operator infix fun times(a: Approx): Approx {\n val v = \u03bd * a.\u03bd\n return Approx(v, sqrt(v * v * \u03c3 * \u03c3 / (\u03bd * \u03bd) + a.\u03c3 * a.\u03c3 / (a.\u03bd * a.\u03bd)))\n }\n\n operator infix fun times(d: Double) = Approx(\u03bd * d, abs(d * \u03c3))\n\n operator infix fun div(a: Approx): Approx {\n val v = \u03bd / a.\u03bd\n return Approx(v, sqrt(v * v * \u03c3 * \u03c3 / (\u03bd * \u03bd) + a.\u03c3 * a.\u03c3 / (a.\u03bd * a.\u03bd)))\n }\n\n operator infix fun div(d: Double) = Approx(\u03bd / d, abs(d * \u03c3))\n\n fun pow(d: Double): Approx {\n val v = pow(\u03bd, d)\n return Approx(v, abs(v * d * \u03c3 / \u03bd))\n }\n}\n\nfun main(args: Array) {\n val x1 = Approx(100.0, 1.1)\n val y1 = Approx(50.0, 1.2)\n val x2 = Approx(200.0, 2.2)\n val y2 = Approx(100.0, 2.3)\n println(((x1 - x2).pow(2.0) + (y1 - y2).pow(2.0)).pow(0.5))\n}"} {"title": "Odd word problem", "language": "Kotlin from C", "task": "Write a program that solves the odd word problem with the restrictions given below.\n\n\n;Description:\nYou are promised an input stream consisting of English letters and punctuations. \n\nIt is guaranteed that:\n* the words (sequence of consecutive letters) are delimited by one and only one punctuation,\n* the stream will begin with a word,\n* the words will be at least one letter long, and \n* a full stop (a period, [.]) appears after, and only after, the last word.\n\n\n;Example:\nA stream with six words: \n:: what,is,the;meaning,of:life. \n\n\nThe task is to reverse the letters in every other word while leaving punctuations intact, producing:\n:: what,si,the;gninaem,of:efil. \nwhile observing the following restrictions:\n# Only I/O allowed is reading or writing one character at a time, which means: no reading in a string, no peeking ahead, no pushing characters back into the stream, and no storing characters in a global variable for later use;\n# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;\n# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.\n\n\n;Test cases:\nWork on both the \"life\" example given above, and also the text:\n:: we,are;not,in,kansas;any,more.\n\n", "solution": "// version 1.1.3\n\ntypealias Func = () -> Unit\n\nfun doChar(odd: Boolean, f: Func?): Boolean {\n val c = System.`in`.read()\n if (c == -1) return false // end of stream reached\n val ch = c.toChar()\n\n fun writeOut() {\n print(ch)\n if (f != null) f()\n }\n\n if (!odd) print(ch)\n if (ch.isLetter()) return doChar(odd, ::writeOut)\n if (odd) {\n if (f != null) f()\n print(ch)\n } \n return ch != '.'\n}\n\nfun main(args: Array) {\n repeat(2) {\n var b = true\n while (doChar(!b, null)) b = !b\n System.`in`.read() // remove '\\n' from buffer\n println(\"\\n\") \n }\n}"} {"title": "Old Russian measure of length", "language": "Kotlin from FreeBASIC", "task": "Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).\n\n\nIt is an example of a linear transformation of several variables. \n\n\nThe program should accept a single value in a selected unit of measurement, and convert and return it to the other units: \n''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.\n\n\n;Also see:\n:* Old Russian measure of length\n\n", "solution": "// version 1.0.6\n\n/* clears console on Windows 10 */\nfun cls() = ProcessBuilder(\"cmd\", \"/c\", \"cls\").inheritIO().start().waitFor()\n\nfun main(args: Array) {\n val units = listOf(\"tochka\", \"liniya\", \"dyuim\", \"vershok\", \"piad\", \"fut\",\n \"arshin\", \"sazhen\", \"versta\", \"milia\",\n \"centimeter\", \"meter\", \"kilometer\")\n val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f, \n 71.12f, 213.36f, 10668.0f, 74676.0f, \n 1.0f, 100.0f, 10000.0f)\n var unit: Int\n var value: Float\n var yn : String\n do {\n cls()\n println()\n for (i in 0 until units.size) println(\"${\"%2d\".format(i + 1)} ${units[i]}\")\n println()\n do {\n print(\"Please choose a unit 1 to 13 : \")\n unit = try { readLine()!!.toInt() } catch (e: NumberFormatException) { 0 }\n }\n while (unit !in 1..13)\n unit--\n do {\n print(\"Now enter a value in that unit : \")\n value = try { readLine()!!.toFloat() } catch (e: NumberFormatException) { -1.0f }\n }\n while (value < 0.0f)\n println(\"\\nThe equivalent in the remaining units is:\\n\")\n for (i in 0 until units.size) {\n if (i == unit) continue \n println(\" ${units[i].padEnd(10)} : ${value * convs[unit] / convs[i]}\")\n }\n println()\n do {\n print(\"Do another one y/n : \")\n yn = readLine()!!.toLowerCase()\n }\n while (yn != \"y\" && yn != \"n\") \n }\n while (yn == \"y\")\n}"} {"title": "Old lady swallowed a fly", "language": "Kotlin", "task": "Present a program which emits the lyrics to the song ''I Knew an Old Lady Who Swallowed a Fly'', taking advantage of the repetitive structure of the song's lyrics. \n\nThis song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.\n\n\n\n", "solution": "// version 1.1.3\n\nval animals = listOf(\"fly\", \"spider\", \"bird\", \"cat\",\"dog\", \"goat\", \"cow\", \"horse\")\n\nval phrases = listOf(\n \"\",\n \"That wriggled and jiggled and tickled inside her\",\n \"How absurd to swallow a bird\",\n \"Fancy that to swallow a cat\",\n \"What a hog, to swallow a dog\",\n \"She just opened her throat and swallowed a goat\",\n \"I don't know how she swallowed a cow\",\n \"\\n ...She's dead of course\"\n)\n\nfun sing() {\n for (i in 0..7) {\n println(\"There was an old lady who swallowed a ${animals[i]};\")\n if (i > 0) println(\"${phrases[i]}!\")\n if (i == 7) return\n println() \n if (i > 0) {\n for (j in i downTo 1) {\n print(\" She swallowed the ${animals[j]} to catch the ${animals[j - 1]}\")\n println(if (j < 3) \";\" else \",\")\n if (j == 2) println(\" ${phrases[1]}!\") \n }\n }\n println(\" I don't know why she swallowed a fly - Perhaps she'll die!\\n\")\n }\n} \n\nfun main(args: Array) {\n sing()\n}"} {"title": "One-time pad", "language": "Kotlin", "task": "One-time pad, for encrypting and decrypting messages.\nTo keep it simple, we will be using letters only.\n\n;Sub-Tasks:\n* '''Generate''' the data for a One-time pad (user needs to specify a filename and length)\n: The important part is to get \"true random\" numbers, e.g. from /dev/random\n* '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] )\n: For this step, much of [[Vigenere cipher]] could be reused,with the key to be read from the file containing the One-time pad.\n* optional: '''management''' of One-time pads: list, mark as used, delete, etc.\n: Somehow, the users needs to keep track which pad to use for which partner.\n\nTo support the management of pad-files:\n* Such files have a file-extension \".1tp\"\n* Lines starting with \"#\" may contain arbitary meta-data (i.e. comments)\n* Lines starting with \"-\" count as \"used\"\n* Whitespace within the otp-data is ignored\n\n\n\nFor example, here is the data from Wikipedia:\n\n# Example data - Wikipedia - 2014-11-13\n-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ \n-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK \n YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK \n CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX \n QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR \n CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE \n EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE \n\n\n;See also\n* one time pad encryption in Python\n* snapfractalpop - One-Time-Pad Command-Line-Utility (C).\n* Crypt-OTP-2.00 on CPAN (Perl)\n\n", "solution": "// version 1.2.31\n\nimport java.io.File\nimport java.security.SecureRandom\n\nconst val CHARS_PER_LINE = 48\nconst val CHUNK_SIZE = 6\nconst val COLS = 8\nconst val DEMO = true // would normally be set to false\n\nenum class FileType { OTP, ENC, DEC }\n\nfun Char.isAlpha() = this in 'A'..'Z'\n\nfun String.toAlpha() = this.filter { it.isAlpha() }\n\nfun String.isOtpRelated() = endsWith(\".1tp\") || endsWith(\".1tp_cpy\") ||\n endsWith(\".1tp_enc\") || endsWith(\".1tp_dec\")\n\nfun makePad(nLines: Int): String {\n val nChars = nLines * CHARS_PER_LINE\n val sr = SecureRandom()\n val sb = StringBuilder(nChars)\n /* generate random upper case letters */\n for (i in 0 until nChars) sb.append((sr.nextInt(26) + 65).toChar())\n return sb.toString().inChunks(nLines, FileType.OTP)\n}\n\nfun vigenere(text: String, key: String, encrypt: Boolean = true): String {\n val sb = StringBuilder(text.length)\n for ((i, c) in text.withIndex()) {\n val ci = if (encrypt)\n (c.toInt() + key[i].toInt() - 130) % 26\n else\n (c.toInt() - key[i].toInt() + 26) % 26\n sb.append((ci + 65).toChar())\n }\n val temp = sb.length % CHARS_PER_LINE\n if (temp > 0) { // pad with random characters so each line is a full one\n val sr = SecureRandom()\n for (i in temp until CHARS_PER_LINE) sb.append((sr.nextInt(26) + 65).toChar())\n }\n val ft = if (encrypt) FileType.ENC else FileType.DEC\n return sb.toString().inChunks(sb.length / CHARS_PER_LINE, ft)\n}\n\nfun String.inChunks(nLines: Int, ft: FileType): String {\n val chunks = this.chunked(CHUNK_SIZE)\n val sb = StringBuilder(this.length + nLines * (COLS + 1))\n for (i in 0 until nLines) {\n val j = i * COLS\n sb.append(\" ${chunks.subList(j, j + COLS).joinToString(\" \")}\\n\")\n }\n val s = \" file\\n\" + sb.toString()\n return when (ft) {\n FileType.OTP -> \"# OTP\" + s\n FileType.ENC -> \"# Encrypted\" + s\n FileType.DEC -> \"# Decrypted\" + s\n }\n}\n\nfun menu(): Int {\n println(\"\"\"\n |\n |1. Create one time pad file.\n |\n |2. Delete one time pad file.\n |\n |3. List one time pad files.\n |\n |4. Encrypt plain text.\n |\n |5. Decrypt cipher text.\n |\n |6. Quit program.\n |\n \"\"\".trimMargin())\n var choice: Int?\n do {\n print(\"Your choice (1 to 6) : \")\n choice = readLine()!!.toIntOrNull()\n }\n while (choice == null || choice !in 1..6)\n return choice\n}\n\nfun main(args: Array) {\n mainLoop@ while (true) {\n val choice = menu()\n println()\n when (choice) {\n 1 -> { // Create OTP\n println(\"Note that encrypted lines always contain 48 characters.\\n\")\n print(\"OTP file name to create (without extension) : \")\n val fileName = readLine()!! + \".1tp\" \n var nLines: Int?\n\n do {\n print(\"Number of lines in OTP (max 1000) : \")\n nLines = readLine()!!.toIntOrNull()\n }\n while (nLines == null || nLines !in 1..1000)\n\n val key = makePad(nLines)\n File(fileName).writeText(key)\n println(\"\\n'$fileName' has been created in the current directory.\")\n if (DEMO) {\n // a copy of the OTP file would normally be on a different machine\n val fileName2 = fileName + \"_cpy\" // copy for decryption\n File(fileName2).writeText(key)\n println(\"'$fileName2' has been created in the current directory.\")\n println(\"\\nThe contents of these files are :\\n\")\n println(key)\n }\n }\n\n 2 -> { // Delete OTP\n println(\"Note that this will also delete ALL associated files.\\n\")\n print(\"OTP file name to delete (without extension) : \")\n val toDelete1 = readLine()!! + \".1tp\"\n val toDelete2 = toDelete1 + \"_cpy\"\n val toDelete3 = toDelete1 + \"_enc\"\n val toDelete4 = toDelete1 + \"_dec\"\n val allToDelete = listOf(toDelete1, toDelete2, toDelete3, toDelete4)\n var deleted = 0\n println()\n for (name in allToDelete) {\n val f = File(name)\n if (f.exists()) {\n f.delete()\n deleted++\n println(\"'$name' has been deleted from the current directory.\")\n }\n }\n if (deleted == 0) println(\"There are no files to delete.\")\n }\n\n 3 -> { // List OTPs\n println(\"The OTP (and related) files in the current directory are:\\n\")\n val otpFiles = File(\".\").listFiles().filter {\n it.isFile() && it.name.isOtpRelated()\n }.map { it.name }.toMutableList()\n otpFiles.sort()\n println(otpFiles.joinToString(\"\\n\"))\n }\n\n 4 -> { // Encrypt\n print(\"OTP file name to use (without extension) : \")\n val keyFile = readLine()!! + \".1tp\"\n val kf = File(keyFile)\n if (kf.exists()) {\n val lines = File(keyFile).readLines().toMutableList()\n var first = lines.size\n for (i in 0 until lines.size) {\n if (lines[i].startsWith(\" \")) {\n first = i\n break\n }\n }\n if (first == lines.size) {\n println(\"\\nThat file has no unused lines.\")\n continue@mainLoop\n }\n val lines2 = lines.drop(first) // get rid of comments and used lines\n\n println(\"Text to encrypt :-\\n\")\n val text = readLine()!!.toUpperCase().toAlpha()\n val len = text.length\n var nLines = len / CHARS_PER_LINE\n if (len % CHARS_PER_LINE > 0) nLines++\n\n if (lines2.size >= nLines) {\n val key = lines2.take(nLines).joinToString(\"\").toAlpha()\n val encrypted = vigenere(text, key)\n val encFile = keyFile + \"_enc\"\n File(encFile).writeText(encrypted)\n println(\"\\n'$encFile' has been created in the current directory.\")\n for (i in first until first + nLines) {\n lines[i] = \"-\" + lines[i].drop(1)\n }\n File(keyFile).writeText(lines.joinToString(\"\\n\"))\n if (DEMO) {\n println(\"\\nThe contents of the encrypted file are :\\n\")\n println(encrypted)\n }\n }\n else println(\"Not enough lines left in that file to do encryption\")\n }\n else println(\"\\nThat file does not exist.\")\n }\n\n 5 -> { // Decrypt\n print(\"OTP file name to use (without extension) : \")\n val keyFile = readLine()!! + \".1tp_cpy\"\n val kf = File(keyFile)\n if (kf.exists()) {\n val keyLines = File(keyFile).readLines().toMutableList()\n var first = keyLines.size\n for (i in 0 until keyLines.size) {\n if (keyLines[i].startsWith(\" \")) {\n first = i\n break\n }\n }\n if (first == keyLines.size) {\n println(\"\\nThat file has no unused lines.\")\n continue@mainLoop\n }\n val keyLines2 = keyLines.drop(first) // get rid of comments and used lines\n\n val encFile = keyFile.dropLast(3) + \"enc\"\n val ef = File(encFile)\n if (ef.exists()) {\n val encLines = File(encFile).readLines().drop(1) // exclude comment line\n val nLines = encLines.size\n if (keyLines2.size >= nLines) {\n val encrypted = encLines.joinToString(\"\").toAlpha()\n val key = keyLines2.take(nLines).joinToString(\"\").toAlpha()\n val decrypted = vigenere(encrypted, key, false)\n val decFile = keyFile.dropLast(3) + \"dec\"\n File(decFile).writeText(decrypted)\n println(\"\\n'$decFile' has been created in the current directory.\")\n for (i in first until first + nLines) {\n keyLines[i] = \"-\" + keyLines[i].drop(1)\n }\n File(keyFile).writeText(keyLines.joinToString(\"\\n\"))\n if (DEMO) {\n println(\"\\nThe contents of the decrypted file are :\\n\")\n println(decrypted)\n }\n }\n else println(\"Not enough lines left in that file to do decryption\")\n }\n else println(\"\\n'$encFile' is missing.\")\n }\n else println(\"\\nThat file does not exist.\")\n }\n\n else -> return // Quit\n }\n }\n}"} {"title": "One of n lines in a file", "language": "Kotlin", "task": "A method of choosing a line randomly from a file:\n::* Without reading the file more than once\n::* When substantial parts of the file cannot be held in memory\n::* Without knowing how many lines are in the file\nIs to:\n::* keep the first line of the file as a possible choice, then\n::* Read the second line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/2.\n::* Read the third line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/3.\n::* ...\n::* Read the Nth line of the file if possible and make it the possible choice if a uniform random value between zero and one is less than 1/N\n\n::* Return the computed possible choice when no further lines exist in the file.\n\n\n;Task:\n# Create a function/method/routine called one_of_n that given n, the number of actual lines in a file, follows the algorithm above to return an integer - the line number of the line chosen from the file. The number returned can vary, randomly, in each run.\n# Use one_of_n in a ''simulation'' to find what would be the chosen line of a 10-line file simulated 1,000,000 times.\n# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.\n\n\nNote: You may choose a smaller number of repetitions if necessary, but mention this up-front.\n\nNote: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling\n\n", "solution": "// version 1.1.51\n\nimport java.util.Random\n\nval r = Random()\n\nfun oneOfN(n: Int): Int {\n var choice = 1\n for (i in 2..n) {\n if (r.nextDouble() < 1.0 / i) choice = i\n }\n return choice\n}\n\nfun main(args: Array) {\n val n = 10\n val freqs = IntArray(n)\n val reps = 1_000_000\n repeat(reps) {\n val num = oneOfN(n)\n freqs[num - 1]++\n }\n for (i in 1..n) println(\"Line ${\"%-2d\".format(i)} = ${freqs[i - 1]}\")\n}"} {"title": "OpenWebNet password", "language": "Kotlin from Python", "task": "Calculate the password requested by ethernet gateways from the Legrand / Bticino MyHome OpenWebNet home automation system when the user's ip address is not in the gateway's whitelist\n\n'''Note:''' Factory default password is '12345'. Changing it is highly recommended !\n\nconversation goes as follows\n\n- *#*1##\n- *99*0##\n- *#603356072##\n\nat which point a password should be sent back, calculated from the \"password open\" that is set in the gateway, and the nonce that was just sent\n\n- *#25280520##\n- *#*1##\n", "solution": "// version 1.1.51\n\nfun ownCalcPass(password: Long, nonce: String): Long {\n val m1 = 0xFFFF_FFFFL\n val m8 = 0xFFFF_FFF8L\n val m16 = 0xFFFF_FFF0L\n val m128 = 0xFFFF_FF80L\n val m16777216 = 0xFF00_0000L\n\n var flag = true\n var num1 = 0L\n var num2 = 0L\n\n for (c in nonce) {\n num2 = num2 and m1\n\n when (c) {\n '1' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 and m128\n num1 = num1 ushr 7\n num2 = num2 shl 25\n num1 = num1 + num2\n }\n\n '2' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 and m16\n num1 = num1 ushr 4\n num2 = num2 shl 28\n num1 = num1 + num2\n }\n\n '3' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 and m8\n num1 = num1 ushr 3\n num2 = num2 shl 29\n num1 = num1 + num2\n }\n\n '4' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 shl 1\n num2 = num2 ushr 31\n num1 = num1 + num2\n }\n\n '5' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 shl 5\n num2 = num2 ushr 27\n num1 = num1 + num2\n }\n\n '6' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 shl 12\n num2 = num2 ushr 20\n num1 = num1 + num2\n }\n\n '7' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 and 0xFF00L\n num1 = num1 + ((num2 and 0xFFL) shl 24)\n num1 = num1 + ((num2 and 0xFF0000L) ushr 16)\n num2 = (num2 and m16777216) ushr 8\n num1 = num1 + num2\n }\n\n '8' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2 and 0xFFFFL\n num1 = num1 shl 16\n num1 = num1 + (num2 ushr 24)\n num2 = num2 and 0xFF0000L\n num2 = num2 ushr 8\n num1 = num1 + num2\n }\n\n '9' -> {\n if (flag) num2 = password\n flag = false\n num1 = num2.inv()\n }\n\n else -> num1 = num2\n }\n num2 = num1\n }\n return num1 and m1\n}\n\nfun ownTestCalcPass(passwd: String, nonce: String, expected: Long) {\n val res = ownCalcPass(passwd.toLong(), nonce)\n val m = \"$passwd $nonce $res $expected\"\n println(if (res == expected) \"PASS $m\" else \"FAIL $m\")\n}\n\nfun main(args: Array) {\n ownTestCalcPass(\"12345\", \"603356072\", 25280520)\n ownTestCalcPass(\"12345\", \"410501656\", 119537670)\n}"} {"title": "Operator precedence", "language": "Kotlin", "task": "Operators in C and C++}}\n\n\n;Task:\nProvide a list of [[wp:order of operations|precedence and associativity of all the operators and constructs that the language utilizes in descending order of precedence such that an operator which is listed on some row will be evaluated prior to any operator that is listed on a row further below it. \n\nOperators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same level of precedence, in the given direction. \n\nState whether arguments are passed by value or by reference.\n\n", "solution": "This is well-documented [https://kotlinlang.org/docs/reference/grammar.html on the Kotlin language website].\n\n"} {"title": "Pancake numbers", "language": "Kotlin from Go", "task": "Adrian Monk has problems and an assistant, Sharona Fleming. Sharona can deal with most of Adrian's problems except his lack of punctuality paying her remuneration. 2 pay checks down and she prepares him pancakes for breakfast. Knowing that he will be unable to eat them unless they are stacked in ascending order of size she leaves him only a skillet which he can insert at any point in the pile and flip all the above pancakes, repeating until the pile is sorted. Sharona has left the pile of n pancakes such that the maximum number of flips is required. Adrian is determined to do this in as few flips as possible. This sequence n->p(n) is known as the Pancake numbers.\n\nThe task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.\n\n[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?\n\nFew people know p(20), generously I shall award an extra credit for anyone doing more than p(16).\n\n\n;References\n# Bill Gates and the pancake problem\n# A058986\n\n", "solution": "fun pancake(n: Int): Int {\n var gap = 2\n var sum = 2\n var adj = -1\n while (sum < n) {\n adj++\n gap = gap * 2 - 1\n sum += gap\n }\n return n + adj\n}\n\nfun main() {\n (1 .. 20).map {\"p(%2d) = %2d\".format(it, pancake(it))}\n val lines = results.chunked(5).map { it.joinToString(\" \") }\n lines.forEach { println(it) }\n}"} {"title": "Pangram checker", "language": "Kotlin", "task": "A pangram is a sentence that contains all the letters of the English alphabet at least once.\n\nFor example: ''The quick brown fox jumps over the lazy dog''.\n\n\n;Task:\nWrite a function or method to check a sentence to see if it is a pangram (or not) and show its use.\n\n\n;Related tasks:\n:* determine if a string has all the same characters\n:* determine if a string has all unique characters\n\n", "solution": "// version 1.0.6\n\nfun isPangram(s: String): Boolean {\n if (s.length < 26) return false\n val t = s.toLowerCase()\n for (c in 'a' .. 'z')\n if (c !in t) return false\n return true\n}\n\nfun main(args: Array) {\n val candidates = arrayOf(\n \"The quick brown fox jumps over the lazy dog\",\n \"New job: fix Mr. Gluck's hazy TV, PDQ!\",\n \"A very bad quack might jinx zippy fowls\",\n \"A very mad quack might jinx zippy fowls\" // no 'b' now!\n )\n for (candidate in candidates)\n println(\"'$candidate' is ${if (isPangram(candidate)) \"a\" else \"not a\"} pangram\")\n}"} {"title": "Paraffins", "language": "Kotlin from Java", "task": "This organic chemistry task is essentially to implement a tree enumeration algorithm.\n\n\n;Task:\nEnumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes). \n\n\nParaffins are built up using only carbon atoms, which has four bonds, and hydrogen, which has one bond. All bonds for each atom must be used, so it is easiest to think of an alkane as linked carbon atoms forming the \"backbone\" structure, with adding hydrogen atoms linking the remaining unused bonds.\n\nIn a paraffin, one is allowed neither double bonds (two bonds between the same pair of atoms), nor cycles of linked carbons. So all paraffins with '''n''' carbon atoms share the empirical formula CnH2n+2\n\nBut for all '''n''' >= 4 there are several distinct molecules (\"isomers\") with the same formula but different structures. \n\nThe number of isomers rises rather rapidly when '''n''' increases. \n\nIn counting isomers it should be borne in mind that the four bond positions on a given carbon atom can be freely interchanged and bonds rotated (including 3-D \"out of the paper\" rotations when it's being observed on a flat diagram), so rotations or re-orientations of parts of the molecule (without breaking bonds) do not give different isomers. So what seem at first to be different molecules may in fact turn out to be different orientations of the same molecule.\n\n\n;Example:\nWith '''n''' = 3 there is only one way of linking the carbons despite the different orientations the molecule can be drawn; and with '''n''' = 4 there are two configurations: \n:::* a straight chain: (CH3)(CH2)(CH2)(CH3) \n:::* a branched chain: (CH3)(CH(CH3))(CH3)\n\nDue to bond rotations, it doesn't matter which direction the branch points in. \n\nThe phenomenon of \"stereo-isomerism\" (a molecule being different from its mirror image due to the actual 3-D arrangement of bonds) is ignored for the purpose of this task.\n\nThe input is the number '''n''' of carbon atoms of a molecule (for instance '''17'''). \n\nThe output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).\n\nThe sequence of those results is visible in the OEIS entry: \n::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers. \n\nThe sequence is (the index starts from zero, and represents the number of carbon atoms):\n\n 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,\n 24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,\n 36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,\n 10660307791, 27711253769, ...\n\n\n;Extra credit:\nShow the paraffins in some way. \n\nA flat 1D representation, with arrays or lists is enough, for instance:\n\n*Main> all_paraffins 1\n [CCP H H H H]\n*Main> all_paraffins 2\n [BCP (C H H H) (C H H H)]\n*Main> all_paraffins 3\n [CCP H H (C H H H) (C H H H)]\n*Main> all_paraffins 4\n [BCP (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 5\n [CCP H H (C H H (C H H H)) (C H H (C H H H)),\n CCP H (C H H H) (C H H H) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H H)]\n*Main> all_paraffins 6\n [BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),\n BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),\n BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),\n CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),\n CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]\nShowing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):\n methane ethane propane isobutane\n \n H H H H H H H H H\n | | | | | | | | |\n H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H\n | | | | | | | | |\n H H H H H H H | H\n |\n H - C - H\n |\n H \n\n;Links:\n* A paper that explains the problem and its solution in a functional language:\nhttp://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf\n\n* A Haskell implementation:\nhttps://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs\n\n* A Scheme implementation:\nhttp://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm\n\n* A Fortress implementation: (this site has been closed)\nhttp://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005\n\n", "solution": "// version 1.1.4-3\n\nimport java.math.BigInteger\n\nconst val MAX_N = 250\nconst val BRANCHES = 4\n\nval rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }\nval unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }\nval c = Array(BRANCHES) { BigInteger.ZERO }\n\nfun tree(br: Int, n: Int, l: Int, s: Int, cnt: BigInteger) {\n var sum = s\n for (b in (br + 1)..BRANCHES) {\n sum += n\n if (sum > MAX_N || (l * 2 >= sum && b >= BRANCHES)) return\n\n var tmp = rooted[n]\n if (b == br + 1) {\n c[br] = tmp * cnt\n }\n else {\n val diff = (b - br).toLong()\n c[br] *= tmp + BigInteger.valueOf(diff - 1L)\n c[br] /= BigInteger.valueOf(diff)\n }\n \n if (l * 2 < sum) unrooted[sum] += c[br]\n if (b < BRANCHES) rooted[sum] += c[br]\n for (m in n - 1 downTo 1) tree(b, m, l, sum, c[br])\n }\n}\n\nfun bicenter(s: Int) {\n if ((s and 1) == 0) {\n var tmp = rooted[s / 2]\n tmp *= tmp + BigInteger.ONE\n unrooted[s] += tmp.shiftRight(1)\n }\n}\n\nfun main(args: Array) {\n for (n in 1..MAX_N) {\n tree(0, n, n, 1, BigInteger.ONE)\n bicenter(n)\n println(\"$n: ${unrooted[n]}\")\n }\n}"} {"title": "Parse an IP Address", "language": "Kotlin", "task": "The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.\n \n\nTaking the following as inputs:\n::: {| border=\"5\" cellspacing=\"0\" cellpadding=2\n|-\n|127.0.0.1\n|The \"localhost\" IPv4 address\n|-\n|127.0.0.1:80\n|The \"localhost\" IPv4 address, with a specified port (80)\n|-\n|::1\n|The \"localhost\" IPv6 address\n|-\n|[::1]:80\n|The \"localhost\" IPv6 address, with a specified port (80)\n|-\n|2605:2700:0:3::4713:93e3\n|Rosetta Code's primary server's public IPv6 address\n|-\n|[2605:2700:0:3::4713:93e3]:80\n|Rosetta Code's primary server's public IPv6 address, with a specified port (80)\n|}\n\n\n;Task:\nEmit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any. \n\nIn languages where variant result types are clumsy, the result should be ipv4 or ipv6 address number, something which says which address space was represented, port number and something that says if the port was specified.\n\n\n;Example:\n'''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal) \nin the ipv4 address space. \n\n'''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the \naddress number '''FFFF7F000001''' (281472812449793 decimal). \n\n'''::1''' has address number '''1''' and serves the same purpose in the ipv6 address \nspace that '''127.0.0.1''' serves in the ipv4 address space.\n\n", "solution": "// version 1.1.3\n\nimport java.math.BigInteger\n\nenum class AddressSpace { IPv4, IPv6, Invalid }\n\ndata class IPAddressComponents(\n val address: BigInteger,\n val addressSpace: AddressSpace,\n val port: Int // -1 denotes 'not specified'\n)\n\nval INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid, 0)\n \nfun ipAddressParse(ipAddress: String): IPAddressComponents {\n var addressSpace = AddressSpace.IPv4\n var ipa = ipAddress.toLowerCase()\n var port = -1\n var trans = false\n \n if (ipa.startsWith(\"::ffff:\") && '.' in ipa) {\n addressSpace = AddressSpace.IPv6\n trans = true\n ipa = ipa.drop(7)\n }\n else if (ipa.startsWith(\"[::ffff:\") && '.' in ipa) {\n addressSpace = AddressSpace.IPv6\n trans = true\n ipa = ipa.drop(8).replace(\"]\", \"\")\n } \n val octets = ipa.split('.').reversed().toTypedArray()\n var address = BigInteger.ZERO\n if (octets.size == 4) {\n val split = octets[0].split(':')\n if (split.size == 2) {\n val temp = split[1].toIntOrNull()\n if (temp == null || temp !in 0..65535) return INVALID \n port = temp\n octets[0] = split[0]\n }\n \n for (i in 0..3) {\n val num = octets[i].toLongOrNull()\n if (num == null || num !in 0..255) return INVALID\n val bigNum = BigInteger.valueOf(num)\n address = address.or(bigNum.shiftLeft(i * 8))\n }\n\n if (trans) address += BigInteger(\"ffff00000000\", 16)\n }\n else if (octets.size == 1) {\n addressSpace = AddressSpace.IPv6\n if (ipa[0] == '[') {\n ipa = ipa.drop(1)\n val split = ipa.split(\"]:\")\n if (split.size != 2) return INVALID\n val temp = split[1].toIntOrNull()\n if (temp == null || temp !in 0..65535) return INVALID\n port = temp\n ipa = ipa.dropLast(2 + split[1].length)\n }\n val hextets = ipa.split(':').reversed().toMutableList()\n val len = hextets.size\n\n if (ipa.startsWith(\"::\")) \n hextets[len - 1] = \"0\"\n else if (ipa.endsWith(\"::\")) \n hextets[0] = \"0\"\n\n if (ipa == \"::\") hextets[1] = \"0\" \n if (len > 8 || (len == 8 && hextets.any { it == \"\" }) || hextets.count { it == \"\" } > 1)\n return INVALID\n if (len < 8) {\n var insertions = 8 - len \n for (i in 0..7) {\n if (hextets[i] == \"\") {\n hextets[i] = \"0\"\n while (insertions-- > 0) hextets.add(i, \"0\") \n break \n }\n } \n }\n for (j in 0..7) {\n val num = hextets[j].toLongOrNull(16)\n if (num == null || num !in 0x0..0xFFFF) return INVALID\n val bigNum = BigInteger.valueOf(num)\n address = address.or(bigNum.shiftLeft(j * 16))\n } \n }\n else return INVALID\n\n return IPAddressComponents(address, addressSpace, port)\n}\n\nfun main(args: Array) {\n val ipas = listOf(\n \"127.0.0.1\",\n \"127.0.0.1:80\",\n \"::1\",\n \"[::1]:80\",\n \"2605:2700:0:3::4713:93e3\",\n \"[2605:2700:0:3::4713:93e3]:80\",\n \"::ffff:192.168.173.22\",\n \"[::ffff:192.168.173.22]:80\",\n \"1::\",\n \"::\",\n \"256.0.0.0\",\n \"::ffff:127.0.0.0.1\"\n )\n for (ipa in ipas) {\n val (address, addressSpace, port) = ipAddressParse(ipa)\n println(\"IP address : $ipa\")\n println(\"Address : ${\"%X\".format(address)}\") \n println(\"Address Space : $addressSpace\")\n println(\"Port : ${if (port == -1) \"not specified\" else port.toString()}\")\n println()\n } \n}"} {"title": "Parsing/RPN calculator algorithm", "language": "Kotlin", "task": "Create a stack-based evaluator for an expression in reverse Polish notation (RPN) that also shows the changes in the stack as each individual token is processed ''as a table''.\n\n\n* Assume an input of a correct, space separated, string of tokens of an RPN expression\n* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task: \n 3 4 2 * 1 5 - 2 3 ^ ^ / + \n* Print or display the output here\n\n\n;Notes:\n* '''^''' means exponentiation in the expression above.\n* '''/''' means division.\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).\n* [[Parsing/RPN to infix conversion]].\n* [[Arithmetic evaluation]].\n\n", "solution": "// version 1.1.2\n\nfun rpnCalculate(expr: String) {\n if (expr.isEmpty()) throw IllegalArgumentException(\"Expresssion cannot be empty\")\n println(\"For expression = $expr\\n\")\n println(\"Token Action Stack\")\n val tokens = expr.split(' ').filter { it != \"\" }\n val stack = mutableListOf()\n for (token in tokens) {\n val d = token.toDoubleOrNull()\n if (d != null) {\n stack.add(d)\n println(\" $d Push num onto top of stack $stack\") \n }\n else if ((token.length > 1) || (token !in \"+-*/^\")) {\n throw IllegalArgumentException(\"$token is not a valid token\")\n }\n else if (stack.size < 2) {\n throw IllegalArgumentException(\"Stack contains too few operands\")\n }\n else {\n val d1 = stack.removeAt(stack.lastIndex)\n val d2 = stack.removeAt(stack.lastIndex)\n stack.add(when (token) {\n \"+\" -> d2 + d1\n \"-\" -> d2 - d1\n \"*\" -> d2 * d1\n \"/\" -> d2 / d1\n else -> Math.pow(d2, d1) \n })\n println(\" $token Apply op to top of stack $stack\")\n }\n } \n println(\"\\nThe final value is ${stack[0]}\")\n}\n\nfun main(args: Array) {\n val expr = \"3 4 2 * 1 5 - 2 3 ^ ^ / +\"\n rpnCalculate(expr)\n}"} {"title": "Parsing/RPN to infix conversion", "language": "Kotlin from Java", "task": "Create a program that takes an infix notation.\n\n* Assume an input of a correct, space separated, string of tokens\n* Generate a space separated output string representing the same expression in infix notation\n* Show how the major datastructure of your algorithm changes with each new token parsed.\n* Test with the following input RPN strings then print and display the output here.\n:::::{| class=\"wikitable\"\n! RPN input !! sample output\n|- || align=\"center\"\n| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\n|- || align=\"center\"\n| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\n|}\n\n* Operator precedence and operator associativity is given in this table:\n::::::::{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\" \n| ^ || 4 || right || exponentiation\n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\" \n| - || 2 || left || subtraction\n|}\n\n\n;See also:\n* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* Postfix to infix from the RubyQuiz site.\n\n", "solution": "// version 1.2.0\n\nimport java.util.Stack\n\nclass Expression(var ex: String, val op: String = \"\", val prec: Int = 3) {\n\n constructor(e1: String, e2: String, o: String) :\n this(\"$e1 $o $e2\", o, OPS.indexOf(o) / 2)\n\n override fun toString() = ex\n\n companion object {\n const val OPS = \"-+/*^\"\n }\n}\n\nfun postfixToInfix(postfix: String): String {\n val expr = Stack()\n val rx = Regex(\"\"\"\\s+\"\"\")\n for (token in postfix.split(rx)) {\n val c = token[0]\n val idx = Expression.OPS.indexOf(c)\n if (idx != -1 && token.length == 1) {\n val r = expr.pop()\n val l = expr.pop()\n val opPrec = idx / 2\n if (l.prec < opPrec || (l.prec == opPrec && c == '^')) {\n l.ex = \"(${l.ex})\"\n }\n if (r.prec < opPrec || (r.prec == opPrec && c != '^')) {\n r.ex = \"(${r.ex})\"\n }\n expr.push(Expression(l.ex, r.ex, token))\n }\n else {\n expr.push(Expression(token))\n }\n println(\"$token -> $expr\")\n }\n return expr.peek().ex\n}\n\nfun main(args: Array) {\n val es = listOf(\n \"3 4 2 * 1 5 - 2 3 ^ ^ / +\",\n \"1 2 + 3 4 + ^ 5 6 + ^\"\n )\n for (e in es) {\n println(\"Postfix : $e\")\n println(\"Infix : ${postfixToInfix(e)}\\n\")\n }\n}"} {"title": "Parsing/Shunting-yard algorithm", "language": "Kotlin from Java", "task": "Given the operator characteristics and input from the Shunting-yard algorithm page and tables, use the algorithm to show the changes in the operator stack and RPN output\nas each individual token is processed.\n\n* Assume an input of a correct, space separated, string of tokens representing an infix expression\n* Generate a space separated output string representing the RPN\n* Test with the input string:\n:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 \n* print and display the output here.\n* Operator precedence is given in this table:\n:{| class=\"wikitable\"\n\n! operator !! associativity !! operation\n|- || align=\"center\"\n| ^ || 4 || right || exponentiation \n|- || align=\"center\" \n| * || 3 || left || multiplication\n|- || align=\"center\" \n| / || 3 || left || division\n|- || align=\"center\" \n| + || 2 || left || addition\n|- || align=\"center\"\n| - || 2 || left || subtraction\n|}\n\n\n;Extra credit\nAdd extra text explaining the actions and an optional comment for the action on receipt of each token.\n\n\n;Note\nThe handling of functions and arguments is not required.\n\n\n;See also:\n* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.\n* [[Parsing/RPN to infix conversion]].\n\n", "solution": "// version 1.2.0\n\nimport java.util.Stack\n\n/* To find out the precedence, we take the index of the\n token in the OPS string and divide by 2 (rounding down).\n This will give us: 0, 0, 1, 1, 2 */\nconst val OPS = \"-+/*^\"\n\nfun infixToPostfix(infix: String): String {\n val sb = StringBuilder()\n val s = Stack()\n val rx = Regex(\"\"\"\\s\"\"\")\n for (token in infix.split(rx)) {\n if (token.isEmpty()) continue\n val c = token[0]\n val idx = OPS.indexOf(c)\n\n // check for operator\n if (idx != - 1) {\n if (s.isEmpty()) {\n s.push(idx)\n }\n else {\n while (!s.isEmpty()) {\n val prec2 = s.peek() / 2\n val prec1 = idx / 2\n if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {\n sb.append(OPS[s.pop()]).append(' ')\n }\n else break\n }\n s.push(idx)\n }\n }\n else if (c == '(') {\n s.push(-2) // -2 stands for '('\n }\n else if (c == ')') {\n // until '(' on stack, pop operators.\n while (s.peek() != -2) sb.append(OPS[s.pop()]).append(' ')\n s.pop()\n }\n else {\n sb.append(token).append(' ')\n }\n }\n while (!s.isEmpty()) sb.append(OPS[s.pop()]).append(' ')\n return sb.toString()\n}\n\nfun main(args: Array) {\n val es = listOf(\n \"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3\",\n \"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )\"\n )\n for (e in es) {\n println(\"Infix : $e\")\n println(\"Postfix : ${infixToPostfix(e)}\\n\")\n }\n}"} {"title": "Pascal's triangle/Puzzle", "language": "Kotlin from C", "task": "This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.\n\n [ 151]\n [ ][ ]\n [40][ ][ ]\n [ ][ ][ ][ ]\n [ X][11][ Y][ 4][ Z]\n\nEach brick of the pyramid is the sum of the two bricks situated below it.\nOf the three missing numbers at the base of the pyramid, \nthe middle one is the sum of the other two (that is, Y = X + Z).\n\n\n;Task:\nWrite a program to find a solution to this puzzle.\n\n", "solution": "// version 1.1.3\n\ndata class Solution(val x: Int, val y: Int, val z: Int)\n\nfun Double.isIntegral(tolerance: Double = 0.0) =\n (this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance\n\nfun pascal(a: Int, b: Int, mid: Int, top: Int): Solution {\n val yd = (top - 4 * (a + b)) / 7.0\n if (!yd.isIntegral(0.0001)) return Solution(0, 0, 0)\n val y = yd.toInt()\n val x = mid - 2 * a - y\n return Solution(x, y, y - x)\n}\n\nfun main(args: Array) {\n val (x, y, z) = pascal(11, 4, 40, 151)\n if (x != 0)\n println(\"Solution is: x = $x, y = $y, z = $z\")\n else\n println(\"There is no solutuon\")\n}"} {"title": "Pascal matrix generation", "language": "Kotlin", "task": "A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.\n\nShown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4. \n\nA Pascal upper-triangular matrix that is populated with jCi:\n\n[[1, 1, 1, 1, 1],\n [0, 1, 2, 3, 4],\n [0, 0, 1, 3, 6],\n [0, 0, 0, 1, 4],\n [0, 0, 0, 0, 1]]\n\n\nA Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):\n\n[[1, 0, 0, 0, 0],\n [1, 1, 0, 0, 0],\n [1, 2, 1, 0, 0],\n [1, 3, 3, 1, 0],\n [1, 4, 6, 4, 1]]\n\n\nA Pascal symmetric matrix that is populated with i+jCi:\n\n[[1, 1, 1, 1, 1],\n [1, 2, 3, 4, 5],\n [1, 3, 6, 10, 15],\n [1, 4, 10, 20, 35],\n [1, 5, 15, 35, 70]]\n\n\n\n;Task:\nWrite functions capable of generating each of the three forms of n-by-n matrices.\n\nUse those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page. \n\nThe output should distinguish between different matrices and the rows of each matrix (no showing a list of 25 numbers assuming the reader should split it into rows).\n\n\n;Note: \nThe [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size. \n\n", "solution": "// version 1.1.3\n\nfun binomial(n: Int, k: Int): Int {\n if (n < k) return 0 \n if (n == 0 || k == 0) return 1\n val num = (k + 1..n).fold(1) { acc, i -> acc * i }\n val den = (2..n - k).fold(1) { acc, i -> acc * i }\n return num / den\n}\n\nfun pascalUpperTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(j, i) } }\n\nfun pascalLowerTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i, j) } }\n\nfun pascalSymmetric(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i + j, i) } }\n\nfun printMatrix(title: String, m: List) {\n val n = m.size\n println(title)\n print(\"[\")\n for (i in 0 until n) {\n if (i > 0) print(\" \")\n print(m[i].contentToString())\n if (i < n - 1) println(\",\") else println(\"]\\n\")\n }\n}\n\nfun main(args: Array) {\n printMatrix(\"Pascal upper-triangular matrix\", pascalUpperTriangular(5))\n printMatrix(\"Pascal lower-triangular matrix\", pascalLowerTriangular(5))\n printMatrix(\"Pascal symmetric matrix\", pascalSymmetric(5))\n}"} {"title": "Password generator", "language": "Kotlin", "task": "Create a password generation program which will generate passwords containing random ASCII characters from the following groups:\n lower-case letters: a --> z\n upper-case letters: A --> Z\n digits: 0 --> 9\n other printable characters: !\"#$%&'()*+,-./:;<=>?@[]^_{|}~ \n (the above character list excludes white-space, backslash and grave) \n\n\nThe generated password(s) must include ''at least one'' (of each of the four groups):\n lower-case letter, \n upper-case letter,\n digit (numeral), and \n one \"other\" character. \n\n\nThe user must be able to specify the password length and the number of passwords to generate. \n\nThe passwords should be displayed or written to a file, one per line.\n\nThe randomness should be from a system source or library. \n\nThe program should implement a help option or button which should describe the program and options when invoked. \n\nYou may also allow the user to specify a seed value, and give the option of excluding visually similar characters.\n\nFor example: Il1 O0 5S 2Z where the characters are: \n::::* capital eye, lowercase ell, the digit one\n::::* capital oh, the digit zero \n::::* the digit five, capital ess\n::::* the digit two, capital zee\n\n\n", "solution": "// version 1.1.4-3\n\nimport java.util.Random\nimport java.io.File\n\nval r = Random()\nval rr = Random() // use a separate generator for shuffles\nval ls = System.getProperty(\"line.separator\") \n\nvar lower = \"abcdefghijklmnopqrstuvwxyz\"\nvar upper = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nvar digit = \"0123456789\"\nvar other = \"\"\"!\"#$%&'()*+,-./:;<=>?@[]^_{|}~\"\"\"\n\nval exclChars = arrayOf(\n \"'I', 'l' and '1'\", \n \"'O' and '0' \",\n \"'5' and 'S' \",\n \"'2' and 'Z' \"\n)\n\nfun String.shuffle(): String {\n val sb = StringBuilder(this)\n var n = sb.length\n while (n > 1) {\n val k = rr.nextInt(n--)\n val t = sb[n]\n sb[n] = sb[k]\n sb[k] = t\n }\n return sb.toString()\n}\n\nfun generatePasswords(pwdLen: Int, pwdNum: Int, toConsole: Boolean, toFile: Boolean) {\n val sb = StringBuilder()\n val ll = lower.length\n val ul = upper.length\n val dl = digit.length\n val ol = other.length\n val tl = ll + ul + dl + ol \n var fw = if (toFile) File(\"pwds.txt\").writer() else null\n \n if (toConsole) println(\"\\nThe generated passwords are:\")\n for (i in 0 until pwdNum) {\n sb.setLength(0)\n sb.append(lower[r.nextInt(ll)])\n sb.append(upper[r.nextInt(ul)])\n sb.append(digit[r.nextInt(dl)])\n sb.append(other[r.nextInt(ol)])\n \n for (j in 0 until pwdLen - 4) {\n val k = r.nextInt(tl)\n sb.append(when (k) {\n in 0 until ll -> lower[k]\n in ll until ll + ul -> upper[k - ll]\n in ll + ul until tl - ol -> digit[k - ll - ul]\n else -> other[tl - 1 - k]\n })\n }\n var pwd = sb.toString()\n repeat(5) { pwd = pwd.shuffle() } // shuffle 5 times say\n if (toConsole) println(\" ${\"%2d\".format(i + 1)}: $pwd\")\n if (toFile) {\n fw!!.write(pwd)\n if (i < pwdNum - 1) fw.write(ls)\n }\n }\n if (toFile) {\n println(\"\\nThe generated passwords have been written to the file pwds.txt\") \n fw!!.close()\n } \n}\n\nfun printHelp() {\n println(\"\"\" \n |This program generates up to 99 passwords of between 5 and 20 characters in \n |length.\n |\n |You will be prompted for the values of all parameters when the program is run \n |- there are no command line options to memorize.\n |\n |The passwords can either be written to the console or to a file (pwds.txt), \n |or both.\n |\n |The passwords must contain at least one each of the following character types:\n | lower-case letters : a -> z\n | upper-case letters : A -> Z\n | digits : 0 -> 9\n | other characters : !\"#$%&'()*+,-./:;<=>?@[]^_{|}~\n |\n |Optionally, a seed can be set for the random generator \n |(any non-zero Long integer) otherwise the default seed will be used. \n |Even if the same seed is set, the passwords won't necessarily be exactly\n |the same on each run as additional random shuffles are always performed.\n |\n |You can also specify that various sets of visually similar characters\n |will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z\n | \n |Finally, the only command line options permitted are -h and -help which\n |will display this page and then exit.\n |\n |Any other command line parameters will simply be ignored and the program\n |will be run normally.\n |\n \"\"\".trimMargin())\n} \n \nfun main(args: Array) {\n if (args.size == 1 && (args[0] == \"-h\" || args[0] == \"-help\")) {\n printHelp()\n return\n }\n \n println(\"Please enter the following and press return after each one\")\n \n var pwdLen: Int?\n do {\n print(\" Password length (5 to 20) : \")\n pwdLen = readLine()!!.toIntOrNull() ?: 0 \n }\n while (pwdLen !in 5..20)\n\n var pwdNum: Int?\n do {\n print(\" Number to generate (1 to 99) : \")\n pwdNum = readLine()!!.toIntOrNull() ?: 0 \n }\n while (pwdNum !in 1..99)\n \n var seed: Long?\n do {\n print(\" Seed value (0 to use default) : \")\n seed = readLine()!!.toLongOrNull() \n }\n while (seed == null)\n if (seed != 0L) r.setSeed(seed)\n\n println(\" Exclude the following visually similar characters\")\n for (i in 0..3) {\n var yn: String\n do {\n print(\" ${exclChars[i]} y/n : \")\n yn = readLine()!!.toLowerCase()\n }\n while (yn != \"y\" && yn != \"n\")\n if (yn == \"y\") {\n when (i) {\n 0 -> {\n upper = upper.replace(\"I\", \"\")\n lower = lower.replace(\"l\", \"\")\n digit = digit.replace(\"1\", \"\")\n }\n\n 1 -> {\n upper = upper.replace(\"O\", \"\")\n digit = digit.replace(\"0\", \"\")\n }\n\n 2 -> {\n upper = upper.replace(\"S\", \"\")\n digit = digit.replace(\"5\", \"\")\n }\n\n 3 -> {\n upper = upper.replace(\"Z\", \"\")\n digit = digit.replace(\"2\", \"\")\n }\n }\n }\n }\n \n var toConsole: Boolean?\n do {\n print(\" Write to console y/n : \")\n val t = readLine()!!\n toConsole = if (t == \"y\") true else if (t == \"n\") false else null\n }\n while (toConsole == null)\n\n var toFile: Boolean? = true\n if (toConsole) {\n do {\n print(\" Write to file y/n : \")\n val t = readLine()!!\n toFile = if (t == \"y\") true else if (t == \"n\") false else null\n }\n while (toFile == null)\n }\n \n generatePasswords(pwdLen!!, pwdNum!!, toConsole, toFile!!)\n}"} {"title": "Pathological floating point problems", "language": "Kotlin", "task": "Most programmers are familiar with the inexactness of floating point calculations in a binary processor. \n\nThe classic example being:\n\n0.1 + 0.2 = 0.30000000000000004\n\n\nIn many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.\n\nThere are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.\n\nThis task's purpose is to show how your language deals with such classes of problems.\n\n\n'''A sequence that seems to converge to a wrong limit.''' \n\nConsider the sequence:\n:::::: v1 = 2 \n:::::: v2 = -4 \n:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2) \n\n\nAs '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.\n\n\n;Task 1:\nDisplay the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.\n\n n = 3 18.5\n n = 4 9.378378\n n = 5 7.801153\n n = 6 7.154414\n n = 7 6.806785\n n = 8 6.5926328\n n = 20 6.0435521101892689\n n = 30 6.006786093031205758530554\n n = 50 6.0001758466271871889456140207471954695237\n n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266\n\n\n\n;Task 2:\n'''The Chaotic Bank Society''' is offering a new investment account to their customers. \n\nYou first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.\n\nAfter each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed. \n\nSo ...\n::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.\n::* after 2 years your balance will be doubled and $1 removed.\n::* after 3 years your balance will be tripled and $1 removed.\n::* ... \n::* after 10 years, multiplied by 10 and $1 removed, and so on. \n\n\nWhat will your balance be after 25 years?\n Starting balance: $e-1\n Balance = (Balance * year) - 1 for 25 years\n Balance after 25 years: $0.0399387296732302\n\n\n;Task 3, extra credit:\n'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.\n:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b) \n:::::: compute f(a,b) where a=77617.0 and b=33096.0 \n:::::: f(77617.0, 33096.0) = -0.827396059946821 \n\n\nDemonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.\n\n\n;See also;\n* Floating-Point Arithmetic Section 1.3.2 Difficult problems.\n\n", "solution": "// version 1.0.6\n\nimport java.math.*\n\nconst val LIMIT = 100\n\nval con480 = MathContext(480)\nval bigTwo = BigDecimal(2)\nval bigE = BigDecimal(\"2.71828182845904523536028747135266249775724709369995\") // precise enough!\n\nfun main(args: Array) {\n // v(n) sequence task\n val c1 = BigDecimal(111)\n val c2 = BigDecimal(1130)\n val c3 = BigDecimal(3000)\n var v1 = bigTwo\n var v2 = BigDecimal(-4)\n var v3: BigDecimal\n for (i in 3 .. LIMIT) {\n v3 = c1 - c2.divide(v2, con480) + c3.divide(v2 * v1, con480)\n println(\"${\"%3d\".format(i)} : ${\"%19.16f\".format(v3)}\")\n v1 = v2\n v2 = v3\n }\n\n // Chaotic Building Society task\n var balance = bigE - BigDecimal.ONE\n for (year in 1..25) balance = balance.multiply(BigDecimal(year), con480) - BigDecimal.ONE\n println(\"\\nBalance after 25 years is ${\"%18.16f\".format(balance)}\")\n\n // Siegfried Rump task\n val a = BigDecimal(77617)\n val b = BigDecimal(33096)\n val c4 = BigDecimal(\"333.75\")\n val c5 = BigDecimal(11)\n val c6 = BigDecimal(121)\n val c7 = BigDecimal(\"5.5\")\n var f = c4 * b.pow(6, con480) + c7 * b.pow(8, con480) + a.divide(bigTwo * b, con480)\n val c8 = c5 * a.pow(2, con480) * b.pow(2, con480) - b.pow(6, con480) - c6 * b.pow(4, con480) - bigTwo\n f += c8 * a.pow(2, con480)\n println(\"\\nf(77617.0, 33096.0) is ${\"%18.16f\".format(f)}\") \n}"} {"title": "Peaceful chess queen armies", "language": "Kotlin from D", "task": "In chess, a queen attacks positions from where it is, in straight lines up-down and left-right as well as on both its diagonals. It attacks only pieces ''not'' of its own colour.\n\n\n\n\n\\\n|\n/\n\n\n\n=\n=\n\n=\n=\n\n\n\n/\n|\n\\\n\n\n\n/\n\n|\n\n\\\n\n\n\n\n|\n\n\n\n\n\n\nThe goal of Peaceful chess queen armies is to arrange m black queens and m white queens on an n-by-n square grid, (the board), so that ''no queen attacks another of a different colour''.\n\n\n;Task:\n# Create a routine to represent two-colour queens on a 2-D board. (Alternating black/white background colours, Unicode chess pieces and other embellishments are not necessary, but may be used at your discretion).\n# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.\n# Display here results for the m=4, n=5 case.\n\n\n;References:\n* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.\n* A250000 OEIS\n\n", "solution": "import kotlin.math.abs\n\nenum class Piece {\n Empty,\n Black,\n White,\n}\n\ntypealias Position = Pair\n\nfun place(m: Int, n: Int, pBlackQueens: MutableList, pWhiteQueens: MutableList): Boolean {\n if (m == 0) {\n return true\n }\n var placingBlack = true\n for (i in 0 until n) {\n inner@\n for (j in 0 until n) {\n val pos = Position(i, j)\n for (queen in pBlackQueens) {\n if (queen == pos || !placingBlack && isAttacking(queen, pos)) {\n continue@inner\n }\n }\n for (queen in pWhiteQueens) {\n if (queen == pos || placingBlack && isAttacking(queen, pos)) {\n continue@inner\n }\n }\n placingBlack = if (placingBlack) {\n pBlackQueens.add(pos)\n false\n } else {\n pWhiteQueens.add(pos)\n if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {\n return true\n }\n pBlackQueens.removeAt(pBlackQueens.lastIndex)\n pWhiteQueens.removeAt(pWhiteQueens.lastIndex)\n true\n }\n }\n }\n if (!placingBlack) {\n pBlackQueens.removeAt(pBlackQueens.lastIndex)\n }\n return false\n}\n\nfun isAttacking(queen: Position, pos: Position): Boolean {\n return queen.first == pos.first\n || queen.second == pos.second\n || abs(queen.first - pos.first) == abs(queen.second - pos.second)\n}\n\nfun printBoard(n: Int, blackQueens: List, whiteQueens: List) {\n val board = MutableList(n * n) { Piece.Empty }\n\n for (queen in blackQueens) {\n board[queen.first * n + queen.second] = Piece.Black\n }\n for (queen in whiteQueens) {\n board[queen.first * n + queen.second] = Piece.White\n }\n for ((i, b) in board.withIndex()) {\n if (i != 0 && i % n == 0) {\n println()\n }\n if (b == Piece.Black) {\n print(\"B \")\n } else if (b == Piece.White) {\n print(\"W \")\n } else {\n val j = i / n\n val k = i - j * n\n if (j % 2 == k % 2) {\n print(\"\u2022 \")\n } else {\n print(\"\u25e6 \")\n }\n }\n }\n println('\\n')\n}\n\nfun main() {\n val nms = listOf(\n Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3),\n Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5),\n Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6),\n Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7)\n )\n for ((n, m) in nms) {\n println(\"$m black and $m white queens on a $n x $n board:\")\n val blackQueens = mutableListOf()\n val whiteQueens = mutableListOf()\n if (place(m, n, blackQueens, whiteQueens)) {\n printBoard(n, blackQueens, whiteQueens)\n } else {\n println(\"No solution exists.\\n\")\n }\n }\n}"} {"title": "Pentagram", "language": "Kotlin from Java", "task": "A pentagram is a star polygon, consisting of a central pentagon of which each side forms the base of an isosceles triangle. The vertex of each triangle, a point of the star, is 36 degrees.\n\n\n;Task:\nDraw (or print) a regular pentagram, in any orientation. Use a different color (or token) for stroke and fill, and background. For the fill it should be assumed that all points inside the triangles and the pentagon are inside the pentagram.\n\n\n;See also\n* Angle sum of a pentagram\n\n", "solution": "// version 1.1.2\n\nimport java.awt.*\nimport java.awt.geom.Path2D\nimport javax.swing.*\n \nclass Pentagram : JPanel() {\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n }\n\n private fun drawPentagram(g: Graphics2D, len: Int, x: Int, y: Int,\n fill: Color, stroke: Color) {\n var x2 = x.toDouble()\n var y2 = y.toDouble()\n var angle = 0.0\n val p = Path2D.Float() \n p.moveTo(x2, y2)\n \n for (i in 0..4) {\n x2 += Math.cos(angle) * len\n y2 += Math.sin(-angle) * len\n p.lineTo(x2, y2)\n angle -= Math.toRadians(144.0)\n }\n\n p.closePath()\n with(g) {\n color = fill\n fill(p)\n color = stroke\n draw(p)\n }\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n g.stroke = BasicStroke(5.0f, BasicStroke.CAP_ROUND, 0)\n drawPentagram(g, 500, 70, 250, Color(0x6495ED), Color.darkGray)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with(f) { \n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Pentagram\"\n isResizable = false\n add(Pentagram(), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "Pentomino tiling", "language": "Kotlin from Java", "task": "A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes, \nif you don't count rotations and reflections. Most pentominoes can form their own mirror image through \nrotation, but some of them have to be flipped over.\n\n I \n I L N Y \n FF I L NN PP TTT V W X YY ZZ\nFF I L N PP T U U V WW XXX Y Z \n F I LL N P T UUU VVV WW X Y ZZ \n\n\nA Pentomino tiling is an example of an exact cover problem and can take on many forms. \nA traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered \nby the 12 pentomino shapes, without overlaps, with every shape only used once.\n\nThe 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.\n\n\n;Task\nCreate an 8 by 8 tiling and print the result.\n\n\n;Example\n\nF I I I I I L N\nF F F L L L L N\nW F - X Z Z N N\nW W X X X Z N V\nT W W X - Z Z V\nT T T P P V V V\nT Y - P P U U U\nY Y Y Y P U - U\n\n\n;Related tasks\n* Free polyominoes enumeration\n\n", "solution": "// Version 1.1.4-3\n\nimport java.util.Random\n\nval F = arrayOf(\n intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0),\n intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0),\n intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1), \n intArrayOf(1, -1, 1, 0, 1, 1, 2, -1), intArrayOf(1, -1, 1, 0, 2, 0, 2, 1)\n)\n\nval I = arrayOf(\n intArrayOf(0, 1, 0, 2, 0, 3, 0, 4), intArrayOf(1, 0, 2, 0, 3, 0, 4, 0)\n)\n\nval L = arrayOf(\n intArrayOf(1, 0, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, 0, 3, -1, 3, 0),\n intArrayOf(0, 1, 0, 2, 0, 3, 1, 3), intArrayOf(0, 1, 1, 0, 2, 0, 3, 0),\n intArrayOf(0, 1, 1, 1, 2, 1, 3, 1), intArrayOf(0, 1, 0, 2, 0, 3, 1, 0),\n intArrayOf(1, 0, 2, 0, 3, 0, 3, 1), intArrayOf(1, -3, 1, -2, 1, -1, 1, 0)\n)\n\nval N = arrayOf(\n intArrayOf(0, 1, 1, -2, 1, -1, 1, 0), intArrayOf(1, 0, 1, 1, 2, 1, 3, 1),\n intArrayOf(0, 1, 0, 2, 1, -1, 1, 0), intArrayOf(1, 0, 2, 0, 2, 1, 3, 1),\n intArrayOf(0, 1, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, -1, 2, 0, 3, -1), \n intArrayOf(0, 1, 0, 2, 1, 2, 1, 3), intArrayOf(1, -1, 1, 0, 2, -1, 3, -1)\n)\n\nval P = arrayOf(\n intArrayOf(0, 1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 0, 2, 1, 0, 1, 1),\n intArrayOf(1, 0, 1, 1, 2, 0, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 1, 1),\n intArrayOf(0, 1, 1, 0, 1, 1, 1, 2), intArrayOf(1, -1, 1, 0, 2, -1, 2, 0),\n intArrayOf(0, 1, 0, 2, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 1, 1, 2, 0)\n)\n\nval T = arrayOf(\n intArrayOf(0, 1, 0, 2, 1, 1, 2, 1), intArrayOf(1, -2, 1, -1, 1, 0, 2, 0),\n intArrayOf(1, 0, 2, -1, 2, 0, 2, 1), intArrayOf(1, 0, 1, 1, 1, 2, 2, 0)\n)\n\nval U = arrayOf(\n intArrayOf(0, 1, 0, 2, 1, 0, 1, 2), intArrayOf(0, 1, 1, 1, 2, 0, 2, 1),\n intArrayOf(0, 2, 1, 0, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 2, 0, 2, 1)\n)\n\nval V = arrayOf(\n intArrayOf(1, 0, 2, 0, 2, 1, 2, 2), intArrayOf(0, 1, 0, 2, 1, 0, 2, 0),\n intArrayOf(1, 0, 2, -2, 2, -1, 2, 0), intArrayOf(0, 1, 0, 2, 1, 2, 2, 2)\n)\n\nval W = arrayOf(\n intArrayOf(1, 0, 1, 1, 2, 1, 2, 2), intArrayOf(1, -1, 1, 0, 2, -2, 2, -1),\n intArrayOf(0, 1, 1, 1, 1, 2, 2, 2), intArrayOf(0, 1, 1, -1, 1, 0, 2, -1)\n)\n\nval X = arrayOf(intArrayOf(1, -1, 1, 0, 1, 1, 2, 0))\n\nval Y = arrayOf(\n intArrayOf(1, -2, 1, -1, 1, 0, 1, 1), intArrayOf(1, -1, 1, 0, 2, 0, 3, 0),\n intArrayOf(0, 1, 0, 2, 0, 3, 1, 1), intArrayOf(1, 0, 2, 0, 2, 1, 3, 0),\n intArrayOf(0, 1, 0, 2, 0, 3, 1, 2), intArrayOf(1, 0, 1, 1, 2, 0, 3, 0),\n intArrayOf(1, -1, 1, 0, 1, 1, 1, 2), intArrayOf(1, 0, 2, -1, 2, 0, 3, 0)\n)\n\nval Z = arrayOf(\n intArrayOf(0, 1, 1, 0, 2, -1, 2, 0), intArrayOf(1, 0, 1, 1, 1, 2, 2, 2),\n intArrayOf(0, 1, 1, 1, 2, 1, 2, 2), intArrayOf(1, -2, 1, -1, 1, 0, 2, -2)\n)\n\nval shapes = arrayOf(F, I, L, N, P, T, U, V, W, X, Y, Z)\nval rand = Random()\n\nval symbols = \"FILNPTUVWXYZ-\".toCharArray()\n\nval nRows = 8\nval nCols = 8\nval blank = 12\n\nval grid = Array(nRows) { IntArray(nCols) }\nval placed = BooleanArray(symbols.size - 1)\n\nfun tryPlaceOrientation(o: IntArray, r: Int, c: Int, shapeIndex: Int): Boolean {\n for (i in 0 until o.size step 2) {\n val x = c + o[i + 1]\n val y = r + o[i]\n if (x !in (0 until nCols) || y !in (0 until nRows) || grid[y][x] != - 1) return false\n }\n grid[r][c] = shapeIndex\n for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex\n return true\n}\n\nfun removeOrientation(o: IntArray, r: Int, c: Int) {\n grid[r][c] = -1\n for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = -1\n}\n\nfun solve(pos: Int, numPlaced: Int): Boolean {\n if (numPlaced == shapes.size) return true\n val row = pos / nCols\n val col = pos % nCols\n if (grid[row][col] != -1) return solve(pos + 1, numPlaced)\n\n for (i in 0 until shapes.size) {\n if (!placed[i]) {\n for (orientation in shapes[i]) {\n if (!tryPlaceOrientation(orientation, row, col, i)) continue\n placed[i] = true\n if (solve(pos + 1, numPlaced + 1)) return true\n removeOrientation(orientation, row, col)\n placed[i] = false\n }\n }\n }\n return false\n}\n\nfun shuffleShapes() {\n var n = shapes.size\n while (n > 1) {\n val r = rand.nextInt(n--)\n val tmp = shapes[r]\n shapes[r] = shapes[n]\n shapes[n] = tmp\n val tmpSymbol= symbols[r]\n symbols[r] = symbols[n]\n symbols[n] = tmpSymbol\n }\n}\n\nfun printResult() {\n for (r in grid) {\n for (i in r) print(\"${symbols[i]} \")\n println()\n }\n}\n\nfun main(args: Array) {\n shuffleShapes()\n for (r in 0 until nRows) grid[r].fill(-1)\n for (i in 0..3) {\n var randRow: Int\n var randCol: Int\n do {\n randRow = rand.nextInt(nRows)\n randCol = rand.nextInt(nCols)\n }\n while (grid[randRow][randCol] == blank)\n grid[randRow][randCol] = blank\n }\n if (solve(0, 0)) printResult()\n else println(\"No solution\")\n}"} {"title": "Perfect shuffle", "language": "Kotlin", "task": "A perfect shuffle (or faro/weave shuffle) means splitting a deck of cards into equal halves, and perfectly interleaving them - so that you end up with the first card from the left half, followed by the first card from the right half, and so on:\n\n\n\n::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K\n\n\n\nWhen you repeatedly perform perfect shuffles on an even-sized deck of unique cards, it will at some point arrive back at its original order. How many shuffles this takes, depends solely on the number of cards in the deck - for example for a deck of eight cards it takes three shuffles:\n\n\n\n::::: {| style=\"border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right\"\n|-\n| ''original:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|-\n| ''after 1st shuffle:'' ||\n1\n5\n2\n6\n3\n7\n4\n8\n|-\n| ''after 2nd shuffle:'' ||\n1\n3\n5\n7\n2\n4\n6\n8\n|-\n| ''after 3rd shuffle:'' ||\n1\n2\n3\n4\n5\n6\n7\n8\n|}\n\n\n'''''The Task'''''\n\n# Write a function that can perform a perfect shuffle on an even-sized list of values.\n# Call this function repeatedly to count how many shuffles are needed to get a deck back to its original order, for each of the deck sizes listed under \"Test Cases\" below.\n#* You can use a list of numbers (or anything else that's convenient) to represent a deck; just make sure that all \"cards\" are unique within each deck.\n#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.\n'''''Test Cases'''''\n\n::::: {| class=\"wikitable\"\n|-\n! input ''(deck size)'' !! output ''(number of shuffles required)''\n|-\n| 8 || 3\n|-\n| 24 || 11\n|-\n| 52 || 8\n|-\n| 100 || 30\n|-\n| 1020 || 1018\n|-\n| 1024 || 10\n|-\n| 10000 || 300\n|}\n\n", "solution": "// version 1.1.2\n\nfun areSame(a: IntArray, b: IntArray): Boolean {\n for (i in 0 until a.size) if (a[i] != b[i]) return false\n return true\n}\n\nfun perfectShuffle(a: IntArray): IntArray {\n var b = IntArray(a.size)\n val hSize = a.size / 2\n for (i in 0 until hSize) b[i * 2] = a[i]\n var j = 1\n for (i in hSize until a.size) {\n b[j] = a[i]\n j += 2\n }\n return b\n}\n\nfun countShuffles(a: IntArray): Int {\n require(a.size >= 2 && a.size % 2 == 0)\n var b = a\n var count = 0\n while (true) {\n val c = perfectShuffle(b)\n count++\n if (areSame(a, c)) return count\n b = c\n }\n}\n\nfun main(args: Array) {\n println(\"Deck size Num shuffles\")\n println(\"--------- ------------\")\n val sizes = intArrayOf(8, 24, 52, 100, 1020, 1024, 10000)\n for (size in sizes) {\n val a = IntArray(size) { it }\n val count = countShuffles(a)\n println(\"${\"%-9d\".format(size)} $count\")\n }\n}"} {"title": "Perfect totient numbers", "language": "Kotlin from Go", "task": "Generate and show here, the first twenty Perfect totient numbers.\n\n\n;Related task:\n::* [[Totient function]]\n\n\n;Also see:\n::* the OEIS entry for perfect totient numbers.\n::* mrob list of the first 54\n\n", "solution": "// Version 1.3.21\n\nfun totient(n: Int): Int {\n var tot = n\n var nn = n\n var i = 2\n while (i * i <= nn) {\n if (nn % i == 0) {\n while (nn % i == 0) nn /= i\n tot -= tot / i\n }\n if (i == 2) i = 1\n i += 2\n }\n if (nn > 1) tot -= tot / nn\n return tot\n}\n\nfun main() {\n val perfect = mutableListOf()\n var n = 1\n while (perfect.size < 20) {\n var tot = n\n var sum = 0\n while (tot != 1) {\n tot = totient(tot)\n sum += tot\n }\n if (sum == n) perfect.add(n)\n n += 2\n }\n println(\"The first 20 perfect totient numbers are:\")\n println(perfect)\n}"} {"title": "Perlin noise", "language": "Kotlin from Java", "task": "The '''computer graphics, most notably to procedurally generate textures or heightmaps. \n\nThe Perlin noise is basically a pseudo-random mapping of \\R^d into \\R with an integer d which can be arbitrarily large but which is usually 2, 3, or 4.\n\nEither by using a dedicated library or by implementing the algorithm, show that the Perlin noise (as defined in 2002 in the Java implementation below) of the point in 3D-space with coordinates 3.14, 42, 7 is 0.13691995878400012.\n\n\n''Note: this result assumes 64 bit IEEE-754 floating point calculations. If your language uses a different floating point representation, make a note of it and calculate the value accurate to 15 decimal places, or your languages accuracy threshold if it is less. Trailing zeros need not be displayed.''\n\n", "solution": "// version 1.1.3\n\nobject Perlin {\n\n private val permutation = intArrayOf(\n 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,\n 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,\n 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,\n 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, \n 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,\n 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,\n 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,\n 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,\n 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,\n 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,\n 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,\n 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,\n 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,\n 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,\n 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,\n 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180\n )\n\n private val p = IntArray(512) { \n if (it < 256) permutation[it] else permutation[it - 256] \n }\n \n fun noise(x: Double, y: Double, z: Double): Double {\n // Find unit cube that contains point\n val xi = Math.floor(x).toInt() and 255\n val yi = Math.floor(y).toInt() and 255\n val zi = Math.floor(z).toInt() and 255\n\n // Find relative x, y, z of point in cube\n val xx = x - Math.floor(x)\n val yy = y - Math.floor(y)\n val zz = z - Math.floor(z) \n\n // Compute fade curves for each of xx, yy, zz\n val u = fade(xx)\n val v = fade(yy)\n val w = fade(zz)\n\n // Hash co-ordinates of the 8 cube corners \n // and add blended results from 8 corners of cube\n\n val a = p[xi] + yi\n val aa = p[a] + zi\n val ab = p[a + 1] + zi\n val b = p[xi + 1] + yi\n val ba = p[b] + zi\n val bb = p[b + 1] + zi\n \n return lerp(w, lerp(v, lerp(u, grad(p[aa], xx, yy, zz),\n grad(p[ba], xx - 1, yy, zz)),\n lerp(u, grad(p[ab], xx, yy - 1, zz),\n grad(p[bb], xx - 1, yy - 1, zz))),\n lerp(v, lerp(u, grad(p[aa + 1], xx, yy, zz - 1),\n grad(p[ba + 1], xx - 1, yy, zz - 1)),\n lerp(u, grad(p[ab + 1], xx, yy - 1, zz - 1),\n grad(p[bb + 1], xx - 1, yy - 1, zz - 1))))\n }\n\n private fun fade(t: Double) = t * t * t * (t * (t * 6 - 15) + 10)\n\n private fun lerp(t: Double, a: Double, b: Double) = a + t * (b - a) \n\n private fun grad(hash: Int, x: Double, y: Double, z: Double): Double {\n // Convert low 4 bits of hash code into 12 gradient directions\n val h = hash and 15 \n val u = if (h < 8) x else y\n val v = if (h < 4) y else if (h == 12 || h == 14) x else z\n return (if ((h and 1) == 0) u else -u) + \n (if ((h and 2) == 0) v else -v)\n } \n}\n\nfun main(args: Array) {\n println(Perlin.noise(3.14, 42.0, 7.0))\n}"} {"title": "Permutations/Derangements", "language": "Kotlin", "task": "A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.\n\nFor example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).\n\nThe number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. \nThere are various ways to calculate !''n''.\n\n\n;Task:\n# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer). \n# Generate ''and show'' all the derangements of 4 integers using the above routine.\n# Create a function that calculates the subfactorial of ''n'', !''n''.\n# Print and show a table of the ''counted'' number of derangements of ''n'' vs. the calculated !''n'' for n from 0..9 inclusive.\n\n\n;Optional stretch goal:\n* Calculate !''20'' \n\n\n;Related tasks:\n* [[Anagrams/Deranged anagrams]]\n* [[Best shuffle]]\n* [[Left_factorials]]\n\n\n\n", "solution": "// version 1.1.2\n\nfun permute(input: List): List> {\n if (input.size == 1) return listOf(input)\n val perms = mutableListOf>()\n val toInsert = input[0]\n for (perm in permute(input.drop(1))) {\n for (i in 0..perm.size) {\n val newPerm = perm.toMutableList()\n newPerm.add(i, toInsert)\n perms.add(newPerm)\n }\n }\n return perms\n}\n\nfun derange(input: List): List> {\n if (input.isEmpty()) return listOf(input)\n return permute(input).filter { permutation ->\n permutation.filterIndexed { i, index -> i == index }.none()\n }\n}\n\nfun subFactorial(n: Int): Long =\n when (n) {\n 0 -> 1\n 1 -> 0\n else -> (n - 1) * (subFactorial(n - 1) + subFactorial(n - 2))\n }\n\nfun main(args: Array) {\n val input = listOf(0, 1, 2, 3)\n\n val derangements = derange(input)\n println(\"There are ${derangements.size} derangements of $input, namely:\\n\")\n derangements.forEach(::println)\n\n println(\"\\nN Counted Calculated\")\n println(\"- ------- ----------\")\n for (n in 0..9) {\n val list = List(n) { it }\n val counted = derange(list).size\n println(\"%d %-9d %-9d\".format(n, counted, subFactorial(n)))\n }\n println(\"\\n!20 = ${subFactorial(20)}\")\n}"} {"title": "Permutations/Rank of a permutation", "language": "Kotlin from C", "task": "A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items. \nFor our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).\n\nFor example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:\n\n PERMUTATION RANK\n (0, 1, 2, 3) -> 0\n (0, 1, 3, 2) -> 1\n (0, 2, 1, 3) -> 2\n (0, 2, 3, 1) -> 3\n (0, 3, 1, 2) -> 4\n (0, 3, 2, 1) -> 5\n (1, 0, 2, 3) -> 6\n (1, 0, 3, 2) -> 7\n (1, 2, 0, 3) -> 8\n (1, 2, 3, 0) -> 9\n (1, 3, 0, 2) -> 10\n (1, 3, 2, 0) -> 11\n (2, 0, 1, 3) -> 12\n (2, 0, 3, 1) -> 13\n (2, 1, 0, 3) -> 14\n (2, 1, 3, 0) -> 15\n (2, 3, 0, 1) -> 16\n (2, 3, 1, 0) -> 17\n (3, 0, 1, 2) -> 18\n (3, 0, 2, 1) -> 19\n (3, 1, 0, 2) -> 20\n (3, 1, 2, 0) -> 21\n (3, 2, 0, 1) -> 22\n (3, 2, 1, 0) -> 23\n\nAlgorithms exist that can generate a rank from a permutation for some particular ordering of permutations, and that can generate the same rank from the given individual permutation (i.e. given a rank of 17 produce (2, 3, 1, 0) in the example above).\n\nOne use of such algorithms could be in generating a small, random, sample of permutations of n items without duplicates when the total number of permutations is large. Remember that the total number of permutations of n items is given by n! which grows large very quickly: A 32 bit integer can only hold 12!, a 64 bit integer only 20!. It becomes difficult to take the straight-forward approach of generating all permutations then taking a random sample of them.\n\nA question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.\n\n\n;Task:\n# Create a function to generate a permutation from a rank.\n# Create the inverse function that given the permutation generates its rank.\n# Show that for n=3 the two functions are indeed inverses of each other.\n# Compute and show here 4 random, individual, samples of permutations of 12 objects.\n\n\n;Stretch goal:\n* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.\n\n\n;References:\n# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).\n# Ranks on the DevData site.\n# Another answer on Stack Overflow to a different question that explains its algorithm in detail.\n\n;Related tasks:\n#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]\n\n", "solution": "// version 1.1.2\n\nimport java.util.Random\n\nfun IntArray.swap(i: Int, j: Int) {\n val temp = this[i]\n this[i] = this[j]\n this[j] = temp\n}\n\ntailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) {\n if (n < 1) return\n val q = rank / n\n val r = rank % n\n vec.swap(r, n - 1) \n mrUnrank1(q, n - 1, vec)\n}\n\nfun mrRank1(n: Int, vec: IntArray, inv: IntArray): Int {\n if (n < 2) return 0\n val s = vec[n - 1]\n vec.swap(n - 1, inv[n - 1])\n inv.swap(s, n - 1)\n return s + n * mrRank1(n - 1, vec, inv)\n} \n\nfun getPermutation(rank: Int, n: Int, vec: IntArray) {\n for (i in 0 until n) vec[i] = i\n mrUnrank1(rank, n, vec)\n}\n\nfun getRank(n: Int, vec: IntArray): Int {\n val v = IntArray(n)\n val inv = IntArray(n)\n for (i in 0 until n) {\n v[i] = vec[i]\n inv[vec[i]] = i\n }\n return mrRank1(n, v, inv)\n}\n\nfun main(args: Array) {\n var tv = IntArray(3) \n for (r in 0..5) {\n getPermutation(r, 3, tv)\n System.out.printf(\"%2d -> %s -> %d\\n\", r, tv.contentToString(), getRank(3, tv))\n }\n println()\n tv = IntArray(4) \n for (r in 0..23) {\n getPermutation(r, 4, tv)\n System.out.printf(\"%2d -> %s -> %d\\n\", r, tv.contentToString(), getRank(4, tv))\n }\n\n println()\n tv = IntArray(12)\n val a = IntArray(4)\n val rand = Random()\n val fact12 = (2..12).fold(1) { acc, i -> acc * i }\n for (i in 0..3) a[i] = rand.nextInt(fact12)\n for (r in a) {\n getPermutation(r, 12, tv)\n System.out.printf(\"%9d -> %s -> %d\\n\", r, tv.contentToString(), getRank(12, tv))\n }\n}"} {"title": "Permutations by swapping", "language": "Kotlin", "task": "Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items. \n\nAlso generate the sign of the permutation which is +1 when the permutation is generated from an even number of swaps from the initial state, and -1 for odd. \n\nShow the permutations and signs of three items, in order of generation ''here''.\n\nSuch data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.\n\nNote: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.\n\n\n;References:\n* Steinhaus-Johnson-Trotter algorithm\n* Johnson-Trotter Algorithm Listing All Permutations\n* Heap's algorithm\n* Tintinnalogia\n\n\n;Related tasks:\n* [[Matrix arithmetic]\n* [[Gray code]]\n\n", "solution": "// version 1.1.2\n\nfun johnsonTrotter(n: Int): Pair, List> {\n val p = IntArray(n) { it } // permutation\n val q = IntArray(n) { it } // inverse permutation\n val d = IntArray(n) { -1 } // direction = 1 or -1\n var sign = 1\n val perms = mutableListOf()\n val signs = mutableListOf()\n\n fun permute(k: Int) {\n if (k >= n) {\n perms.add(p.copyOf())\n signs.add(sign)\n sign *= -1\n return\n } \n permute(k + 1)\n for (i in 0 until k) {\n val z = p[q[k] + d[k]]\n p[q[k]] = z\n p[q[k] + d[k]] = k\n q[z] = q[k]\n q[k] += d[k]\n permute(k + 1)\n }\n d[k] *= -1\n } \n\n permute(0)\n return perms to signs\n}\n\nfun printPermsAndSigns(perms: List, signs: List) {\n for ((i, perm) in perms.withIndex()) {\n println(\"${perm.contentToString()} -> sign = ${signs[i]}\")\n }\n}\n\nfun main(args: Array) {\n val (perms, signs) = johnsonTrotter(3)\n printPermsAndSigns(perms, signs)\n println()\n val (perms2, signs2) = johnsonTrotter(4)\n printPermsAndSigns(perms2, signs2)\n}"} {"title": "Phrase reversals", "language": "Kotlin", "task": "Given a string of space separated words containing the following phrase:\n rosetta code phrase reversal\n\n:# Reverse the characters of the string.\n:# Reverse the characters of each individual word in the string, maintaining original word order within the string.\n:# Reverse the order of each word of the string, maintaining the order of characters in each word.\n\nShow your output here.\n \n\n\n", "solution": "// version 1.0.6\n\nfun reverseEachWord(s: String) = s.split(\" \").map { it.reversed() }.joinToString(\" \")\n\nfun main(args: Array) {\n val original = \"rosetta code phrase reversal\"\n val reversed = original.reversed()\n println(\"Original string => $original\")\n println(\"Reversed string => $reversed\")\n println(\"Reversed words => ${reverseEachWord(original)}\")\n println(\"Reversed order => ${reverseEachWord(reversed)}\")\n}"} {"title": "Pig the dice game", "language": "Kotlin", "task": "The game of Pig is a multiplayer game played with a single six-sided die. The\nobject of the game is to reach '''100''' points or more. \nPlay is taken in turns. On each person's turn that person has the option of either:\n\n:# '''Rolling the dice''': where a roll of two to six is added to their score for that turn and the player's turn continues as the player is given the same choice again; or a roll of '''1''' loses the player's total points ''for that turn'' and their turn finishes with play passing to the next player.\n:# '''Holding''': the player's score for that round is added to their total and becomes safe from the effects of throwing a '''1''' (one). The player's turn finishes with play passing to the next player.\n\n\n;Task:\nCreate a program to score for, and simulate dice throws for, a two-person game. \n\n\n;Related task:\n* [[Pig the dice game/Player]]\n\n", "solution": "// version 1.1.2\n\nfun main(Args: Array) {\n print(\"Player 1 - Enter your name : \")\n val name1 = readLine()!!.trim().let { if (it == \"\") \"PLAYER 1\" else it.toUpperCase() }\n print(\"Player 2 - Enter your name : \")\n val name2 = readLine()!!.trim().let { if (it == \"\") \"PLAYER 2\" else it.toUpperCase() }\n val names = listOf(name1, name2)\n val r = java.util.Random()\n val totals = intArrayOf(0, 0)\n var player = 0\n while (true) {\n println(\"\\n${names[player]}\")\n println(\" Your total score is currently ${totals[player]}\")\n var score = 0\n while (true) {\n print(\" Roll or Hold r/h : \") \n val rh = readLine()!![0].toLowerCase()\n if (rh == 'h') {\n totals[player] += score\n println(\" Your total score is now ${totals[player]}\")\n if (totals[player] >= 100) {\n println(\" So, ${names[player]}, YOU'VE WON!\")\n return\n } \n player = if (player == 0) 1 else 0\n break\n }\n if (rh != 'r') {\n println(\" Must be 'r'or 'h', try again\")\n continue\n } \n val dice = 1 + r.nextInt(6)\n println(\" You have thrown a $dice\") \n if (dice == 1) {\n println(\" Sorry, your score for this round is now 0\")\n println(\" Your total score remains at ${totals[player]}\")\n player = if (player == 0) 1 else 0\n break\n }\n score += dice \n println(\" Your score for the round is now $score\")\n } \n }\n}"} {"title": "Plasma effect", "language": "Kotlin from Java", "task": "The plasma effect is a visual effect created by applying various functions, notably sine and cosine, to the color values of screen pixels. When animated (not a task requirement) the effect may give the impression of a colorful flowing liquid.\n\n\n;Task\nCreate a plasma effect.\n\n\n;See also\n* Computer Graphics Tutorial (lodev.org)\n* Plasma (bidouille.org)\n\n", "solution": "// version 1.1.2\n\nimport java.awt.*\nimport java.awt.image.BufferedImage\nimport javax.swing.*\n\nclass PlasmaEffect : JPanel() {\n private val plasma: Array\n private var hueShift = 0.0f\n private val img: BufferedImage\n\n init {\n val dim = Dimension(640, 640)\n preferredSize = dim\n background = Color.white\n img = BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB)\n plasma = createPlasma(dim.height, dim.width)\n // animate about 24 fps and shift hue value with every frame\n Timer(42) {\n hueShift = (hueShift + 0.02f) % 1\n repaint()\n }.start()\n }\n\n private fun createPlasma(w: Int, h: Int): Array {\n val buffer = Array(h) { FloatArray(w) }\n for (y in 0 until h)\n for (x in 0 until w) {\n var value = Math.sin(x / 16.0)\n value += Math.sin(y / 8.0)\n value += Math.sin((x + y) / 16.0)\n value += Math.sin(Math.sqrt((x * x + y * y).toDouble()) / 8.0)\n value += 4.0 // shift range from -4 .. 4 to 0 .. 8\n value /= 8.0 // bring range down to 0 .. 1\n if (value < 0.0 || value > 1.0) throw RuntimeException(\"Hue value out of bounds\")\n buffer[y][x] = value.toFloat()\n }\n return buffer\n }\n\n private fun drawPlasma(g: Graphics2D) {\n val h = plasma.size\n val w = plasma[0].size\n for (y in 0 until h)\n for (x in 0 until w) {\n val hue = hueShift + plasma[y][x] % 1\n img.setRGB(x, y, Color.HSBtoRGB(hue, 1.0f, 1.0f))\n }\n g.drawImage(img, 0, 0, null)\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n drawPlasma(g);\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Plasma Effect\"\n f.isResizable = false\n f.add(PlasmaEffect(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}"} {"title": "Playfair cipher", "language": "Kotlin from FreeBASIC", "task": "Implement a Playfair cipher for encryption and decryption.\n\n\nThe user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.\n\nThe output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.\n\n\n;Output example:\n HI DE TH EG OL DI NT HE TR EX ES TU MP\n\n", "solution": "// version 1.0.5-2\n\nenum class PlayfairOption {\n NO_Q, \n I_EQUALS_J\n}\n\nclass Playfair(keyword: String, val pfo: PlayfairOption) {\n private val table: Array = Array(5, { CharArray(5) }) // 5 x 5 char array\n\n init {\n // build table\n val used = BooleanArray(26) // all elements false \n if (pfo == PlayfairOption.NO_Q) \n used[16] = true // Q used\n else\n used[9] = true // J used\n val alphabet = keyword.toUpperCase() + \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n var i = 0\n var j = 0\n var c: Char\n var d: Int\n for (k in 0 until alphabet.length) {\n c = alphabet[k]\n if (c !in 'A'..'Z') continue\n d = c.toInt() - 65\n if (!used[d]) {\n table[i][j] = c\n used[d] = true\n if (++j == 5) { \n if (++i == 5) break // table has been filled \n j = 0\n }\n } \n }\n }\n \n private fun getCleanText(plainText: String): String {\n val plainText2 = plainText.toUpperCase() // ensure everything is upper case\n // get rid of any non-letters and insert X between duplicate letters\n var cleanText = \"\"\n var prevChar = '\\u0000' // safe to assume null character won't be present in plainText\n var nextChar: Char\n for (i in 0 until plainText2.length) {\n nextChar = plainText2[i]\n // It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway\n if (nextChar !in 'A'..'Z' || (nextChar == 'Q' && pfo == PlayfairOption.NO_Q)) continue\n // If I_EQUALS_J option specified, replace J with I\n if (nextChar == 'J' && pfo == PlayfairOption.I_EQUALS_J) nextChar = 'I'\n if (nextChar != prevChar)\n cleanText += nextChar\n else\n cleanText += \"X\" + nextChar\n prevChar = nextChar\n } \n val len = cleanText.length\n if (len % 2 == 1) { // dangling letter at end so add another letter to complete digram\n if (cleanText[len - 1] != 'X')\n cleanText += 'X'\n else \n cleanText += 'Z'\n }\n return cleanText \n }\n\n private fun findChar(c: Char): Pair {\n for (i in 0..4)\n for (j in 0..4)\n if (table[i][j] == c) return Pair(i, j)\n return Pair(-1, -1)\n }\n\n fun encode(plainText: String): String {\n val cleanText = getCleanText(plainText)\n var cipherText = \"\"\n val length = cleanText.length\n for (i in 0 until length step 2) {\n val (row1, col1) = findChar(cleanText[i])\n val (row2, col2) = findChar(cleanText[i + 1]) \n cipherText += when {\n row1 == row2 -> table[row1][(col1 + 1) % 5].toString() + table[row2][(col2 + 1) % 5]\n col1 == col2 -> table[(row1 + 1) % 5][col1].toString() + table[(row2 + 1) % 5][col2]\n else -> table[row1][col2].toString() + table[row2][col1]\n }\n if (i < length - 1) cipherText += \" \" \n }\n return cipherText\n }\n\n fun decode(cipherText: String): String {\n var decodedText = \"\"\n val length = cipherText.length\n for (i in 0 until length step 3) { // cipherText will include spaces so we need to skip them\n val (row1, col1) = findChar(cipherText[i])\n val (row2, col2) = findChar(cipherText[i + 1]) \n decodedText += when {\n row1 == row2 -> table[row1][if (col1 > 0) col1 - 1 else 4].toString() + table[row2][if (col2 > 0) col2 - 1 else 4]\n col1 == col2 -> table[if (row1 > 0) row1- 1 else 4][col1].toString() + table[if (row2 > 0) row2 - 1 else 4][col2]\n else -> table[row1][col2].toString() + table[row2][col1]\n }\n if (i < length - 1) decodedText += \" \"\n }\n return decodedText\n } \n\n fun printTable() {\n println(\"The table to be used is :\\n\")\n for (i in 0..4) {\n for (j in 0..4) print(table[i][j] + \" \")\n println()\n }\n }\n}\n\nfun main(args: Array) {\n print(\"Enter Playfair keyword : \")\n val keyword: String = readLine()!!\n var ignoreQ: String\n do {\n print(\"Ignore Q when buiding table y/n : \")\n ignoreQ = readLine()!!.toLowerCase() \n }\n while (ignoreQ != \"y\" && ignoreQ != \"n\")\n val pfo = if (ignoreQ == \"y\") PlayfairOption.NO_Q else PlayfairOption.I_EQUALS_J\n val playfair = Playfair(keyword, pfo)\n playfair.printTable()\n print(\"\\nEnter plain text : \")\n val plainText: String = readLine()!!\n val encodedText = playfair.encode(plainText)\n println(\"\\nEncoded text is : $encodedText\") \n val decodedText = playfair.decode(encodedText)\n println(\"Decoded text is : $decodedText\")\n}"} {"title": "Plot coordinate pairs", "language": "Kotlin from Groovy", "task": "Plot a function represented as x, y numerical arrays.\n\nPost the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):\n x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};\n y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "// Version 1.2.31\n\nimport org.jfree.chart.ChartFactory\nimport org.jfree.chart.ChartPanel\nimport org.jfree.data.xy.XYSeries\nimport org.jfree.data.xy.XYSeriesCollection\nimport org.jfree.chart.plot.PlotOrientation\nimport javax.swing.JFrame\nimport javax.swing.SwingUtilities\nimport java.awt.BorderLayout\n\nfun main(args: Array) {\n val x = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n val y = doubleArrayOf(\n 2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0\n )\n val series = XYSeries(\"plots\")\n (0 until x.size).forEach { series.add(x[it], y[it]) }\n val labels = arrayOf(\"Plot Demo\", \"X\", \"Y\")\n val data = XYSeriesCollection(series)\n val options = booleanArrayOf(false, true, false)\n val orient = PlotOrientation.VERTICAL\n val chart = ChartFactory.createXYLineChart(\n labels[0], labels[1], labels[2], data, orient, options[0], options[1], options[2]\n )\n val chartPanel = ChartPanel(chart)\n SwingUtilities.invokeLater {\n val f = JFrame()\n with(f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n add(chartPanel, BorderLayout.CENTER)\n title = \"Plot coordinate pairs\"\n isResizable = false\n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "Poker hand analyser", "language": "Kotlin", "task": "Create a program to parse a single five card poker hand and rank it according to this list of poker hands.\n\n\nA poker hand is specified as a space separated list of five playing cards. \n\nEach input card has two characters indicating face and suit. \n\n\n;Example:\n::::'''2d''' (two of diamonds).\n\n\n\nFaces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''\n\nSuits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or \nalternatively, the unicode card-suit characters: \n\n\nDuplicate cards are illegal.\n\nThe program should analyze a single hand and produce one of the following outputs:\n straight-flush\n four-of-a-kind\n full-house\n flush\n straight\n three-of-a-kind\n two-pair\n one-pair\n high-card\n invalid\n\n\n;Examples:\n 2 2 2 k q: three-of-a-kind\n 2 5 7 8 9: high-card\n a 2 3 4 5: straight\n 2 3 2 3 3: full-house\n 2 7 2 3 3: two-pair\n 2 7 7 7 7: four-of-a-kind \n 10 j q k a: straight-flush\n 4 4 k 5 10: one-pair\n q 10 7 6 q: invalid\n\nThe programs output for the above examples should be displayed here on this page.\n\n\n;Extra credit:\n# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).\n# allow two jokers\n::* use the symbol '''joker'''\n::* duplicates would be allowed (for jokers only)\n::* five-of-a-kind would then be the highest hand\n\n\n;More extra credit examples:\n joker 2 2 k q: three-of-a-kind\n joker 5 7 8 9: straight\n joker 2 3 4 5: straight\n joker 3 2 3 3: four-of-a-kind\n joker 7 2 3 3: three-of-a-kind\n joker 7 7 7 7: five-of-a-kind\n joker j q k A: straight-flush\n joker 4 k 5 10: one-pair\n joker k 7 6 4: flush\n joker 2 joker 4 5: straight\n joker Q joker A 10: straight\n joker Q joker A 10: straight-flush\n joker 2 2 joker q: four-of-a-kind\n\n\n;Related tasks:\n* [[Playing cards]]\n* [[Card shuffles]]\n* [[Deal cards_for_FreeCell]]\n* [[War Card_Game]]\n* [[Go Fish]]\n\n", "solution": "// version 1.1.2\n\nclass Card(val face: Int, val suit: Char)\n\nconst val FACES = \"23456789tjqka\"\nconst val SUITS = \"shdc\"\n\nfun isStraight(cards: List): Boolean {\n val sorted = cards.sortedBy { it.face }\n if (sorted[0].face + 4 == sorted[4].face) return true\n if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5) return true \n return false\n}\n\nfun isFlush(cards: List): Boolean {\n val suit = cards[0].suit\n if (cards.drop(1).all { it.suit == suit }) return true \n return false\n}\n\nfun analyzeHand(hand: String): String {\n val h = hand.toLowerCase()\n val split = h.split(' ').filterNot { it == \"\" }.distinct()\n if (split.size != 5) return \"invalid\"\n val cards = mutableListOf()\n\n for (s in split) {\n if (s.length != 2) return \"invalid\" \n val fIndex = FACES.indexOf(s[0])\n if (fIndex == -1) return \"invalid\"\n val sIndex = SUITS.indexOf(s[1])\n if (sIndex == -1) return \"invalid\"\n cards.add(Card(fIndex + 2, s[1]))\n } \n \n val groups = cards.groupBy { it.face }\n when (groups.size) {\n 2 -> {\n if (groups.any { it.value.size == 4 }) return \"four-of-a-kind\"\n return \"full-house\"\n }\n 3 -> {\n if (groups.any { it.value.size == 3 }) return \"three-of-a-kind\"\n return \"two-pair\"\n }\n 4 -> return \"one-pair\" \n else -> {\n val flush = isFlush(cards)\n val straight = isStraight(cards)\n when {\n flush && straight -> return \"straight-flush\"\n flush -> return \"flush\"\n straight -> return \"straight\"\n else -> return \"high-card\"\n }\n }\n } \n} \n\nfun main(args: Array) {\n val hands = arrayOf(\n \"2h 2d 2c kc qd\",\n \"2h 5h 7d 8c 9s\",\n \"ah 2d 3c 4c 5d\",\n \"2h 3h 2d 3c 3d\",\n \"2h 7h 2d 3c 3d\",\n \"2h 7h 7d 7c 7s\",\n \"th jh qh kh ah\",\n \"4h 4s ks 5d ts\",\n \"qc tc 7c 6c 4c\",\n \"ah ah 7c 6c 4c\"\n )\n for (hand in hands) {\n println(\"$hand: ${analyzeHand(hand)}\")\n } \n}"} {"title": "Polyspiral", "language": "Kotlin from Java", "task": "A Polyspiral is a spiral made of multiple line segments, whereby each segment is larger (or smaller) than the previous one by a given amount. Each segment also changes direction at a given angle. \n\n\n;Task\nAnimate a series of polyspirals, by drawing a complete spiral then incrementing the angle, and (after clearing the background) drawing the next, and so on. Every spiral will be a frame of the animation. The animation may stop as it goes full circle or continue indefinitely. The given input values may be varied.\n\nIf animation is not practical in your programming environment, you may show a single frame instead.\n\n\n;Pseudo code\n\n set incr to 0.0\n\n // animation loop\n WHILE true \n\n incr = (incr + 0.05) MOD 360\n x = width / 2\n y = height / 2\n length = 5\n angle = incr\n\n // spiral loop\n FOR 1 TO 150\n drawline\n change direction by angle\n length = length + 3\n angle = (angle + incr) MOD 360\n ENDFOR\n \n\n\n", "solution": "// version 1.1.0\n\nimport java.awt.*\nimport java.awt.event.ActionEvent\nimport javax.swing.*\n\nclass PolySpiral() : JPanel() {\n private var inc = 0.0\n\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n Timer(40) {\n inc = (inc + 0.05) % 360.0\n repaint()\n }.start()\n }\n\n private fun drawSpiral(g: Graphics2D, length: Int, angleIncrement: Double) {\n var x1 = width / 2.0\n var y1 = height / 2.0\n var len = length\n var angle = angleIncrement \n for (i in 0 until 150) {\n g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f))\n val x2 = x1 + Math.cos(angle) * len\n val y2 = y1 - Math.sin(angle) * len\n g.drawLine(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt())\n x1 = x2\n y1 = y2\n len += 3\n angle = (angle + angleIncrement) % (Math.PI * 2.0)\n }\n }\n\n override protected fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) \n drawSpiral(g, 5, Math.toRadians(inc))\n } \n} \n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"PolySpiral\"\n f.setResizable(true)\n f.add(PolySpiral(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.setVisible(true)\n }\n}"} {"title": "Population count", "language": "Kotlin", "task": "The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.\n\n''Population count'' is also known as:\n::::* ''pop count''\n::::* ''popcount'' \n::::* ''sideways sum''\n::::* ''bit summation'' \n::::* ''Hamming weight'' \n\n\nFor example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.\n\n\n''Evil numbers'' are non-negative integers that have an ''even'' population count.\n\n''Odious numbers'' are positive integers that have an ''odd'' population count.\n\n\n;Task:\n* write a function (or routine) to return the population count of a non-negative integer.\n* all computation of the lists below should start with '''0''' (zero indexed).\n:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').\n:* display the 1st thirty ''evil'' numbers.\n:* display the 1st thirty ''odious'' numbers.\n* display each list of integers on one line (which may or may not include a title), each set of integers being shown should be properly identified.\n\n\n;See also\n* The On-Line Encyclopedia of Integer Sequences: A000120 population count.\n* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.\n* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.\n\n", "solution": "// version 1.0.6\n\nfun popCount(n: Long) = when {\n n < 0L -> throw IllegalArgumentException(\"n must be non-negative\")\n else -> java.lang.Long.bitCount(n)\n}\n\nfun main(args: Array) {\n println(\"The population count of the first 30 powers of 3 are:\")\n var pow3 = 1L\n for (i in 1..30) {\n print(\"${popCount(pow3)} \")\n pow3 *= 3L\n }\n println(\"\\n\")\n println(\"The first thirty evil numbers are:\")\n var count = 0\n var i = 0\n while (true) {\n val pc = popCount(i.toLong())\n if (pc % 2 == 0) {\n print(\"$i \")\n if (++count == 30) break\n }\n i++\n }\n println(\"\\n\")\n println(\"The first thirty odious numbers are:\")\n count = 0\n i = 1\n while (true) {\n val pc = popCount(i.toLong())\n if (pc % 2 == 1) {\n print(\"$i \")\n if (++count == 30) break\n }\n i++\n }\n println() \n}"} {"title": "Pragmatic directives", "language": "Kotlin", "task": "Pragmatic directives cause the language to operate in a specific manner, allowing support for operational variances within the program code (possibly by the loading of specific or alternative modules).\n\n\n;Task:\nList any pragmatic directives supported by the language, and demonstrate how to activate and deactivate the pragmatic directives and to describe or demonstrate the scope of effect that the pragmatic directives have within a program.\n\n", "solution": "// version 1.0.6\n\n@Suppress(\"UNUSED_VARIABLE\")\n\nfun main(args: Array) {\n val s = \"To be suppressed\"\n}"} {"title": "Priority queue", "language": "Kotlin from Java", "task": "A queue, with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.\n\n\n;Task:\nCreate a priority queue. The queue must support at least two operations:\n:# Insertion. An element is added to the queue with a priority (a numeric value).\n:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.\n\n\nOptionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.\n\n\nTo test your implementation, insert a number of elements into the queue, each with some random priority. \n\nThen dequeue them sequentially; now the elements should be sorted by priority. \n\nYou can use the following task/priority items as input data:\n '''Priority''' '''Task'''\n ---------- ----------------\n 3 Clear drains\n 4 Feed cat\n 5 Make tea\n 1 Solve RC tasks\n 2 Tax return\n\n\nThe implementation should try to be efficient. A typical implementation has '''O(log n)''' insertion and extraction time, where '''n''' is the number of items in the queue. \n\nYou may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.\n\n", "solution": "import java.util.PriorityQueue\n\ninternal data class Task(val priority: Int, val name: String) : Comparable {\n override fun compareTo(other: Task) = when {\n priority < other.priority -> -1\n priority > other.priority -> 1\n else -> 0\n }\n}\n\nprivate infix fun String.priority(priority: Int) = Task(priority, this)\n\nfun main(args: Array) {\n val q = PriorityQueue(listOf(\"Clear drains\" priority 3,\n \"Feed cat\" priority 4,\n \"Make tea\" priority 5,\n \"Solve RC tasks\" priority 1,\n \"Tax return\" priority 2))\n while (q.any()) println(q.remove())\n}"} {"title": "Pseudo-random numbers/Combined recursive generator MRG32k3a", "language": "Kotlin from C++", "task": "MRG32k3a Combined recursive generator (pseudo-code):\n\n /* Constants */\n /* First generator */\n a1 = [0, 1403580, -810728]\n m1 = 2**32 - 209\n /* Second Generator */\n a2 = [527612, 0, -1370589]\n m2 = 2**32 - 22853\n \n d = m1 + 1\n \n class MRG32k3a\n x1 = [0, 0, 0] /* list of three last values of gen #1 */\n x2 = [0, 0, 0] /* list of three last values of gen #2 */\n \n method seed(u64 seed_state)\n assert seed_state in range >0 and < d \n x1 = [seed_state, 0, 0]\n x2 = [seed_state, 0, 0]\n end method\n \n method next_int()\n x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1\n x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2\n x1 = [x1i, x1[0], x1[1]] /* Keep last three */\n x2 = [x2i, x2[0], x2[1]] /* Keep last three */\n z = (x1i - x2i) % m1\n answer = (z + 1)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / d\n end method\n \n end class\n \n:MRG32k3a Use:\n random_gen = instance MRG32k3a\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 1459213977 */\n print(random_gen.next_int()) /* 2827710106 */\n print(random_gen.next_int()) /* 4245671317 */\n print(random_gen.next_int()) /* 3877608661 */\n print(random_gen.next_int()) /* 2595287583 */\n \n \n;Task\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers generated with the seed `1234567`\nare as shown above \n\n* Show that for an initial seed of '987654321' the counts of 100_000\nrepetitions of\n\n floor(random_gen.next_float() * 5)\n\nIs as follows:\n \n 0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931\n\n* Show your output here, on this page.\n\n\n", "solution": "import kotlin.math.floor\n\nfun mod(x: Long, y: Long): Long {\n val m = x % y\n return if (m < 0) {\n if (y < 0) {\n m - y\n } else {\n m + y\n }\n } else m\n}\n\nclass RNG {\n // first generator\n private val a1 = arrayOf(0L, 1403580L, -810728L)\n private val m1 = (1L shl 32) - 209\n private var x1 = arrayOf(0L, 0L, 0L)\n\n // second generator\n private val a2 = arrayOf(527612L, 0L, -1370589L)\n private val m2 = (1L shl 32) - 22853\n private var x2 = arrayOf(0L, 0L, 0L)\n\n private val d = m1 + 1\n\n fun seed(state: Long) {\n x1 = arrayOf(state, 0, 0)\n x2 = arrayOf(state, 0, 0)\n }\n\n fun nextInt(): Long {\n val x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1)\n val x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2)\n val z = mod(x1i - x2i, m1)\n\n // keep last three values of the first generator\n x1 = arrayOf(x1i, x1[0], x1[1])\n // keep last three values of the second generator\n x2 = arrayOf(x2i, x2[0], x2[1])\n\n return z + 1\n }\n\n fun nextFloat(): Double {\n return nextInt().toDouble() / d\n }\n}\n\nfun main() {\n val rng = RNG()\n\n rng.seed(1234567)\n println(rng.nextInt())\n println(rng.nextInt())\n println(rng.nextInt())\n println(rng.nextInt())\n println(rng.nextInt())\n println()\n\n val counts = IntArray(5)\n rng.seed(987654321)\n for (i in 0 until 100_000) {\n val v = floor((rng.nextFloat() * 5.0)).toInt()\n counts[v]++\n }\n for (iv in counts.withIndex()) {\n println(\"${iv.index}: ${iv.value}\")\n }\n}"} {"title": "Pseudo-random numbers/PCG32", "language": "Kotlin from C++", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n:'''|''' Bitwise or operator\n::https://en.wikipedia.org/wiki/Bitwise_operation#OR\n::Bitwise comparison gives 1 if any of corresponding bits are 1\n:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111\n\n\n;PCG32 Generator (pseudo-code):\n\nPCG32 has two unsigned 64-bit integers of internal state:\n# '''state''': All 2**64 values may be attained.\n# '''sequence''': Determines which of 2**63 sequences that state iterates through. (Once set together with state at time of seeding will stay constant for this generators lifetime).\n\nValues of sequence allow 2**63 ''different'' sequences of random numbers from the same state.\n\nThe algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-\n\nconst N<-U64 6364136223846793005\nconst inc<-U64 (seed_sequence << 1) | 1\nstate<-U64 ((inc+seed_state)*N+inc\ndo forever\n xs<-U32 (((state>>18)^state)>>27)\n rot<-INT (state>>59)\n OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))\n state<-state*N+inc\nend do\n\nNote that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers using the above.\n\n* Show that the first five integers generated with the seed 42, 54\nare: 2707161783 2068313097 3122475824 2211639955 3215226955\n\n \n\n* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005\n\n* Show your output here, on this page.\n\n\n", "solution": "import kotlin.math.floor\n\nclass PCG32 {\n private var state = 0x853c49e6748fea9buL\n private var inc = 0xda3e39cb94b95bdbuL\n\n fun nextInt(): UInt {\n val old = state\n state = old * N + inc\n val shifted = old.shr(18).xor(old).shr(27).toUInt()\n val rot = old.shr(59)\n return (shifted shr rot.toInt()) or shifted.shl((rot.inv() + 1u).and(31u).toInt())\n }\n\n fun nextFloat(): Double {\n return nextInt().toDouble() / (1L shl 32)\n }\n\n fun seed(seedState: ULong, seedSequence: ULong) {\n state = 0u\n inc = (seedSequence shl 1).or(1uL)\n nextInt()\n state += seedState\n nextInt()\n }\n\n companion object {\n private const val N = 6364136223846793005uL\n }\n}\n\nfun main() {\n val r = PCG32()\n\n r.seed(42u, 54u)\n println(r.nextInt())\n println(r.nextInt())\n println(r.nextInt())\n println(r.nextInt())\n println(r.nextInt())\n println()\n\n val counts = Array(5) { 0 }\n r.seed(987654321u, 1u)\n for (i in 0 until 100000) {\n val j = floor(r.nextFloat() * 5.0).toInt()\n counts[j] += 1\n }\n\n println(\"The counts for 100,000 repetitions are:\")\n for (iv in counts.withIndex()) {\n println(\" %d : %d\".format(iv.index, iv.value))\n }\n}"} {"title": "Pseudo-random numbers/Xorshift star", "language": "Kotlin from Java", "task": "Some definitions to help in the explanation:\n\n:Floor operation\n::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions\n::Greatest integer less than or equal to a real number.\n\n:Bitwise Logical shift operators (c-inspired)\n::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts\n::Binary bits of value shifted left or right, with zero bits shifted in where appropriate. \n::Examples are shown for 8 bit binary numbers; most significant bit to the left.\n \n:: '''<<''' Logical shift left by given number of bits.\n:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100\n \n:: '''>>''' Logical shift right by given number of bits.\n:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101\n \n:'''^''' Bitwise exclusive-or operator\n::https://en.wikipedia.org/wiki/Exclusive_or\n::Bitwise comparison for if bits differ\n:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110\n \n;Xorshift_star Generator (pseudo-code):\n\n /* Let u64 denote an unsigned 64 bit integer type. */\n /* Let u32 denote an unsigned 32 bit integer type. */\n \n class Xorshift_star\n u64 state /* Must be seeded to non-zero initial value */\n u64 const = HEX '2545F4914F6CDD1D'\n \n method seed(u64 num):\n state = num\n end method\n \n method next_int():\n u64 x = state\n x = x ^ (x >> 12)\n x = x ^ (x << 25)\n x = x ^ (x >> 27)\n state = x\n u32 answer = ((x * const) >> 32)\n \n return answer\n end method\n \n method next_float():\n return float next_int() / (1 << 32)\n end method\n \n end class\n \n:;Xorshift use:\n\n random_gen = instance Xorshift_star\n random_gen.seed(1234567)\n print(random_gen.next_int()) /* 3540625527 */\n print(random_gen.next_int()) /* 2750739987 */\n print(random_gen.next_int()) /* 4037983143 */\n print(random_gen.next_int()) /* 1993361440 */\n print(random_gen.next_int()) /* 3809424708 */\n\n;Task:\n\n* Generate a class/set of functions that generates pseudo-random\nnumbers as shown above.\n\n* Show that the first five integers genrated with the seed 1234567\nare as shown above \n\n* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of\n\n floor(random_gen.next_float() * 5)\n\n:Is as follows:\n \n 0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007\n\n* Show your output here, on this page.\n\n\n\n", "solution": "import kotlin.math.floor\n\nclass XorShiftStar {\n private var state = 0L\n\n fun seed(num: Long) {\n state = num\n }\n\n fun nextInt(): Int {\n var x = state\n x = x xor (x ushr 12)\n x = x xor (x shl 25)\n x = x xor (x ushr 27)\n state = x\n\n return (x * MAGIC shr 32).toInt()\n }\n\n fun nextFloat(): Float {\n return nextInt().toUInt().toFloat() / (1L shl 32)\n }\n\n companion object {\n private const val MAGIC = 0x2545F4914F6CDD1D\n }\n}\n\nfun main() {\n val rng = XorShiftStar()\n\n rng.seed(1234567)\n println(rng.nextInt().toUInt())\n println(rng.nextInt().toUInt())\n println(rng.nextInt().toUInt())\n println(rng.nextInt().toUInt())\n println(rng.nextInt().toUInt())\n println()\n\n rng.seed(987654321)\n val counts = arrayOf(0, 0, 0, 0, 0)\n for (i in 1..100000) {\n val j = floor(rng.nextFloat() * 5.0).toInt()\n counts[j]++\n }\n for (iv in counts.withIndex()) {\n println(\"${iv.index}: ${iv.value}\")\n }\n}"} {"title": "Pythagoras tree", "language": "Kotlin from Java", "task": "The Pythagoras tree is a fractal tree constructed from squares. It is named after Pythagoras because each triple of touching squares encloses a right triangle, in a configuration traditionally used to represent the Pythagorean theorem. \n\n;Task\nConstruct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).\n\n;Related tasks\n* Fractal tree\n\n", "solution": "// version 1.1.2\n\nimport java.awt.*\nimport java.awt.geom.Path2D\nimport javax.swing.*\n\nclass PythagorasTree : JPanel() {\n val depthLimit = 7\n val hue = 0.15f\n\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n }\n\n private fun drawTree(g: Graphics2D, x1: Float, y1: Float,\n x2: Float, y2: Float, depth: Int) {\n if (depth == depthLimit) return\n\n val dx = x2 - x1\n val dy = y1 - y2\n\n val x3 = x2 - dy\n val y3 = y2 - dx\n val x4 = x1 - dy\n val y4 = y1 - dx\n val x5 = x4 + 0.5f * (dx - dy)\n val y5 = y4 - 0.5f * (dx + dy)\n\n val square = Path2D.Float()\n with (square) {\n moveTo(x1, y1)\n lineTo(x2, y2)\n lineTo(x3, y3)\n lineTo(x4, y4)\n closePath()\n }\n\n g.color = Color.getHSBColor(hue + depth * 0.02f, 1.0f, 1.0f)\n g.fill(square)\n g.color = Color.lightGray\n g.draw(square)\n\n val triangle = Path2D.Float()\n with (triangle) {\n moveTo(x3, y3)\n lineTo(x4, y4)\n lineTo(x5, y5)\n closePath()\n }\n\n g.color = Color.getHSBColor(hue + depth * 0.035f, 1.0f, 1.0f)\n g.fill(triangle)\n g.color = Color.lightGray\n g.draw(triangle)\n\n drawTree(g, x4, y4, x5, y5, depth + 1)\n drawTree(g, x5, y5, x3, y3, depth + 1)\n }\n\n override fun paintComponent(g: Graphics) {\n super.paintComponent(g)\n drawTree(g as Graphics2D, 275.0f, 500.0f, 375.0f, 500.0f, 0)\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with (f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Pythagoras Tree\"\n isResizable = false\n add(PythagorasTree(), BorderLayout.CENTER)\n pack()\n setLocationRelativeTo(null);\n setVisible(true)\n }\n }\n}"} {"title": "Pythagorean quadruples", "language": "Kotlin", "task": "One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''): \n\n\n:::::::: a2 + b2 + c2 = d2 \n\n\nAn example:\n\n:::::::: 22 + 32 + 62 = 72 \n\n::::: which is:\n\n:::::::: 4 + 9 + 36 = 49 \n\n\n;Task:\n\nFor positive integers up '''2,200''' (inclusive), for all values of '''a''', \n'''b''', '''c''', and '''d''', \nfind (and show here) those values of '''d''' that ''can't'' be represented.\n\nShow the values of '''d''' on one line of output (optionally with a title).\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]]. \n* [[Pythagorean triples]].\n\n\n;Reference:\n:* the Wikipedia article: Pythagorean quadruple.\n\n", "solution": "// version 1.1.3\n\nconst val MAX = 2200\nconst val MAX2 = MAX * MAX - 1\n\nfun main(args: Array) {\n val found = BooleanArray(MAX + 1) // all false by default\n val p2 = IntArray(MAX + 1) { it * it } // pre-compute squares\n\n // compute all possible positive values of d * d - c * c and map them back to d\n val dc = mutableMapOf>()\n for (d in 1..MAX) {\n for (c in 1 until d) {\n val diff = p2[d] - p2[c] \n val v = dc[diff]\n if (v == null)\n dc.put(diff, mutableListOf(d))\n else if (d !in v)\n v.add(d)\n }\n }\n \n for (a in 1..MAX) {\n for (b in 1..a) {\n if ((a and 1) != 0 && (b and 1) != 0) continue\n val sum = p2[a] + p2[b]\n if (sum > MAX2) continue\n val v = dc[sum]\n if (v != null) v.forEach { found[it] = true }\n }\n }\n println(\"The values of d <= $MAX which can't be represented:\")\n for (i in 1..MAX) if (!found[i]) print(\"$i \")\n println()\n}"} {"title": "Pythagorean triples", "language": "Kotlin from Go", "task": "A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.\n\nThey are called primitive triples if a, b, c are co-prime, that is, if their pairwise greatest common divisors {\\rm gcd}(a, b) = {\\rm gcd}(a, c) = {\\rm gcd}(b, c) = 1. \n\nBecause of their relationship through the Pythagorean theorem, a, b, and c are co-prime if a and b are co-prime ({\\rm gcd}(a, b) = 1). \n\nEach triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.\n\n\n;Task:\nThe task is to determine how many Pythagorean triples there are with a perimeter no larger than 100 and the number of these that are primitive.\n\n\n;Extra credit: \nDeal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?\n\nNote: the extra credit is not for you to demonstrate how fast your language is compared to others; you need a proper algorithm to solve them in a timely manner.\n\n\n;Related tasks:\n* [[Euler's sum of powers conjecture]] \n* [[List comprehensions]]\n* [[Pythagorean quadruples]] \n\n", "solution": "// version 1.1.2\n\nvar total = 0L\nvar prim = 0L\nvar maxPeri = 0L\n\nfun newTri(s0: Long, s1: Long, s2: Long) {\n val p = s0 + s1 + s2\n if (p <= maxPeri) {\n prim++\n total += maxPeri / p\n newTri( s0 - 2 * s1 + 2 * s2, 2 * s0 - s1 + 2 * s2, 2 * s0 - 2 * s1 + 3 * s2)\n newTri( s0 + 2 * s1 + 2 * s2, 2 * s0 + s1 + 2 * s2, 2 * s0 + 2 * s1 + 3 * s2)\n newTri(-s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2)\n }\n}\n\nfun main(args: Array) {\n maxPeri = 100\n while (maxPeri <= 10_000_000_000L) {\n prim = 0\n total = 0\n newTri(3, 4, 5)\n println(\"Up to $maxPeri: $total triples, $prim primatives\")\n maxPeri *= 10\n }\n}"} {"title": "Quaternion type", "language": "Kotlin", "task": "complex numbers.\n\nA complex number has a real and complex part, sometimes written as a + bi, \nwhere a and b stand for real numbers, and i stands for the square root of minus 1.\n\nAn example of a complex number might be -3 + 2i, \nwhere the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''. \n\nA quaternion has one real part and ''three'' imaginary parts, i, j, and k. \n\nA quaternion might be written as a + bi + cj + dk. \n\nIn the quaternion numbering system:\n:::* ii = jj = kk = ijk = -1, or more simply,\n:::* ii = jj = kk = ijk = -1. \n\nThe order of multiplication is important, as, in general, for two quaternions:\n:::: q1 and q2: q1q2 q2q1. \n\nAn example of a quaternion might be 1 +2i +3j +4k \n\nThere is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position. \n\nSo the example above would be written as (1, 2, 3, 4) \n\n\n;Task:\nGiven the three quaternions and their components: \n q = (1, 2, 3, 4) = (a, b, c, d)\n q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)\n q2 = (3, 4, 5, 6) = (a2, b2, c2, d2) \nAnd a wholly real number r = 7. \n\n\nCreate functions (or classes) to perform simple maths with quaternions including computing:\n# The norm of a quaternion: = \\sqrt{a^2 + b^2 + c^2 + d^2} \n# The negative of a quaternion: = (-a, -b, -c, -d) \n# The conjugate of a quaternion: = ( a, -b, -c, -d) \n# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d) \n# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2) \n# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr) \n# Multiplication of two quaternions q1 and q2 is given by: ( a1a2 - b1b2 - c1c2 - d1d2, a1b2 + b1a2 + c1d2 - d1c2, a1c2 - b1d2 + c1a2 + d1b2, a1d2 + b1c2 - c1b2 + d1a2 ) \n# Show that, for the two quaternions q1 and q2: q1q2 q2q1 \n\nIf a language has built-in support for quaternions, then use it.\n\n\n;C.f.:\n* [[Vector products]]\n* On Quaternions; or on a new System of Imaginaries in Algebra. By Sir William Rowan Hamilton LL.D, P.R.I.A., F.R.A.S., Hon. M. R. Soc. Ed. and Dub., Hon. or Corr. M. of the Royal or Imperial Academies of St. Petersburgh, Berlin, Turin and Paris, Member of the American Academy of Arts and Sciences, and of other Scientific Societies at Home and Abroad, Andrews' Prof. of Astronomy in the University of Dublin, and Royal Astronomer of Ireland.\n\n", "solution": "// version 1.1.2\n\ndata class Quaternion(val a: Double, val b: Double, val c: Double, val d: Double) {\n operator fun plus(other: Quaternion): Quaternion {\n return Quaternion (this.a + other.a, this.b + other.b,\n this.c + other.c, this.d + other.d)\n }\n\n operator fun plus(r: Double) = Quaternion(a + r, b, c, d)\n\n operator fun times(other: Quaternion): Quaternion {\n return Quaternion(\n this.a * other.a - this.b * other.b - this.c * other.c - this.d * other.d,\n this.a * other.b + this.b * other.a + this.c * other.d - this.d * other.c,\n this.a * other.c - this.b * other.d + this.c * other.a + this.d * other.b,\n this.a * other.d + this.b * other.c - this.c * other.b + this.d * other.a\n )\n }\n\n operator fun times(r: Double) = Quaternion(a * r, b * r, c * r, d * r)\n\n operator fun unaryMinus() = Quaternion(-a, -b, -c, -d)\n\n fun conj() = Quaternion(a, -b, -c, -d)\n\n fun norm() = Math.sqrt(a * a + b * b + c * c + d * d)\n\n override fun toString() = \"($a, $b, $c, $d)\"\n}\n\n// extension functions for Double type\noperator fun Double.plus(q: Quaternion) = q + this\noperator fun Double.times(q: Quaternion) = q * this\n\nfun main(args: Array) {\n val q = Quaternion(1.0, 2.0, 3.0, 4.0)\n val q1 = Quaternion(2.0, 3.0, 4.0, 5.0)\n val q2 = Quaternion(3.0, 4.0, 5.0, 6.0)\n val r = 7.0\n println(\"q = $q\")\n println(\"q1 = $q1\")\n println(\"q2 = $q2\")\n println(\"r = $r\\n\")\n println(\"norm(q) = ${\"%f\".format(q.norm())}\")\n println(\"-q = ${-q}\")\n println(\"conj(q) = ${q.conj()}\\n\")\n println(\"r + q = ${r + q}\")\n println(\"q + r = ${q + r}\")\n println(\"q1 + q2 = ${q1 + q2}\\n\")\n println(\"r * q = ${r * q}\")\n println(\"q * r = ${q * r}\")\n val q3 = q1 * q2\n val q4 = q2 * q1\n println(\"q1 * q2 = $q3\")\n println(\"q2 * q1 = $q4\\n\")\n println(\"q1 * q2 != q2 * q1 = ${q3 != q4}\")\n}"} {"title": "Quine", "language": "Kotlin", "task": "A quine is a self-referential program that can, \nwithout any external access, output its own source. \n\n\nA '''quine''' (named after Willard Van Orman Quine) is also known as:\n::* ''self-reproducing automata'' (1972)\n::* ''self-replicating program'' or ''self-replicating computer program''\n::* ''self-reproducing program'' or ''self-reproducing computer program''\n::* ''self-copying program'' or ''self-copying computer program''\n\n\n\nIt is named after the philosopher and logician \nwho studied self-reference and quoting in natural language, \nas for example in the paradox \"'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation.\"\n\n\"Source\" has one of two meanings. It can refer to the text-based program source. \nFor languages in which program source is represented as a data structure, \"source\" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression.\n\nThe usual way to code a quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested.\n\n\n;Task:\nWrite a program that outputs its own source code in this way. If the language allows it, you may add a variant that accesses the code directly. You are not allowed to read any external files with the source code. The program should also contain some sort of self-reference, so constant expressions which return their own value which some top-level interpreter will print out. Empty programs producing no output are not allowed.\n\nThere are several difficulties that one runs into when writing a quine, mostly dealing with quoting:\n* Part of the code usually needs to be stored as a string or structural literal in the language, which needs to be quoted somehow. However, including quotation marks in the string literal itself would be troublesome because it requires them to be escaped, which then necessitates the escaping character (e.g. a backslash) in the string, which itself usually needs to be escaped, and so on.\n** Some languages have a function for getting the \"source code representation\" of a string (i.e. adds quotation marks, etc.); in these languages, this can be used to circumvent the quoting problem.\n** Another solution is to construct the quote character from its [[character code]], without having to write the quote character itself. Then the character is inserted into the string at the appropriate places. The ASCII code for double-quote is 34, and for single-quote is 39.\n* Newlines in the program may have to be reproduced as newlines in the string, which usually requires some kind of escape sequence (e.g. \"\\n\"). This causes the same problem as above, where the escaping character needs to itself be escaped, etc.\n** If the language has a way of getting the \"source code representation\", it usually handles the escaping of characters, so this is not a problem.\n** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.\n** Write the entire program on one line, for free-form languages (as you can see for some of the solutions here, they run off the edge of the screen), thus removing the need for newlines. However, this may be unacceptable as some languages require a newline at the end of the file; and otherwise it is still generally good style to have a newline at the end of a file. (The task is not clear on whether a newline is required at the end of the file.) Some languages have a print statement that appends a newline; which solves the newline-at-the-end issue; but others do not.\n\n\n'''Next to the Quines presented here, many other versions can be found on the Quine page.'''\n\n\n;Related task:\n:* print itself.\n\n", "solution": "// version 1.1.2\n\nconst val F = \"\"\"// version 1.1.2\n\nconst val F = %c%c%c%s%c%c%c\n\nfun main(args: Array) {\n System.out.printf(F, 34, 34, 34, F, 34, 34, 34)\n}\n\"\"\"\n\nfun main(args: Array) {\n System.out.printf(F, 34, 34, 34, F, 34, 34, 34)\n}"} {"title": "RPG attributes generator", "language": "Kotlin", "task": "'''RPG''' = Role Playing Game.\n\n\n\nYou're running a tabletop RPG, and your players are creating characters.\n\nEach character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.\n\nOne way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll.\n\nSome players like to assign values to their attributes in the order they're rolled.\n\nTo ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:\n\n* The total of all character attributes must be at least 75.\n* At least two of the attributes must be at least 15.\n\nHowever, this can require a lot of manual dice rolling. A programatic solution would be much faster.\n\n\n;Task:\nWrite a program that:\n# Generates 4 random, whole values between 1 and 6.\n# Saves the sum of the 3 largest values.\n# Generates a total of 6 values this way.\n# Displays the total, and all 6 values once finished.\n\n* The order in which each value was generated must be preserved.\n* The total of all 6 values must be at least 75.\n* At least 2 of the values must be 15 or more.\n\n", "solution": "import kotlin.random.Random\n\nfun main() {\n while (true) {\n val values = List(6) {\n val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4)\n rolls.sorted().take(3).sum()\n }\n val vsum = values.sum()\n val vcount = values.count { it >= 15 }\n if (vsum < 75 || vcount < 2) continue\n println(\"The 6 random numbers generated are: $values\")\n println(\"Their sum is $vsum and $vcount of them are >= 15\")\n break\n }\n}"} {"title": "Ramer-Douglas-Peucker line simplification", "language": "Kotlin from C++", "task": "The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape. \n\n\n;Task:\nUsing the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:\n (0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9) \n\nThe error threshold to be used is: '''1.0'''. \n\nDisplay the remaining points here.\n\n\n;Reference:\n:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.\n\n", "solution": "// version 1.1.0\n\ntypealias Point = Pair\n\nfun perpendicularDistance(pt: Point, lineStart: Point, lineEnd: Point): Double {\n var dx = lineEnd.first - lineStart.first\n var dy = lineEnd.second - lineStart.second\n\n // Normalize\n val mag = Math.hypot(dx, dy)\n if (mag > 0.0) { dx /= mag; dy /= mag }\n val pvx = pt.first - lineStart.first\n val pvy = pt.second - lineStart.second\n\n // Get dot product (project pv onto normalized direction)\n val pvdot = dx * pvx + dy * pvy\n \n // Scale line direction vector and substract it from pv\n val ax = pvx - pvdot * dx\n val ay = pvy - pvdot * dy\n \n return Math.hypot(ax, ay)\n}\n\nfun RamerDouglasPeucker(pointList: List, epsilon: Double, out: MutableList) {\n if (pointList.size < 2) throw IllegalArgumentException(\"Not enough points to simplify\")\n \n // Find the point with the maximum distance from line between start and end\n var dmax = 0.0\n var index = 0\n val end = pointList.size - 1\n for (i in 1 until end) {\n val d = perpendicularDistance(pointList[i], pointList[0], pointList[end])\n if (d > dmax) { index = i; dmax = d }\n }\n\n // If max distance is greater than epsilon, recursively simplify\n if (dmax > epsilon) {\n val recResults1 = mutableListOf()\n val recResults2 = mutableListOf()\n val firstLine = pointList.take(index + 1) \n val lastLine = pointList.drop(index)\n RamerDouglasPeucker(firstLine, epsilon, recResults1)\n RamerDouglasPeucker(lastLine, epsilon, recResults2)\n\n // build the result list\n out.addAll(recResults1.take(recResults1.size - 1))\n out.addAll(recResults2)\n if (out.size < 2) throw RuntimeException(\"Problem assembling output\")\n }\n else {\n // Just return start and end points\n out.clear()\n out.add(pointList.first())\n out.add(pointList.last())\n }\n}\n\nfun main(args: Array) {\n val pointList = listOf(\n Point(0.0, 0.0),\n Point(1.0, 0.1),\n Point(2.0, -0.1),\n Point(3.0, 5.0),\n Point(4.0, 6.0),\n Point(5.0, 7.0),\n Point(6.0, 8.1),\n\tPoint(7.0, 9.0),\n\tPoint(8.0, 9.0),\n Point(9.0, 9.0) \n )\n val pointListOut = mutableListOf()\n RamerDouglasPeucker(pointList, 1.0, pointListOut) \n println(\"Points remaining after simplification:\")\n for (p in pointListOut) println(p)\n}"} {"title": "Random Latin squares", "language": "Kotlin from Go", "task": "A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.\nFor the purposes of this task, a random Latin square of size n is a Latin square constructed or generated by a probabilistic procedure such that the probability of any particular Latin square of size n being produced is non-zero.\n\n;Example n=4 randomised Latin square:\n0 2 3 1\n2 1 0 3\n3 0 1 2\n1 3 2 0\n\n;Task:\n# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.\n# Use the function to generate ''and show here'', two randomly generated squares of size 5.\n\n;Note: \nStrict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.\n\n;Related tasks:\n* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]\n* [[Latin Squares in reduced form]]\n\n;Reference:\n* Wikipedia: Latin square\n* OEIS: A002860\n\n", "solution": "typealias matrix = MutableList>\n\nfun printSquare(latin: matrix) {\n for (row in latin) {\n println(row)\n }\n println()\n}\n\nfun latinSquare(n: Int) {\n if (n <= 0) {\n println(\"[]\")\n return\n }\n\n val latin = MutableList(n) { MutableList(n) { it } }\n // first row\n latin[0].shuffle()\n\n // middle row(s)\n for (i in 1 until n - 1) {\n var shuffled = false\n shuffling@\n while (!shuffled) {\n latin[i].shuffle()\n for (k in 0 until i) {\n for (j in 0 until n) {\n if (latin[k][j] == latin[i][j]) {\n continue@shuffling\n }\n }\n }\n shuffled = true\n }\n }\n\n // last row\n for (j in 0 until n) {\n val used = MutableList(n) { false }\n for (i in 0 until n - 1) {\n used[latin[i][j]] = true\n }\n for (k in 0 until n) {\n if (!used[k]) {\n latin[n - 1][j] = k\n break\n }\n }\n }\n\n printSquare(latin)\n}\n\nfun main() {\n latinSquare(5)\n latinSquare(5)\n latinSquare(10) // for good measure\n}"} {"title": "Random number generator (device)", "language": "Kotlin", "task": "If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:\n\nshow how to obtain a random 32-bit number from that mechanism.\n\n;Related task\n* [[Random_number_generator_(included)]]\n\n", "solution": "// version 1.1.2\n\nimport java.security.SecureRandom\n\nfun main(args: Array) {\n val rng = SecureRandom()\n val rn1 = rng.nextInt()\n val rn2 = rng.nextInt()\n val newSeed = rn1.toLong() * rn2\n rng.setSeed(newSeed) // reseed using the previous 2 random numbers\n println(rng.nextInt()) // get random 32-bit number and print it\n}"} {"title": "Random number generator (included)", "language": "Kotlin", "task": "The task is to:\n: State the type of random number generator algorithm used in a language's built-in random number generator. If the language or its immediate libraries don't provide a random number generator, skip this task.\n: If possible, give a link to a wider explanation of the algorithm used.\n\nNote: the task is ''not'' to create an RNG, but to report on the languages in-built RNG that would be the most likely RNG used.\n\nThe main types of pseudo-random number generator (Mersenne twister generator is a subclass). The last main type is where the output of one of the previous ones (typically a Mersenne twister) is fed through a [[cryptographic hash function]] to maximize unpredictability of individual bits. \n\nNote that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.\n\n", "solution": "As mentioned in the Java entry, the java.util.Random class uses a linear congruential formula and is not therefore cryptographically secure. However, there is also a derived class, java.security.SecureRandom, which can be used for cryptographic purposes\n\n"} {"title": "Range consolidation", "language": "Kotlin", "task": "Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''. \n\n\nThat range can be shown as:\n::::::::: '''[b0, b1]'''\n:::::::: or equally as:\n::::::::: '''[b1, b0]'''\n\n\nGiven two ranges, the act of consolidation between them compares the two ranges:\n* If one range covers all of the other then the result is that encompassing range.\n* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.\n* Otherwise the act of consolidation is to return the two non-touching ranges.\n\n\nGiven '''N''' ranges where '''N > 2''' then the result is the same as repeatedly replacing all combinations of two ranges by their consolidation until no further consolidation between range pairs is possible. \n\nIf '''N < 2''' then range consolidation has no strict meaning and the input can be returned. \n\n\n;Example 1:\n: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then \n: there is no common region between the ranges and the result is the same as the input.\n\n\n;Example 2:\n: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then \n: there is : an overlap '''[2.5, 1.8]''' between the ranges and \n: the result is the single range '''[1, 4.7]'''. \n: Note that order of bounds in a range is not (yet) stated.\n\n\n;Example 3:\n: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then \n: they touch at '''7.2''' and \n: the result is the single range '''[6.1, 8.3]'''. \n\n\n;Example 4:\n: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]''' \n: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]''' \n: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and \n: consolidate to produce the range '''[1, 5]'''. \n: This range, in turn, overlaps the other range '''[4, 8]''', and \n: so consolidates to the final output of the single range '''[1, 8]'''.\n\n\n;Task:\nLet a normalized range display show the smaller bound to the left; and show the\nrange with the smaller lower bound to the left of other ranges when showing multiple ranges.\n\nOutput the ''normalized'' result of applying consolidation to these five sets of ranges: \n [1.1, 2.2]\n [6.1, 7.2], [7.2, 8.3]\n [4, 3], [2, 1]\n [4, 3], [2, 1], [-1, -2], [3.9, 10]\n [1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6] \nShow all output here.\n\n\n;See also:\n* [[Set consolidation]]\n* [[Set of real numbers]]\n\n", "solution": "fun consolidate(ranges: Iterable>): List> where T : Comparable\n{\n return ranges\n .sortedWith(compareBy({ it.start }, { it.endInclusive }))\n .asReversed()\n .fold(mutableListOf>()) {\n consolidatedRanges, range ->\n if (consolidatedRanges.isEmpty())\n {\n consolidatedRanges.add(range)\n }\n // Keep in mind the reverse-sorting applied above:\n // If the end of the current-range is higher, than it must start at a lower value,\n else if (range.endInclusive >= consolidatedRanges[0].endInclusive)\n {\n consolidatedRanges[0] = range\n }\n else if (range.endInclusive >= consolidatedRanges[0].start)\n {\n consolidatedRanges[0] = range.start .. consolidatedRanges[0].endInclusive\n }\n else\n {\n consolidatedRanges.add(0, range)\n }\n\n return@fold consolidatedRanges\n }\n .toList()\n}\n\n// What a bummer! Kotlin's range syntax (a..b) doesn't meet the task requirements when b < b,\n// and on the other hand, the syntax for constructing lists, arrays and pairs isn't close enough\n// to the range notation. Instead then, here's a *very* naive parser. Don't take it seriously.\nval rangeRegex = Regex(\"\"\"\\[(.+),(.+)\\]\"\"\")\nfun parseDoubleRange(rangeStr: String): ClosedFloatingPointRange {\n val parts = rangeRegex\n .matchEntire(rangeStr)\n ?.groupValues\n ?.drop(1)\n ?.map { it.toDouble() }\n ?.sorted()\n if (parts == null) throw IllegalArgumentException(\"Unable to parse range $rangeStr\")\n return parts[0] .. parts[1]\n}\n\nfun serializeRange(range: ClosedRange<*>) = \"[${range.start}, ${range.endInclusive}]\"\n\n// See above. In practice you'd probably use consolidate directly\nfun consolidateDoubleRanges(rangeStrings: Iterable): List\n{\n return consolidate(rangeStrings.asSequence().map(::parseDoubleRange).toList()).map(::serializeRange)\n}\n\n\nfun main() {\n val inputRanges = listOf(\n listOf(\"[1.1, 2.2]\"),\n listOf(\"[6.1, 7.2]\", \"[7.2, 8.3]\"),\n listOf(\"[4, 3]\", \"[2, 1]\"),\n listOf(\"[4, 3]\", \"[2, 1]\", \"[-1, -2]\", \"[3.9, 10]\"),\n listOf(\"[1, 3]\", \"[-6, -1]\", \"[-4, -5]\", \"[8, 2]\", \"[-6, -6]\")\n )\n\n inputRanges.associateBy(Any::toString, ::consolidateDoubleRanges).forEach({ println(\"${it.key} => ${it.value}\") })\n}"} {"title": "Range expansion", "language": "Kotlin", "task": "{{:Range extraction/Format}}\n\n\n;Task:\nExpand the range description: \n -6,-3--1,3-5,7-11,14,15,17-20 \nNote that the second element above, \nis the '''range from minus 3 to ''minus'' 1'''. \n\n\n;Related task:\n* [[Range extraction]]\n\n", "solution": "// version 1.0.6\n\nfun expandRange(s: String): MutableList {\n val list = mutableListOf() \n val items = s.split(',')\n var first: Int\n var last: Int\n for (item in items) {\n val count = item.count { it == '-' }\n if (count == 0 || (count == 1 && item[0] == '-'))\n list.add(item.toInt())\n else {\n val items2 = item.split('-')\n if (count == 1) {\n first = items2[0].toInt()\n last = items2[1].toInt() \n }\n else if (count == 2) {\n first = items2[1].toInt() * -1\n last = items2[2].toInt()\n }\n else {\n first = items2[1].toInt() * -1\n last = items2[3].toInt() * -1\n }\n for (i in first..last) list.add(i) \n }\n }\n return list\n} \n\nfun main(args: Array) {\n val s = \"-6,-3--1,3-5,7-11,14,15,17-20\"\n println(expandRange(s))\n}"} {"title": "Range extraction", "language": "Kotlin", "task": "{{:Range extraction/Format}}\n\n;Task:\n* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format. \n* Use the function to compute and print the range formatted version of the following ordered list of integers. (The correct answer is: 0-2,4,6-8,11,12,14-25,27-33,35-39).\n\n 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39\n* Show the output of your program.\n\n\n;Related task:\n* [[Range expansion]]\n\n", "solution": "// version 1.0.6\n\nfun extractRange(list: List): String {\n if (list.isEmpty()) return \"\"\n val sb = StringBuilder()\n var first = list[0]\n var prev = first\n\n fun append(index: Int) {\n if (first == prev) sb.append(prev)\n else if (first == prev - 1) sb.append(first, \",\", prev)\n else sb.append(first, \"-\", prev)\n if (index < list.size - 1) sb.append(\",\")\n }\n\n for (i in 1 until list.size) {\n if (list[i] == prev + 1) prev++\n else {\n append(i)\n first = list[i]\n prev = first\n }\n }\n append(list.size - 1)\n return sb.toString()\n}\n \nfun main(args: Array) {\n val list1 = listOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20)\n println(extractRange(list1))\n println()\n val list2 = listOf(0, 1, 2, 4, 6, 7, 8, 11, 12, 14,\n 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,\n 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,\n 37, 38, 39)\n println(extractRange(list2))\n}"} {"title": "Rate counter", "language": "Kotlin from JavaScript", "task": "Counting the frequency at which something occurs is a common activity in measuring performance and managing resources. In this task, we assume that there is some job which we want to perform repeatedly, and we want to know how quickly these jobs are being performed.\nOf interest is the code that performs the actual measurements. Any other code (such as job implementation or dispatching) that is required to demonstrate the rate tracking is helpful, but not the focus.\n\nMultiple approaches are allowed (even preferable), so long as they can accomplish these goals:\n\n* Run N seconds worth of jobs and/or Y jobs.\n* Report at least three distinct times.\n\nBe aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.\n\n'''See also:''' [[System time]], [[Time a function]]\n\n", "solution": "// version 1.1.3\n\ntypealias Func = (T) -> T\n\nfun cube(n: Int) = n * n * n\n\nfun benchmark(n: Int, func: Func, arg: T): LongArray {\n val times = LongArray(n)\n for (i in 0 until n) {\n val m = System.nanoTime()\n func(arg)\n times[i] = System.nanoTime() - m\n }\n return times\n} \n\nfun main(args: Array) {\n println(\"\\nTimings (nanoseconds) : \")\n for (time in benchmark(10, ::cube, 5)) println(time)\n}"} {"title": "Read a specific line from a file", "language": "Kotlin", "task": "Some languages have special semantics for obtaining a known line number from a file.\n\n\n;Task:\nDemonstrate how to obtain the contents of a specific line within a file. \n\nFor the purpose of this task demonstrate how the contents of the seventh line of a file can be obtained, and store it in a variable or in memory (for potential future use within the program if the code were to become embedded). \n\nIf the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message. \n\nIf no special semantics are available for obtaining the required line, it is permissible to read line by line. \n\nNote that empty lines are considered and should still be counted.\n\nAlso note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.\n\n", "solution": "// version 1.1.2\n\nimport java.io.File\n\nfun main(args: Array) {\n /* The following code reads the whole file into memory\n and so should not be used for large files\n which should instead be read line by line until the\n desired line is reached */\n\n val lines = File(\"input.txt\").readLines()\n if (lines.size < 7)\n println(\"There are only ${lines.size} lines in the file\")\n else {\n val line7 = lines[6].trim()\n if (line7.isEmpty())\n println(\"The seventh line is empty\")\n else\n println(\"The seventh line is : $line7\")\n }\n}\n\n/* Note that 'input.txt' contains the eight lines:\nLine 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\n*/"} {"title": "Recaman's sequence", "language": "Kotlin from Go", "task": "The '''Recaman's sequence''' generates Natural numbers.\n\nStarting from a(0)=0, the n'th term a(n), where n>0, is the previous term minus n i.e a(n) = a(n-1) - n but only if this is '''both''' positive ''and'' has not been previousely generated.\n\nIf the conditions ''don't'' hold then a(n) = a(n-1) + n.\n\n\n;Task:\n# Generate and show here the first 15 members of the sequence.\n# Find and show here, the first duplicated number in the sequence.\n# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.\n\n\n;References:\n* A005132, The On-Line Encyclopedia of Integer Sequences.\n* The Slightly Spooky Recaman Sequence, Numberphile video.\n* Recaman's sequence, on Wikipedia.\n\n", "solution": "// Version 1.2.60\n\nfun main(args: Array) {\n val a = mutableListOf(0)\n val used = mutableSetOf(0)\n val used1000 = mutableSetOf(0)\n var foundDup = false\n var n = 1\n while (n <= 15 || !foundDup || used1000.size < 1001) {\n var next = a[n - 1] - n\n if (next < 1 || used.contains(next)) next += 2 * n\n val alreadyUsed = used.contains(next)\n a.add(next)\n if (!alreadyUsed) {\n used.add(next)\n if (next in 0..1000) used1000.add(next)\n }\n if (n == 14) {\n println(\"The first 15 terms of the Recaman's sequence are: $a\")\n }\n if (!foundDup && alreadyUsed) {\n println(\"The first duplicated term is a[$n] = $next\")\n foundDup = true\n }\n if (used1000.size == 1001) {\n println(\"Terms up to a[$n] are needed to generate 0 to 1000\")\n }\n n++\n }\n}"} {"title": "Remove lines from a file", "language": "Kotlin", "task": "Remove a specific line or a number of lines from a file. \n\nThis should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed). \n\nFor the purpose of this task, line numbers and the number of lines start at one, so to remove the first two lines from the file foobar.txt, the parameters should be: foobar.txt, 1, 2\n\nEmpty lines are considered and should still be counted, and if the specified line is empty, it should still be removed. \n\nAn appropriate message should appear if an attempt is made to remove lines beyond the end of the file.\n\n", "solution": "// version 1.1.2\n\nimport java.io.File\n\nfun removeLines(fileName: String, startLine: Int, numLines: Int) {\n require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)\n val f = File(fileName)\n if (!f.exists()) {\n println(\"$fileName does not exist\")\n return\n }\n var lines = f.readLines()\n val size = lines.size\n if (startLine > size) {\n println(\"The starting line is beyond the length of the file\")\n return\n }\n var n = numLines\n if (startLine + numLines - 1 > size) {\n println(\"Attempting to remove some lines which are beyond the end of the file\")\n n = size - startLine + 1\n }\n lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)\n val text = lines.joinToString(System.lineSeparator())\n f.writeText(text)\n}\n\nfun printFile(fileName: String, message: String) {\n require(!fileName.isEmpty())\n val f = File(fileName)\n if (!f.exists()) {\n println(\"$fileName does not exist\")\n return\n }\n println(\"\\nContents of $fileName $message:\\n\")\n f.forEachLine { println(it) }\n}\n\nfun main(args: Array) {\n printFile(\"input.txt\", \"before removal\")\n removeLines(\"input.txt\", 2, 3)\n printFile(\"input.txt\", \"after removal of 3 lines starting from the second\")\n}"} {"title": "Rep-string", "language": "Kotlin", "task": "Given a series of ones and zeroes in a string, define a repeated string or ''rep-string'' as a string which is created by repeating a substring of the ''first'' N characters of the string ''truncated on the right to the length of the input string, and in which the substring appears repeated at least twice in the original''.\n\nFor example, the string '''10011001100''' is a rep-string as the leftmost four characters of '''1001''' are repeated three times and truncated on the right to give the original string.\n\nNote that the requirement for having the repeat occur two or more times means that the repeating unit is ''never'' longer than half the length of the input string.\n\n\n;Task:\n* Write a function/subroutine/method/... that takes a string and returns an indication of if it is a rep-string and the repeated string. (Either the string that is repeated, or the number of repeated characters would suffice). \n* There may be multiple sub-strings that make a string a rep-string - in that case an indication of all, or the longest, or the shortest would suffice.\n* Use the function to indicate the repeating substring if any, in the following:\n\n\n1001110011\n1110111011\n0010010010\n1010101010\n1111111111\n0100101101\n0100100\n101\n11\n00\n1\n\n\n* Show your output on this page.\n\n\n\n", "solution": "// version 1.0.6\n\nfun repString(s: String): MutableList {\n val reps = mutableListOf()\n if (s.length < 2) return reps\n for (c in s) if (c != '0' && c != '1') throw IllegalArgumentException(\"Not a binary string\")\n for (len in 1..s.length / 2) {\n val t = s.take(len)\n val n = s.length / len\n val r = s.length % len\n val u = t.repeat(n) + t.take(r)\n if (u == s) reps.add(t)\n }\n return reps\n} \n\nfun main(args: Array) {\n val strings = listOf(\n \"1001110011\",\n \"1110111011\",\n \"0010010010\",\n \"1010101010\",\n \"1111111111\",\n \"0100101101\",\n \"0100100\",\n \"101\",\n \"11\",\n \"00\",\n \"1\"\n )\n println(\"The (longest) rep-strings are:\\n\")\n for (s in strings) {\n val reps = repString(s)\n val size = reps.size\n println(\"${s.padStart(10)} -> ${if (size > 0) reps[size - 1] else \"Not a rep-string\"}\")\n }\n}"} {"title": "Repeat", "language": "Kotlin", "task": "Write a procedure which accepts as arguments another procedure and a positive integer. \n\nThe latter procedure is executed a number of times equal to the accepted integer.\n\n", "solution": "// version 1.0.6\n\nfun repeat(n: Int, f: () -> Unit) {\n for (i in 1..n) {\n f()\n println(i)\n }\n}\n\nfun main(args: Array) {\n repeat(5) { print(\"Example \") }\n}"} {"title": "Resistor mesh", "language": "Kotlin from C", "task": "Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,\nfind the resistance between points '''A''' and '''B'''.\n\n\n;See also:\n* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)\n* An article on how to calculate this and an implementation in Mathematica\n\n", "solution": "// version 1.1.4-3\n\ntypealias List2D = List>\n\nconst val S = 10\n\nclass Node(var v: Double, var fixed: Int)\n\nfun setBoundary(m: List2D) {\n m[1][1].v = 1.0; m[1][1].fixed = 1\n m[6][7].v = -1.0; m[6][7].fixed = -1\n}\n\nfun calcDiff(m: List2D, d: List2D, w: Int, h: Int): Double {\n var total = 0.0\n for (i in 0 until h) {\n for (j in 0 until w) {\n var v = 0.0\n var n = 0\n if (i > 0) { v += m[i - 1][j].v; n++ }\n if (j > 0) { v += m[i][j - 1].v; n++ }\n if (i + 1 < h) { v += m[i + 1][j].v; n++ } \n if (j + 1 < w) { v += m[i][j + 1].v; n++ }\n v = m[i][j].v - v / n \n d[i][j].v = v\n if (m[i][j].fixed == 0) total += v * v\n }\n }\n return total\n}\n\nfun iter(m: List2D, w: Int, h: Int): Double {\n val d = List(h) { List(w) { Node(0.0, 0) } }\n val cur = DoubleArray(3)\n var diff = 1e10\n\n while (diff > 1e-24) {\n setBoundary(m)\n diff = calcDiff(m, d, w, h)\n for (i in 0 until h) {\n for (j in 0 until w) m[i][j].v -= d[i][j].v\n }\n }\n\n for (i in 0 until h) {\n for (j in 0 until w) {\n var k = 0\n if (i != 0) k++\n if (j != 0) k++\n if (i < h - 1) k++\n if (j < w - 1) k++ \n cur[m[i][j].fixed + 1] += d[i][j].v * k\n }\n }\n return (cur[2] - cur[0]) / 2.0 \n} \n \nfun main(args: Array) {\n val mesh = List(S) { List(S) { Node(0.0, 0) } }\n val r = 2.0 / iter(mesh, S, S)\n println(\"R = $r\")\n}"} {"title": "Reverse words in a string", "language": "Kotlin", "task": "Reverse the order of all tokens in each of a number of strings and display the result; the order of characters within a token should not be modified.\n\n\n;Example:\nHey you, Bub! would be shown reversed as: Bub! you, Hey \n\n\nTokens are any non-space characters separated by spaces (formally, white-space); the visible punctuation form part of the word within which it is located and should not be modified. \n\nYou may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.\n\nSome strings have no tokens, so an empty string (or one just containing spaces) would be the result.\n\n'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line. \n\n(You can consider the ten strings as ten lines, and the tokens as words.)\n\n\n;Input data\n\n (ten lines within the box)\n line\n +----------------------------------------+\n 1 | ---------- Ice and Fire ------------ |\n 2 | | <--- a blank line here.\n 3 | fire, in end will world the say Some |\n 4 | ice. in say Some |\n 5 | desire of tasted I've what From |\n 6 | fire. favor who those with hold I |\n 7 | | <--- a blank line here.\n 8 | ... elided paragraph last ... |\n 9 | | <--- a blank line here.\n 10 | Frost Robert ----------------------- |\n +----------------------------------------+\n\n\n;Cf.\n* [[Phrase reversals]]\n\n", "solution": "fun reversedWords(s: String) = s.split(\" \").filter { it.isNotEmpty() }.reversed().joinToString(\" \")\n\nfun main() {\n val s = \"Hey you, Bub!\"\n println(reversedWords(s))\n println()\n val sl = listOf(\n \" ---------- Ice and Fire ------------ \", \n \" \",\n \" fire, in end will world the say Some \", \n \" ice. in say Some \", \n \" desire of tasted I've what From \", \n \" fire. favor who those with hold I \", \n \" \", \n \" ... elided paragraph last ... \", \n \" \", \n \" Frost Robert ----------------------- \",\n ) \n sl.forEach { println(reversedWords(it)) }\n}"} {"title": "Roman numerals/Decode", "language": "Kotlin", "task": "Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. \n\nYou don't need to validate the form of the Roman numeral.\n\nModern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, \nstarting with the leftmost decimal digit and skipping any '''0'''s (zeroes). \n\n'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and \n'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).\n \nThe Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.\n\n", "solution": "// version 1.0.6\n\nfun romanDecode(roman: String): Int {\n if (roman.isEmpty()) return 0\n var n = 0\n var last = 'O'\n for (c in roman) { \n when (c) {\n 'I' -> n += 1 \n 'V' -> if (last == 'I') n += 3 else n += 5\n 'X' -> if (last == 'I') n += 8 else n += 10\n 'L' -> if (last == 'X') n += 30 else n += 50\n 'C' -> if (last == 'X') n += 80 else n += 100\n 'D' -> if (last == 'C') n += 300 else n += 500\n 'M' -> if (last == 'C') n += 800 else n += 1000\n }\n last = c\n }\n return n\n}\n\nfun main(args: Array) {\n val romans = arrayOf(\"I\", \"III\", \"IV\", \"VIII\", \"XLIX\", \"CCII\", \"CDXXXIII\", \"MCMXC\", \"MMVIII\", \"MDCLXVI\")\n for (roman in romans) println(\"${roman.padEnd(10)} = ${romanDecode(roman)}\")\n}"} {"title": "Roman numerals/Encode", "language": "Kotlin", "task": "Create a function taking a positive integer as its parameter and returning a string containing the Roman numeral representation of that integer. Modern Roman numerals are written by expressing each digit separately, starting with the left most digit and skipping any digit with a value of zero. \n\n\nIn Roman numerals:\n* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC\n* 2008 is written as 2000=MM, 8=VIII; or MMVIII\n* 1666 uses each Roman symbol in descending order: MDCLXVI\n\n", "solution": "val romanNumerals = mapOf(\n 1000 to \"M\",\n 900 to \"CM\",\n 500 to \"D\",\n 400 to \"CD\",\n 100 to \"C\",\n 90 to \"XC\",\n 50 to \"L\",\n 40 to \"XL\",\n 10 to \"X\",\n 9 to \"IX\",\n 5 to \"V\",\n 4 to \"IV\",\n 1 to \"I\"\n)\n\nfun encode(number: Int): String? {\n if (number > 5000 || number < 1) {\n return null\n }\n var num = number\n var result = \"\"\n for ((multiple, numeral) in romanNumerals.entries) {\n while (num >= multiple) {\n num -= multiple\n result += numeral\n }\n }\n return result\n}\n\nfun main(args: Array) {\n println(encode(1990))\n println(encode(1666))\n println(encode(2008))\n}"} {"title": "Runge-Kutta method", "language": "Kotlin", "task": "Given the example Differential equation:\n:y'(t) = t \\times \\sqrt {y(t)}\nWith initial condition:\n:t_0 = 0 and y_0 = y(t_0) = y(0) = 1\nThis equation has an exact solution:\n:y(t) = \\tfrac{1}{16}(t^2 +4)^2\n\n\n;Task\nDemonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.\n* Solve the given differential equation over the range t = 0 \\ldots 10 with a step value of \\delta t=0.1 (101 total points, the first being given)\n* Print the calculated values of y at whole numbered t's (0.0, 1.0, \\ldots 10.0) along with error as compared to the exact solution.\n\n\n;Method summary\nStarting with a given y_n and t_n calculate:\n:\\delta y_1 = \\delta t\\times y'(t_n, y_n)\\quad\n:\\delta y_2 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_1)\n:\\delta y_3 = \\delta t\\times y'(t_n + \\tfrac{1}{2}\\delta t , y_n + \\tfrac{1}{2}\\delta y_2)\n:\\delta y_4 = \\delta t\\times y'(t_n + \\delta t , y_n + \\delta y_3)\\quad\nthen:\n:y_{n+1} = y_n + \\tfrac{1}{6} (\\delta y_1 + 2\\delta y_2 + 2\\delta y_3 + \\delta y_4)\n:t_{n+1} = t_n + \\delta t\\quad\n\n", "solution": "// version 1.1.2\n\ntypealias Y = (Double) -> Double\ntypealias Yd = (Double, Double) -> Double\n\nfun rungeKutta4(t0: Double, tz: Double, dt: Double, y: Y, yd: Yd) {\n var tn = t0\n var yn = y(tn)\n val z = ((tz - t0) / dt).toInt()\n for (i in 0..z) {\n if (i % 10 == 0) {\n val exact = y(tn)\n val error = yn - exact\n println(\"%4.1f %10f %10f %9f\".format(tn, yn, exact, error))\n }\n if (i == z) break\n val dy1 = dt * yd(tn, yn)\n val dy2 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy1)\n val dy3 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy2)\n val dy4 = dt * yd(tn + dt, yn + dy3)\n yn += (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0\n tn += dt\n }\n}\n\nfun main(args: Array) {\n println(\" T RK4 Exact Error\")\n println(\"---- ---------- ---------- ---------\")\n val y = fun(t: Double): Double {\n val x = t * t + 4.0\n return x * x / 16.0\n }\n val yd = fun(t: Double, yt: Double) = t * Math.sqrt(yt)\n rungeKutta4(0.0, 10.0, 0.1, y, yd)\n}"} {"title": "Runtime evaluation", "language": "Kotlin", "task": "Demonstrate a language's ability for programs to execute code written in the language provided at runtime. \n\nShow what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution.\n\nYou may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform.\n\nFor a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].\n\n", "solution": "Kotlin has a REPL which is started from the command line by running the compiler without any parameters.\n\nAny valid Kotlin code can then be entered and immediately evaluated.\n\nBelow is a sample session.\n\n\n$ kotlinc\nWelcome to Kotlin version 1.2.31 (JRE 1.8.0_162-8u162-b12-0ubuntu0.16.04.2-b12)\nType :help for help, :quit for quit\n>>> 20 + 22\n42\n>>> 5 * Math.sqrt(81.0)\n45.0\n>>> fun triple(x: Int) = x * 3\n>>> triple(16)\n48\n>>> :quit\n\n\n"} {"title": "Runtime evaluation/In an environment", "language": "Kotlin from JavaScript", "task": "Given a program in the language (as a string or AST) with a free variable named x (or another name if that is not valid syntax), evaluate it with x bound to a provided value, then evaluate it again with x bound to another provided value, then subtract the result of the first from the second and return or print it.\n\nDo so in a way which:\n* does not involve string manipulation of the input source code\n* is plausibly extensible to a runtime-chosen set of bindings rather than just x\n* does not make x a ''global'' variable\n\n\nor note that these are impossible.\n\n\n;See also:\n* For more general examples and language-specific details, see [[Eval]].\n* [[Dynamic variable names]] is a similar task.\n\n", "solution": "// Kotlin JS version 1.1.4-3\n\nfun evalWithX(expr: String, a: Double, b: Double) {\n var x = a\n val atA = eval(expr)\n x = b\n val atB = eval(expr)\n return atB - atA\n}\n\nfun main(args: Array) {\n println(evalWithX(\"Math.exp(x)\", 0.0, 1.0))\n}"} {"title": "SHA-1", "language": "Kotlin", "task": "'''SHA-1''' or '''SHA1''' is a one-way hash function; \nit computes a 160-bit message digest. \nSHA-1 often appears in security protocols; for example, \nmany HTTPS websites use RSA with SHA-1 to secure their connections. \nBitTorrent uses SHA-1 to verify downloads. \nGit and Mercurial use SHA-1 digests to identify commits.\n\nA US government standard, FIPS 180-1, defines SHA-1.\n\nFind the SHA-1 message digest for a string of [[octet]]s. You may either call a SHA-1 library, or implement SHA-1 in your language. Both approaches interest Rosetta Code.\n\n{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer. \nThis is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1. \nFor production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}\n", "solution": "// version 1.0.6\n\nimport java.security.MessageDigest\n\nfun main(args: Array) {\n val text = \"Rosetta Code\"\n val bytes = text.toByteArray()\n val md = MessageDigest.getInstance(\"SHA-1\")\n val digest = md.digest(bytes)\n for (byte in digest) print(\"%02x\".format(byte))\n println() \n}"} {"title": "Sailors, coconuts and a monkey problem", "language": "Kotlin", "task": "Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. \n\nThat night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides \"his\" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed.\n\nTo cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey.\n\nIn the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)\n\n\n;The task:\n# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.\n# Use a method that assumes an answer is possible, and then applies the constraints of the tale to see if it is correct. (I.e. no applying some formula that generates the correct answer without integer divisions and remainders and tests on remainders; but constraint solvers ''are'' allowed.)\n# Calculate the size of the initial pile of coconuts if six sailors were marooned and went through a similar process (but split into six piles instead of five of course).\n# Show your answers here.\n\n\n;Extra credit (optional):\n* Give some indication of the number of coconuts each sailor hides during the night.\n\n\n;Note:\n* Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc can occur in time fitting the story line, so as not to affect the mathematics.\n* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!\n\n\n;C.f:\n* Monkeys and Coconuts - Numberphile (Video) Analytical solution.\n* A002021: Pile of coconuts problem The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n var coconuts = 11\n outer@ for (ns in 2..9) {\n val hidden = IntArray(ns)\n coconuts = (coconuts / ns) * ns + 1\n while (true) { \n var nc = coconuts\n for (s in 1..ns) {\n if (nc % ns == 1) {\n hidden[s - 1] = nc / ns \n nc -= hidden[s - 1] + 1\n if (s == ns && nc % ns == 0) {\n println(\"$ns sailors require a minimum of $coconuts coconuts\")\n for (t in 1..ns) println(\"\\tSailor $t hides ${hidden[t - 1]}\")\n println(\"\\tThe monkey gets $ns\")\n println(\"\\tFinally, each sailor takes ${nc / ns}\\n\") \n continue@outer\n }\n } \n else break\n } \n coconuts += ns\n }\n }\n}"} {"title": "Self-describing numbers", "language": "Kotlin", "task": "{{task}}There are several so-called \"self-describing\" or \"self-descriptive\" integers.\n\nAn integer is said to be \"self-describing\" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that that digit appears in the number.\n\nFor example, '''2020''' is a four-digit self describing number:\n\n* position 0 has value 2 and there are two 0s in the number;\n* position 1 has value 0 and there are no 1s in the number;\n* position 2 has value 2 and there are two 2s;\n* position 3 has value 0 and there are zero 3s.\n\n\nSelf-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.\n\n\n;Task Description\n# Write a function/routine/method/... that will check whether a given positive integer is self-describing.\n# As an optional stretch goal - generate and display the set of self-describing numbers.\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-referential sequence]]\n* [[Spelling of ordinal numbers]]\n\n", "solution": "// version 1.0.6\n\nfun selfDescribing(n: Int): Boolean {\n if (n <= 0) return false\n val ns = n.toString()\n val count = IntArray(10)\n var nn = n\n while (nn > 0) {\n count[nn % 10] += 1\n nn /= 10\n }\n for (i in 0 until ns.length) \n if( ns[i] - '0' != count[i]) return false\n return true\n}\n\nfun main(args: Array) {\n println(\"The self-describing numbers less than 100 million are:\")\n for (i in 0..99999999) if (selfDescribing(i)) print(\"$i \")\n println()\n}"} {"title": "Self numbers", "language": "Kotlin from Java", "task": "A number n is a self number if there is no number g such that g + the sum of g's digits = n. So 18 is not a self number because 9+9=18, 43 is not a self number because 35+5+3=43.\n\nThe task is:\n Display the first 50 self numbers;\n I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.\n\n224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.\n\n;See also: \n\n;*OEIS: A003052 - Self numbers or Colombian numbers\n;*Wikipedia: Self numbers\n\n", "solution": "private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1\nprivate val SV = BooleanArray(MC + 1)\n\nprivate fun sieve() {\n val dS = IntArray(10000)\n run {\n var a = 9\n var i = 9999\n while (a >= 0) {\n for (b in 9 downTo 0) {\n var c = 9\n val s = a + b\n while (c >= 0) {\n var d = 9\n val t = s + c\n while (d >= 0) {\n dS[i--] = t + d\n d--\n }\n c--\n }\n }\n a--\n }\n }\n var a = 0\n var n = 0\n while (a < 103) {\n var b = 0\n val d = dS[a]\n while (b < 1000) {\n var c = 0\n var s = d + dS[b] + n\n while (c < 10000) {\n SV[dS[c] + s++] = true\n c++\n }\n b++\n n += 10000\n }\n a++\n }\n}\n\nfun main() {\n sieve()\n println(\"The first 50 self numbers are:\")\n run {\n var i = 0\n var count = 0\n while (count <= 50) {\n if (!SV[i]) {\n count++\n if (count <= 50) {\n print(\"$i \")\n } else {\n println()\n println()\n println(\" Index Self number\")\n }\n }\n i++\n }\n }\n var i = 0\n var limit = 1\n var count = 0\n while (i < MC) {\n if (!SV[i]) {\n if (++count == limit) {\n println(\"%,12d %,13d\".format(count, i))\n limit *= 10\n }\n }\n i++\n }\n}"} {"title": "Semordnilap", "language": "Kotlin from D", "task": "A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. \"Semordnilap\" is a word that itself is a semordnilap.\n\nExample: ''lager'' and ''regal''\n \n;Task\nThis task does not consider semordnilap phrases, only single words.\nUsing only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.\nTwo matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.\n(Note that the word \"semordnilap\" is not in the above dictionary.)\n\n\n\n", "solution": "// version 1.2.0\n\nimport java.io.File\n \nfun main(args: Array) {\n val words = File(\"unixdict.txt\").readLines().toSet()\n val pairs = words.map { Pair(it, it.reversed()) }\n .filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches\n println(\"Found ${pairs.size} semordnilap pairs\")\n println(pairs.take(5))\n}"} {"title": "Sequence: nth number with exactly n divisors", "language": "Kotlin from Go", "task": "Calculate the sequence where each term an is the nth that has '''n''' divisors.\n\n;Task\n\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n;See also\n\n:*OEIS:A073916\n\n;Related tasks\n\n:*[[Sequence: smallest number greater than previous term with exactly n divisors]]\n:*[[Sequence: smallest number with exactly n divisors]]\n\n", "solution": "// Version 1.3.21\n\nimport java.math.BigInteger\nimport kotlin.math.sqrt\n\nconst val MAX = 33\n\nfun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)\n\nfun generateSmallPrimes(n: Int): List {\n val primes = mutableListOf()\n primes.add(2)\n var i = 3\n while (primes.size < n) {\n if (isPrime(i)) {\n primes.add(i)\n }\n i += 2\n }\n return primes\n}\n\nfun countDivisors(n: Int): Int {\n var nn = n\n var count = 1\n while (nn % 2 == 0) {\n nn = nn shr 1\n count++\n }\n var d = 3\n while (d * d <= nn) {\n var q = nn / d\n var r = nn % d\n if (r == 0) {\n var dc = 0\n while (r == 0) {\n dc += count\n nn = q\n q = nn / d\n r = nn % d\n }\n count += dc\n }\n d += 2\n }\n if (nn != 1) count *= 2\n return count\n}\n\nfun main() {\n var primes = generateSmallPrimes(MAX)\n println(\"The first $MAX terms in the sequence are:\")\n for (i in 1..MAX) {\n if (isPrime(i)) {\n var z = BigInteger.valueOf(primes[i - 1].toLong())\n z = z.pow(i - 1)\n System.out.printf(\"%2d : %d\\n\", i, z)\n } else {\n var count = 0\n var j = 1\n while (true) {\n if (i % 2 == 1) {\n val sq = sqrt(j.toDouble()).toInt()\n if (sq * sq != j) {\n j++\n continue\n }\n }\n if (countDivisors(j) == i) {\n if (++count == i) {\n System.out.printf(\"%2d : %d\\n\", i, j)\n break\n }\n }\n j++\n }\n }\n }\n}"} {"title": "Sequence: smallest number greater than previous term with exactly n divisors", "language": "Kotlin from Go", "task": "Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;See also\n:* OEIS:A069654\n\n\n;Related tasks\n:* [[Sequence: smallest number with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n", "solution": "// Version 1.3.21\n\nconst val MAX = 15\n\nfun countDivisors(n: Int): Int {\n var count = 0\n var i = 1\n while (i * i <= n) {\n if (n % i == 0) {\n count += if (i == n / i) 1 else 2\n }\n i++\n }\n return count\n}\n\nfun main() {\n println(\"The first $MAX terms of the sequence are:\")\n var i = 1\n var next = 1\n while (next <= MAX) {\n if (next == countDivisors(i)) {\n print(\"$i \")\n next++\n }\n i++\n }\n println()\n}"} {"title": "Sequence: smallest number with exactly n divisors", "language": "Kotlin from Go", "task": "Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.\n\n\n;Task\nShow here, on this page, at least the first '''15''' terms of the sequence.\n\n\n;Related tasks:\n:* [[Sequence: smallest number greater than previous term with exactly n divisors]]\n:* [[Sequence: nth number with exactly n divisors]]\n\n\n;See also:\n:* OEIS:A005179\n\n", "solution": "// Version 1.3.21\n\nconst val MAX = 15\n\nfun countDivisors(n: Int): Int {\n var count = 0\n var i = 1\n while (i * i <= n) {\n if (n % i == 0) {\n count += if (i == n / i) 1 else 2\n }\n i++\n }\n return count\n}\n\nfun main() {\n var seq = IntArray(MAX)\n println(\"The first $MAX terms of the sequence are:\")\n var i = 1\n var n = 0\n while (n < MAX) {\n var k = countDivisors(i)\n if (k <= MAX && seq[k - 1] == 0) {\n seq[k - 1] = i\n n++\n }\n i++\n }\n println(seq.asList())\n}"} {"title": "Set consolidation", "language": "Kotlin", "task": "Given two sets of items then if any item is common to any set then the result of applying ''consolidation'' to those sets is a set of sets whose contents is:\n* The two input sets if no common item exists between the two input sets of items.\n* The single set that is the union of the two input sets if they share a common item.\n\nGiven N sets of items where N>2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible.\nIf N<2 then consolidation has no strict meaning and the input can be returned.\n\n;'''Example 1:'''\n:Given the two sets {A,B} and {C,D} then there is no common element between the sets and the result is the same as the input.\n;'''Example 2:'''\n:Given the two sets {A,B} and {B,D} then there is a common element B between the sets and the result is the single set {B,D,A}. (Note that order of items in a set is immaterial: {A,B,D} is the same as {B,D,A} and {D,A,B}, etc).\n;'''Example 3:'''\n:Given the three sets {A,B} and {C,D} and {D,B} then there is no common element between the sets {A,B} and {C,D} but the sets {A,B} and {D,B} do share a common element that consolidates to produce the result {B,D,A}. On examining this result with the remaining set, {C,D}, they share a common element and so consolidate to the final output of the single set {A,B,C,D}\n;'''Example 4:'''\n:The consolidation of the five sets:\n::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}\n:Is the two sets:\n::{A, C, B, D}, and {G, F, I, H, K}\n\n'''See also'''\n* Connected component (graph theory)\n* [[Range consolidation]]\n\n", "solution": "// version 1.0.6\n\nfun> consolidateSets(sets: Array>): Set> {\n val size = sets.size\n val consolidated = BooleanArray(size) // all false by default\n var i = 0\n while (i < size - 1) {\n if (!consolidated[i]) {\n while (true) {\n var intersects = 0\n for (j in (i + 1) until size) {\n if (consolidated[j]) continue \n if (sets[i].intersect(sets[j]).isNotEmpty()) {\n sets[i] = sets[i].union(sets[j])\n consolidated[j] = true\n intersects++\n }\n }\n if (intersects == 0) break\n }\n }\n i++\n }\n return (0 until size).filter { !consolidated[it] }.map { sets[it].toSortedSet() }.toSet() \n} \n \nfun main(args: Array) {\n val unconsolidatedSets = arrayOf(\n arrayOf(setOf('A', 'B'), setOf('C', 'D')),\n arrayOf(setOf('A', 'B'), setOf('B', 'D')),\n arrayOf(setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B')),\n arrayOf(setOf('H', 'I', 'K'), setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B'), setOf('F', 'G', 'H')) \n )\n for (sets in unconsolidatedSets) println(consolidateSets(sets))\n}"} {"title": "Set of real numbers", "language": "Kotlin", "task": "All real numbers form the uncountable set R. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers ''a'' and ''b'' where ''a'' <= ''b''. There are actually four cases for the meaning of \"between\", depending on open or closed boundary:\n* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }\n* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }\n* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }\n* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }\nNote that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.\n\n'''Task'''\n* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.\n* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):\n:* ''x'' ''A'': determine if ''x'' is an element of ''A''\n:: example: 1 is in [1, 2), while 2, 3, ... are not.\n:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}\n:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]\n:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set\n:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \\ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}\n:: example: [0, 2) - (1, 3) = [0, 1]\n* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:\n:* (0, 1] [0, 2)\n:* [0, 2) (1, 2]\n:* [0, 3) - (0, 1)\n:* [0, 3) - [0, 1]\n\n'''Implementation notes'''\n* 'Any' real set means 'sets that can be expressed as the union of a finite number of convex real sets'. Cantor's set needs not apply.\n* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.\n* You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is).\n\n'''Optional work'''\n* Create a function to determine if a given set is empty (contains no element).\n* Define ''A'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x''2)| > 1/2 }, ''B'' = {''x'' | 0 < ''x'' < 10 and |sin(p ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' - ''B''. Note that \n|sin(p ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself.\n\n", "solution": "// version 1.1.4-3\n\ntypealias RealPredicate = (Double) -> Boolean\n\nenum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }\n\nclass RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {\n\n constructor (start: Double, end: Double, rangeType: RangeType): this(start, end,\n when (rangeType) {\n RangeType.CLOSED -> fun(d: Double) = d in start..end\n RangeType.BOTH_OPEN -> fun(d: Double) = start < d && d < end\n RangeType.LEFT_OPEN -> fun(d: Double) = start < d && d <= end \n RangeType.RIGHT_OPEN -> fun(d: Double) = start <= d && d < end\n }\n )\n\n fun contains(d: Double) = predicate(d)\n\n infix fun union(other: RealSet): RealSet {\n val low2 = minOf(low, other.low)\n val high2 = maxOf(high, other.high)\n return RealSet(low2, high2) { predicate(it) || other.predicate(it) }\n }\n \n infix fun intersect(other: RealSet): RealSet {\n val low2 = maxOf(low, other.low)\n val high2 = minOf(high, other.high)\n return RealSet(low2, high2) { predicate(it) && other.predicate(it) } \n }\n\n infix fun subtract(other: RealSet) = RealSet(low, high) { predicate(it) && !other.predicate(it) }\n\n var interval = 0.00001\n\n val length: Double get() {\n if (!low.isFinite() || !high.isFinite()) return -1.0 // error value\n if (high <= low) return 0.0\n var p = low\n var count = 0\n do {\n if (predicate(p)) count++\n p += interval\n }\n while (p < high)\n return count * interval\n }\n\n fun isEmpty() = if (high == low) !predicate(low) else length == 0.0\n}\n\nfun main(args: Array) {\n val a = RealSet(0.0, 1.0, RangeType.LEFT_OPEN)\n val b = RealSet(0.0, 2.0, RangeType.RIGHT_OPEN)\n val c = RealSet(1.0, 2.0, RangeType.LEFT_OPEN)\n val d = RealSet(0.0, 3.0, RangeType.RIGHT_OPEN)\n val e = RealSet(0.0, 1.0, RangeType.BOTH_OPEN)\n val f = RealSet(0.0, 1.0, RangeType.CLOSED)\n val g = RealSet(0.0, 0.0, RangeType.CLOSED)\n\n for (i in 0..2) {\n val dd = i.toDouble()\n println(\"(0, 1] \u222a [0, 2) contains $i is ${(a union b).contains(dd)}\")\n println(\"[0, 2) \u2229 (1, 2] contains $i is ${(b intersect c).contains(dd)}\")\n println(\"[0, 3) \u2212 (0, 1) contains $i is ${(d subtract e).contains(dd)}\")\n println(\"[0, 3) \u2212 [0, 1] contains $i is ${(d subtract f).contains(dd)}\\n\")\n }\n\n println(\"[0, 0] is empty is ${g.isEmpty()}\\n\") \n\n val aa = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) && \n Math.abs(Math.sin(Math.PI * x * x)) > 0.5 }\n val bb = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) &&\n Math.abs(Math.sin(Math.PI * x)) > 0.5 }\n val cc = aa subtract bb\n println(\"Approx length of A - B is ${cc.length}\")\n}"} {"title": "Shoelace formula for polygonal area", "language": "Kotlin", "task": "Given the n + 1 vertices x[0], y[0] .. x[N], y[N] of a simple polygon described in a clockwise direction, then the polygon's area can be calculated by:\n\nabs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -\n (sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])\n ) / 2\n(Where abs returns the absolute value)\n\n;Task:\nWrite a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:\n (3,4), (5,11), (12,8), (9,5), and (5,6) \n\n\nShow the answer here, on this page.\n\n", "solution": "// version 1.1.3\n\nclass Point(val x: Int, val y: Int) {\n override fun toString() = \"($x, $y)\"\n}\n \nfun shoelaceArea(v: List): Double {\n val n = v.size\n var a = 0.0\n for (i in 0 until n - 1) { \n a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y\n }\n return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0 \n}\n\nfun main(args: Array) {\n val v = listOf(\n Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6)\n )\n val area = shoelaceArea(v) \n println(\"Given a polygon with vertices at $v,\")\n println(\"its area is $area\")\n}"} {"title": "Shortest common supersequence", "language": "Kotlin", "task": "The '''shortest common supersequence''' is a problem closely related to the [[longest common subsequence]], which you can use as an external function for this task.\n\n\n;;Task:\nGiven two strings u and v, find the shortest possible sequence s, which is the shortest common super-sequence of u and v where both u and v are a subsequence of s. Defined as such, s is not necessarily unique.\n\nDemonstrate this by printing s where u = \"abcbdab\" and v = \"bdcaba\".\n\n\n\n;Also see:\n* Wikipedia: shortest common supersequence \n\n", "solution": "// version 1.1.2\n\nfun lcs(x: String, y: String): String {\n if (x.length == 0 || y.length == 0) return \"\"\n val x1 = x.dropLast(1) \n val y1 = y.dropLast(1)\n if (x.last() == y.last()) return lcs(x1, y1) + x.last()\n val x2 = lcs(x, y1)\n val y2 = lcs(x1, y)\n return if (x2.length > y2.length) x2 else y2\n}\n\nfun scs(u: String, v: String): String{\n val lcs = lcs(u, v)\n var ui = 0\n var vi = 0\n val sb = StringBuilder()\n for (i in 0 until lcs.length) {\n while (ui < u.length && u[ui] != lcs[i]) sb.append(u[ui++]) \n while (vi < v.length && v[vi] != lcs[i]) sb.append(v[vi++])\n sb.append(lcs[i])\n ui++; vi++\n }\n if (ui < u.length) sb.append(u.substring(ui))\n if (vi < v.length) sb.append(v.substring(vi))\n return sb.toString()\n}\n \nfun main(args: Array) {\n val u = \"abcbdab\"\n val v = \"bdcaba\" \n println(scs(u, v))\n}"} {"title": "Show ASCII table", "language": "Kotlin from Go", "task": "Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.\n\n\n\n", "solution": "// Version 1.2.60\n\nfun main(args: Array) {\n for (i in 0..15) {\n for (j in 32 + i..127 step 16) {\n val k = when (j) {\n 32 -> \"Spc\"\n 127 -> \"Del\"\n else -> j.toChar().toString()\n }\n System.out.printf(\"%3d : %-3s \", j, k)\n }\n println()\n }\n}"} {"title": "Show the epoch", "language": "Kotlin from Java", "task": "Choose popular date libraries used by your language and show the epoch those libraries use. \n\nA demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. \n\nFor consistency's sake, show the date in UTC time where possible.\n\n\n;Related task:\n* [[Date format]]\n\n", "solution": "// version 1.1.2\n\nimport java.util.Date\nimport java.util.TimeZone\nimport java.text.DateFormat\n\nfun main( args: Array) {\n val epoch = Date(0)\n val format = DateFormat.getDateTimeInstance()\n format.timeZone = TimeZone.getTimeZone(\"UTC\")\n println(format.format(epoch))\n}"} {"title": "Sierpinski pentagon", "language": "Kotlin from Java", "task": "Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.\n\n\n;See also\n* Sierpinski pentagon\n\n", "solution": "// version 1.1.2\n\nimport java.awt.*\nimport java.awt.geom.Path2D\nimport java.util.Random\nimport javax.swing.*\n\nclass SierpinskiPentagon : JPanel() {\n // exterior angle\n private val degrees072 = Math.toRadians(72.0)\n\n /* After scaling we'll have 2 sides plus a gap occupying the length\n of a side before scaling. The gap is the base of an isosceles triangle\n with a base angle of 72 degrees. */\n private val scaleFactor = 1.0 / (2.0 + Math.cos(degrees072) * 2.0)\n\n private val margin = 20\n private var limit = 0\n private val r = Random()\n\n init {\n preferredSize = Dimension(640, 640)\n background = Color.white\n Timer(3000) {\n limit++\n if (limit >= 5) limit = 0\n repaint()\n }.start()\n }\n\n private fun drawPentagon(g: Graphics2D, x: Double, y: Double, s: Double, depth: Int) {\n var angle = 3.0 * degrees072 // starting angle\n var xx = x\n var yy = y\n var side = s\n if (depth == 0) {\n val p = Path2D.Double()\n p.moveTo(xx, yy)\n\n // draw from the top\n for (i in 0 until 5) {\n xx += Math.cos(angle) * side\n yy -= Math.sin(angle) * side\n p.lineTo(xx, yy)\n angle += degrees072\n }\n\n g.color = RandomHue.next()\n g.fill(p)\n }\n else {\n side *= scaleFactor\n /* Starting at the top of the highest pentagon, calculate\n the top vertices of the other pentagons by taking the\n length of the scaled side plus the length of the gap. */\n val distance = side + side * Math.cos(degrees072) * 2.0\n\n /* The top positions form a virtual pentagon of their own,\n so simply move from one to the other by changing direction. */\n for (i in 0 until 5) {\n xx += Math.cos(angle) * distance\n yy -= Math.sin(angle) * distance\n drawPentagon(g, xx, yy, side, depth - 1)\n angle += degrees072\n }\n }\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)\n val hw = width / 2\n val radius = hw - 2.0 * margin\n val side = radius * Math.sin(Math.PI / 5.0) * 2.0\n drawPentagon(g, hw.toDouble(), 3.0 * margin, side, limit)\n }\n\n private class RandomHue {\n /* Try to avoid random color values clumping together */\n companion object {\n val goldenRatioConjugate = (Math.sqrt(5.0) - 1.0) / 2.0\n var hue = Math.random()\n\n fun next(): Color {\n hue = (hue + goldenRatioConjugate) % 1\n return Color.getHSBColor(hue.toFloat(), 1.0f, 1.0f)\n }\n }\n }\n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n f.title = \"Sierpinski Pentagon\"\n f.isResizable = true\n f.add(SierpinskiPentagon(), BorderLayout.CENTER)\n f.pack()\n f.setLocationRelativeTo(null)\n f.isVisible = true\n }\n}"} {"title": "Sierpinski triangle/Graphical", "language": "Kotlin", "task": "Produce a graphical representation of a Sierpinski triangle of order N in any orientation. \n\nAn example of Sierpinski's triangle (order = 8) looks like this: \n[[File:Sierpinski_Triangle_Unicon.PNG]]\n\n", "solution": "import java.awt.*\nimport javax.swing.JFrame\nimport javax.swing.JPanel\n\nfun main(args: Array) {\n var i = 8 // Default\n if (args.any()) {\n try {\n i = args.first().toInt()\n } catch (e: NumberFormatException) {\n i = 8\n println(\"Usage: 'java SierpinskyTriangle [level]'\\nNow setting level to $i\")\n }\n }\n\n object : JFrame(\"Sierpinsky Triangle - Kotlin\") {\n val panel = object : JPanel() {\n val size = 800\n\n init {\n preferredSize = Dimension(size, size)\n }\n\n public override fun paintComponent(g: Graphics) {\n g.color = Color.BLACK\n if (g is Graphics2D) {\n g.drawSierpinskyTriangle(i, 20, 20, size - 40)\n }\n }\n }\n\n init {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n add(panel)\n pack()\n isResizable = false\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}\n\ninternal fun Graphics2D.drawSierpinskyTriangle(level: Int, x: Int, y: Int, size: Int) {\n if (level > 0) {\n drawLine(x, y, x + size, y)\n drawLine(x, y, x, y + size)\n drawLine(x + size, y, x, y + size)\n\n drawSierpinskyTriangle(level - 1, x, y, size / 2)\n drawSierpinskyTriangle(level - 1, x + size / 2, y, size / 2)\n drawSierpinskyTriangle(level - 1, x, y + size / 2, size / 2)\n }\n}"} {"title": "Smith numbers", "language": "Kotlin from FreeBASIC", "task": "sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. \n\nBy definition, all primes are ''excluded'' as they (naturally) satisfy this condition!\n\nSmith numbers are also known as ''joke'' numbers.\n\n\n;Example\nUsing the number '''166'''\nFind the prime factors of '''166''' which are: '''2''' x '''83'''\nThen, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''\nThen, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''\nTherefore, the number '''166''' is a Smith number.\n\n\n;Task\nWrite a program to find all Smith numbers ''below'' 10000.\n\n\n;See also\n* from Wikipedia: [Smith number].\n* from MathWorld: [Smith number]. \n* from OEIS A6753: [OEIS sequence A6753].\n* from OEIS A104170: [Number of Smith numbers below 10^n]. \n* from The Prime pages: [Smith numbers].\n\n", "solution": "// version 1.0.6\n\nfun getPrimeFactors(n: Int): MutableList {\n val factors = mutableListOf()\n if (n < 2) return factors\n var factor = 2\n var nn = n\n while (true) {\n if (nn % factor == 0) {\n factors.add(factor)\n nn /= factor\n if (nn == 1) return factors\n }\n else if (factor >= 3) factor += 2\n else factor = 3\n }\n}\n\nfun sumDigits(n: Int): Int = when {\n n < 10 -> n\n else -> {\n var sum = 0\n var nn = n\n while (nn > 0) {\n sum += (nn % 10)\n nn /= 10\n }\n sum\n }\n }\n\nfun isSmith(n: Int): Boolean {\n if (n < 2) return false\n val factors = getPrimeFactors(n)\n if (factors.size == 1) return false\n val primeSum = factors.sumBy { sumDigits(it) }\n return sumDigits(n) == primeSum\n}\n\nfun main(args: Array) {\n println(\"The Smith numbers below 10000 are:\\n\")\n var count = 0\n for (i in 2 until 10000) {\n if (isSmith(i)) {\n print(\"%5d\".format(i))\n count++\n }\n }\n println(\"\\n\\n$count numbers found\")\n}"} {"title": "Solve a Hidato puzzle", "language": "Kotlin from Java", "task": "The task is to write a program which solves Hidato (aka Hidoku) puzzles.\n\nThe rules are:\n* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.\n** The grid is not necessarily rectangular.\n** The grid may have holes in it.\n** The grid is always connected.\n** The number \"1\" is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.\n** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.\n* The aim is to place a natural number in each blank square so that in the sequence of numbered squares from \"1\" upwards, each square is in the [[wp:Moore neighborhood]] of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).\n** Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.\n** A square may only contain one number.\n* In a proper Hidato puzzle, the solution is unique.\n\nFor example the following problem\nSample Hidato problem, from Wikipedia\n\nhas the following solution, with path marked on it:\n\nSolution to sample Hidato problem\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[N-queens problem]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]];\n\n", "solution": "// version 1.2.0\n\nlateinit var board: List\nlateinit var given: IntArray\nlateinit var start: IntArray\n\nfun setUp(input: List) {\n val nRows = input.size\n val puzzle = List(nRows) { input[it].split(\" \") }\n val nCols = puzzle[0].size\n val list = mutableListOf()\n board = List(nRows + 2) { IntArray(nCols + 2) { -1 } }\n for (r in 0 until nRows) {\n val row = puzzle[r]\n for (c in 0 until nCols) {\n val cell = row[c]\n if (cell == \"_\") {\n board[r + 1][c + 1] = 0\n }\n else if (cell != \".\") {\n val value = cell.toInt()\n board[r + 1][c + 1] = value\n list.add(value)\n if (value == 1) start = intArrayOf(r + 1, c + 1)\n }\n }\n }\n list.sort()\n given = list.toIntArray()\n}\n\nfun solve(r: Int, c: Int, n: Int, next: Int): Boolean {\n if (n > given[given.lastIndex]) return true\n val back = board[r][c]\n if (back != 0 && back != n) return false\n if (back == 0 && given[next] == n) return false\n var next2 = next\n if (back == n) next2++\n board[r][c] = n\n for (i in -1..1)\n for (j in -1..1)\n if (solve(r + i, c + j, n + 1, next2)) return true\n board[r][c] = back\n return false\n}\n\nfun printBoard() {\n for (row in board) {\n for (c in row) {\n if (c == -1)\n print(\" . \")\n else\n print(if (c > 0) \"%2d \".format(c) else \"__ \")\n }\n println()\n }\n}\n\nfun main(args: Array) {\n var input = listOf(\n \"_ 33 35 _ _ . . .\",\n \"_ _ 24 22 _ . . .\",\n \"_ _ _ 21 _ _ . .\",\n \"_ 26 _ 13 40 11 . .\",\n \"27 _ _ _ 9 _ 1 .\",\n \". . _ _ 18 _ _ .\",\n \". . . . _ 7 _ _\",\n \". . . . . . 5 _\"\n )\n setUp(input)\n printBoard()\n println(\"\\nFound:\")\n solve(start[0], start[1], 1, 0)\n printBoard()\n}"} {"title": "Solve a Holy Knight's tour", "language": "Kotlin from Python", "task": "Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. \n\nThis kind of knight's tour puzzle is similar to Hidato.\n\nThe present task is to produce a solution to such problems. At least demonstrate your program by solving the following:\n\n\n;Example:\n\n 0 0 0 \n 0 0 0 \n 0 0 0 0 0 0 0\n0 0 0 0 0\n0 0 0 0 0\n1 0 0 0 0 0 0\n 0 0 0\n 0 0 0\n\n\nNote that the zeros represent the available squares, not the pennies.\n\nExtra credit is available for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Hopido puzzle]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// version 1.1.3\n\nval moves = arrayOf(\n intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2),\n intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1)\n)\n\nval board1 =\n \" xxx \" +\n \" x xx \" +\n \" xxxxxxx\" +\n \"xxx x x\" +\n \"x x xxx\" +\n \"sxxxxxx \" +\n \" xx x \" +\n \" xxx \"\n\nval board2 =\n \".....s.x.....\" +\n \".....x.x.....\" +\n \"....xxxxx....\" +\n \".....xxx.....\" +\n \"..x..x.x..x..\" +\n \"xxxxx...xxxxx\" +\n \"..xx.....xx..\" +\n \"xxxxx...xxxxx\" +\n \"..x..x.x..x..\" +\n \".....xxx.....\" +\n \"....xxxxx....\" +\n \".....x.x.....\" +\n \".....x.x.....\"\n\nfun solve(pz: Array, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean {\n if (idx > cnt) return true\n for (i in 0 until moves.size) {\n val x = sx + moves[i][0]\n val y = sy + moves[i][1]\n if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) {\n pz[x][y] = idx\n if (solve(pz, sz, x, y, idx + 1, cnt)) return true\n pz[x][y] = 0\n }\n }\n return false\n}\n\nfun findSolution(b: String, sz: Int) {\n val pz = Array(sz) { IntArray(sz) { -1 } }\n var x = 0\n var y = 0\n var idx = 0\n var cnt = 0\n for (j in 0 until sz) {\n for (i in 0 until sz) {\n if (b[idx] == 'x') {\n pz[i][j] = 0\n cnt++\n }\n else if (b[idx] == 's') {\n pz[i][j] = 1\n cnt++\n x = i\n y = j\n }\n idx++\n }\n }\n\n if (solve(pz, sz, x, y, 2, cnt)) {\n for (j in 0 until sz) {\n for (i in 0 until sz) {\n if (pz[i][j] != -1)\n print(\"%02d \".format(pz[i][j]))\n else\n print(\"-- \")\n }\n println()\n }\n }\n else println(\"Cannot solve this puzzle!\")\n}\n\nfun main(args: Array) {\n findSolution(board1, 8) \n println()\n findSolution(board2, 13)\n}"} {"title": "Solve a Hopido puzzle", "language": "Kotlin from Java", "task": "Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:\n\n\"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7x7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!\"\n\nKnowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.\n\nExample:\n\n . 0 0 . 0 0 .\n 0 0 0 0 0 0 0\n 0 0 0 0 0 0 0\n . 0 0 0 0 0 .\n . . 0 0 0 . .\n . . . 0 . . .\n\nExtra credits are available for other interesting designs.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Numbrix puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// version 1.2.0\n\nval board = listOf(\n \".00.00.\",\n \"0000000\",\n \"0000000\",\n \".00000.\",\n \"..000..\",\n \"...0...\"\n)\n\nval moves = listOf(\n -3 to 0, 0 to 3, 3 to 0, 0 to -3,\n 2 to 2, 2 to -2, -2 to 2, -2 to -2\n)\n\nlateinit var grid: List\nvar totalToFill = 0\n\nfun solve(r: Int, c: Int, count: Int): Boolean {\n if (count > totalToFill) return true\n val nbrs = neighbors(r, c)\n if (nbrs.isEmpty() && count != totalToFill) return false\n nbrs.sortBy { it[2] }\n for (nb in nbrs) {\n val rr = nb[0]\n val cc = nb[1]\n grid[rr][cc] = count\n if (solve(rr, cc, count + 1)) return true\n grid[rr][cc] = 0\n }\n return false\n}\n\nfun neighbors(r: Int, c: Int): MutableList {\n val nbrs = mutableListOf()\n for (m in moves) {\n val x = m.first\n val y = m.second\n if (grid[r + y][c + x] == 0) {\n val num = countNeighbors(r + y, c + x) - 1\n nbrs.add(intArrayOf(r + y, c + x, num))\n }\n }\n return nbrs\n}\n\nfun countNeighbors(r: Int, c: Int): Int {\n var num = 0\n for (m in moves)\n if (grid[r + m.second][c + m.first] == 0) num++\n return num\n}\n\nfun printResult() {\n for (row in grid) {\n for (i in row) {\n print(if (i == -1) \" \" else \"%2d \".format(i))\n }\n println()\n }\n}\n\nfun main(args: Array) {\n val nRows = board.size + 6\n val nCols = board[0].length + 6\n grid = List(nRows) { IntArray(nCols) { -1} }\n for (r in 0 until nRows) {\n for (c in 3 until nCols - 3) {\n if (r in 3 until nRows - 3) {\n if (board[r - 3][c - 3] == '0') {\n grid[r][c] = 0\n totalToFill++\n }\n }\n }\n }\n var pos = -1\n var rr: Int\n var cc: Int\n do {\n do {\n pos++\n rr = pos / nCols\n cc = pos % nCols\n }\n while (grid[rr][cc] == -1)\n\n grid[rr][cc] = 1\n if (solve(rr, cc, 2)) break\n grid[rr][cc] = 0\n }\n while (pos < nRows * nCols)\n\n printResult()\n}"} {"title": "Solve a Numbrix puzzle", "language": "Kotlin from Java", "task": "Numbrix puzzles are similar to Hidato. \nThe most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). \nPublished puzzles also tend not to have holes in the grid and may not always indicate the end node. \nTwo examples follow:\n\n;Example 1\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 0 46 45 0 55 74 0 0\n 0 38 0 0 43 0 0 78 0\n 0 35 0 0 0 0 0 71 0\n 0 0 33 0 0 0 59 0 0\n 0 17 0 0 0 0 0 67 0\n 0 18 0 0 11 0 0 64 0\n 0 0 24 21 0 1 2 0 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 49 50 51 52 53 54 75 76 81\n 48 47 46 45 44 55 74 77 80\n 37 38 39 40 43 56 73 78 79\n 36 35 34 41 42 57 72 71 70\n 31 32 33 14 13 58 59 68 69\n 30 17 16 15 12 61 60 67 66\n 29 18 19 20 11 62 63 64 65\n 28 25 24 21 10 1 2 3 4\n 27 26 23 22 9 8 7 6 5\n\n;Example 2\nProblem.\n\n 0 0 0 0 0 0 0 0 0\n 0 11 12 15 18 21 62 61 0\n 0 6 0 0 0 0 0 60 0\n 0 33 0 0 0 0 0 57 0\n 0 32 0 0 0 0 0 56 0\n 0 37 0 1 0 0 0 73 0\n 0 38 0 0 0 0 0 72 0\n 0 43 44 47 48 51 76 77 0\n 0 0 0 0 0 0 0 0 0\n\nSolution.\n\n 9 10 13 14 19 20 63 64 65\n 8 11 12 15 18 21 62 61 66\n 7 6 5 16 17 22 59 60 67\n 34 33 4 3 24 23 58 57 68\n 35 32 31 2 25 54 55 56 69\n 36 37 30 1 26 53 74 73 70\n 39 38 29 28 27 52 75 72 71\n 40 43 44 47 48 51 76 77 78\n 41 42 45 46 49 50 81 80 79\n\n;Task\nWrite a program to solve puzzles of this ilk, \ndemonstrating your program by solving the above examples. \nExtra credit for other interesting examples.\n\n\n;Related tasks:\n* [[A* search algorithm]]\n* [[Solve a Holy Knight's tour]]\n* [[Knight's tour]]\n* [[N-queens problem]]\n* [[Solve a Hidato puzzle]]\n* [[Solve a Holy Knight's tour]]\n* [[Solve a Hopido puzzle]]\n* [[Solve the no connection puzzle]]\n\n", "solution": "// version 1.2.0\n\nval example1 = listOf(\n \"00,00,00,00,00,00,00,00,00\",\n \"00,00,46,45,00,55,74,00,00\",\n \"00,38,00,00,43,00,00,78,00\",\n \"00,35,00,00,00,00,00,71,00\",\n \"00,00,33,00,00,00,59,00,00\",\n \"00,17,00,00,00,00,00,67,00\",\n \"00,18,00,00,11,00,00,64,00\",\n \"00,00,24,21,00,01,02,00,00\",\n \"00,00,00,00,00,00,00,00,00\"\n)\n\nval example2 = listOf(\n \"00,00,00,00,00,00,00,00,00\",\n \"00,11,12,15,18,21,62,61,00\",\n \"00,06,00,00,00,00,00,60,00\",\n \"00,33,00,00,00,00,00,57,00\",\n \"00,32,00,00,00,00,00,56,00\",\n \"00,37,00,01,00,00,00,73,00\",\n \"00,38,00,00,00,00,00,72,00\",\n \"00,43,44,47,48,51,76,77,00\",\n \"00,00,00,00,00,00,00,00,00\"\n)\n\nval moves = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)\n\nlateinit var board: List \nlateinit var grid: List\nlateinit var clues: IntArray\nvar totalToFill = 0\n\nfun solve(r: Int, c: Int, count: Int, nextClue: Int): Boolean {\n if (count > totalToFill) return true\n val back = grid[r][c]\n if (back != 0 && back != count) return false\n if (back == 0 && nextClue < clues.size && clues[nextClue] == count) {\n return false\n }\n var nextClue2 = nextClue\n if (back == count) nextClue2++\n grid[r][c] = count\n for (m in moves) {\n if (solve(r + m.second, c + m.first, count + 1, nextClue2)) return true\n }\n grid[r][c] = back\n return false\n}\n\nfun printResult(n: Int) {\n println(\"Solution for example $n:\")\n for (row in grid) {\n for (i in row) {\n if (i == -1) continue\n print(\"%2d \".format(i))\n }\n println()\n }\n}\n\nfun main(args: Array) {\n for ((n, ex) in listOf(example1, example2).withIndex()) {\n board = ex\n val nRows = board.size + 2\n val nCols = board[0].split(\",\").size + 2\n var startRow = 0\n var startCol = 0\n grid = List(nRows) { IntArray(nCols) { -1 } }\n totalToFill = (nRows - 2) * (nCols - 2)\n val lst = mutableListOf()\n for (r in 0 until nRows) {\n if (r in 1 until nRows - 1) {\n val row = board[r - 1].split(\",\")\n for (c in 1 until nCols - 1) {\n val value = row[c - 1].toInt()\n if (value > 0) lst.add(value)\n if (value == 1) {\n startRow = r\n startCol = c\n }\n grid[r][c] = value\n }\n }\n }\n lst.sort()\n clues = lst.toIntArray()\n if (solve(startRow, startCol, 1, 0)) printResult(n + 1)\n }\n}"} {"title": "Sparkline in unicode", "language": "Kotlin from Java", "task": "A sparkline is a graph of successive values laid out horizontally \nwhere the height of the line is proportional to the values in succession.\n\n\n;Task:\nUse the following series of Unicode characters to create a program \nthat takes a series of numbers separated by one or more whitespace or comma characters \nand generates a sparkline-type bar graph of the values on a single line of output.\n\nThe eight characters: '########'\n(Unicode values U+2581 through U+2588).\n\nUse your program to show sparklines for the following input, \nhere on this page:\n# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\n# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 \n:(note the mix of separators in this second case)!\n\n;Notes: \n* A space is not part of the generated sparkline.\n* The sparkline may be accompanied by simple statistics of the data such as its range.\n* A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:\n\n:: \"0, 1, 19, 20\" -> ####\n:: (Aiming to use just two spark levels)\n\n:: \"0, 999, 4000, 4999, 7000, 7999\" -> ######\n:: (Aiming to use just three spark levels)\n\n:: It may be helpful to include these cases in output tests.\n* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.\n\n", "solution": "internal const val bars = \"\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588\"\ninternal const val n = bars.length - 1\n\nfun Iterable.toSparkline(): String {\n var min = Double.MAX_VALUE\n var max = Double.MIN_VALUE\n val doubles = map { it.toDouble() }\n doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } }\n val range = max - min\n return doubles.fold(\"\") { line, d -> line + bars[Math.ceil((d - min) / range * n).toInt()] }\n}\n\nfun String.toSparkline() = replace(\",\", \"\").split(\" \").map { it.toFloat() }.toSparkline()\n\nfun main(args: Array) {\n val s1 = \"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1\"\n println(s1)\n println(s1.toSparkline())\n val s2 = \"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5\"\n println(s2)\n println(s2.toSparkline())\n}"} {"title": "Spelling of ordinal numbers", "language": "Kotlin", "task": "'''Ordinal numbers''' (as used in this Rosetta Code task), are numbers that describe the ''position'' of something in a list.\n\nIt is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.\n\n\nThe ordinal numbers are (at least, one form of them):\n 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** etc\n\nsometimes expressed as:\n 1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th ***\n\n\nFor this task, the following (English-spelled form) will be used:\n first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth\n\n\nFurthermore, the American version of numbers will be used here (as opposed to the British).\n\n'''2,000,000,000''' is two billion, ''not'' two milliard.\n\n\n;Task:\nWrite a driver and a function (subroutine/routine ***) that returns the English-spelled ordinal version of a specified number (a positive integer).\n\nOptionally, try to support as many forms of an integer that can be expressed: '''123''' '''00123.0''' '''1.23e2''' all are forms of the same integer.\n\nShow all output here.\n\n\n;Test cases:\nUse (at least) the test cases of:\n 1 2 3 4 5 11 65 100 101 272 23456 8007006005004003\n\n\n;Related tasks:\n* [[Number names]]\n* [[N'th]]\n\n", "solution": "// version 1.1.4-3\n\ntypealias IAE = IllegalArgumentException\n\nval names = mapOf(\n 1 to \"one\",\n 2 to \"two\",\n 3 to \"three\",\n 4 to \"four\",\n 5 to \"five\",\n 6 to \"six\",\n 7 to \"seven\",\n 8 to \"eight\",\n 9 to \"nine\",\n 10 to \"ten\",\n 11 to \"eleven\",\n 12 to \"twelve\",\n 13 to \"thirteen\",\n 14 to \"fourteen\",\n 15 to \"fifteen\",\n 16 to \"sixteen\",\n 17 to \"seventeen\",\n 18 to \"eighteen\",\n 19 to \"nineteen\",\n 20 to \"twenty\",\n 30 to \"thirty\",\n 40 to \"forty\",\n 50 to \"fifty\",\n 60 to \"sixty\",\n 70 to \"seventy\",\n 80 to \"eighty\",\n 90 to \"ninety\"\n)\nval bigNames = mapOf(\n 1_000L to \"thousand\",\n 1_000_000L to \"million\",\n 1_000_000_000L to \"billion\",\n 1_000_000_000_000L to \"trillion\",\n 1_000_000_000_000_000L to \"quadrillion\",\n 1_000_000_000_000_000_000L to \"quintillion\"\n)\n\nval irregOrdinals = mapOf(\n \"one\" to \"first\",\n \"two\" to \"second\",\n \"three\" to \"third\",\n \"five\" to \"fifth\",\n \"eight\" to \"eighth\",\n \"nine\" to \"ninth\",\n \"twelve\" to \"twelfth\"\n)\n\nfun String.toOrdinal(): String {\n val splits = this.split(' ', '-')\n var last = splits[splits.lastIndex]\n return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!\n else if (last.endsWith(\"y\")) this.dropLast(1) + \"ieth\"\n else this + \"th\"\n} \n \nfun numToOrdinalText(n: Long, uk: Boolean = false): String {\n if (n == 0L) return \"zeroth\" // or alternatively 'zeroeth'\n val neg = n < 0L\n val maxNeg = n == Long.MIN_VALUE\n var nn = if (maxNeg) -(n + 1) else if (neg) -n else n\n val digits3 = IntArray(7)\n for (i in 0..6) { // split number into groups of 3 digits from the right\n digits3[i] = (nn % 1000).toInt()\n nn /= 1000\n }\n \n fun threeDigitsToText(number: Int) : String {\n val sb = StringBuilder()\n if (number == 0) return \"\"\n val hundreds = number / 100\n val remainder = number % 100\n if (hundreds > 0) {\n sb.append(names[hundreds], \" hundred\")\n if (remainder > 0) sb.append(if (uk) \" and \" else \" \")\n }\n if (remainder > 0) {\n val tens = remainder / 10\n val units = remainder % 10\n if (tens > 1) {\n sb.append(names[tens * 10])\n if (units > 0) sb.append(\"-\", names[units])\n }\n else sb.append(names[remainder])\n }\n return sb.toString()\n }\n \n val strings = Array(7) { threeDigitsToText(digits3[it]) }\n var text = strings[0]\n var andNeeded = uk && digits3[0] in 1..99\n var big = 1000L\n for (i in 1..6) {\n if (digits3[i] > 0) {\n var text2 = strings[i] + \" \" + bigNames[big]\n if (text.length > 0) {\n text2 += if (andNeeded) \" and \" else \", \"\n andNeeded = false\n }\n else andNeeded = uk && digits3[i] in 1..99\n text = text2 + text\n }\n big *= 1000\n }\n if (maxNeg) text = text.dropLast(5) + \"eight\"\n if (neg) text = \"minus \" + text\n return text.toOrdinal()\n}\n\nfun numToOrdinalText(s: String, uk: Boolean = false): String {\n val d = s.toDoubleOrNull() ?: throw IAE(\"String is not numeric\") \n if (d !in Long.MIN_VALUE.toDouble() .. Long.MAX_VALUE.toDouble())\n throw IAE(\"Double is outside the range of a Long Integer\")\n val n = d.toLong()\n if (n.toDouble() != d) throw IAE(\"String does not represent a Long Integer\")\n return numToOrdinalText(n, uk)\n}\n \nfun main(args: Array) {\n val la = longArrayOf(1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003)\n println(\"Using US representation:\")\n for (i in la) println(\"${\"%16d\".format(i)} = ${numToOrdinalText(i)}\")\n val sa = arrayOf(\"123\", \"00123.0\", \"1.23e2\")\n for (s in sa) println(\"${\"%16s\".format(s)} = ${numToOrdinalText(s)}\")\n}"} {"title": "Split a character string based on change of character", "language": "Kotlin", "task": "Split a (character) string into comma (plus a blank) delimited\nstrings based on a change of character (left to right).\n\nShow the output here (use the 1st example below).\n\n\nBlanks should be treated as any other character (except\nthey are problematic to display clearly). The same applies\nto commas.\n\n\nFor instance, the string: \n gHHH5YY++///\\ \nshould be split and show: \n g, HHH, 5, YY, ++, ///, \\ \n\n", "solution": "// version 1.0.6\n\nfun splitOnChange(s: String): String {\n if (s.length < 2) return s\n var t = s.take(1) \n for (i in 1 until s.length)\n if (t.last() == s[i]) t += s[i]\n else t += \", \" + s[i] \n return t\n}\n\nfun main(args: Array) {\n val s = \"\"\"gHHH5YY++///\\\"\"\"\n println(splitOnChange(s))\n}"} {"title": "Square-free integers", "language": "Kotlin from Go", "task": "Write a function to test if a number is ''square-free''.\n\n\nA ''square-free'' is an integer which is divisible by no perfect square other\nthan '''1''' (unity).\n\nFor this task, only positive square-free numbers will be used.\n\n\n\nShow here (on this page) all square-free integers (in a horizontal format) that are between:\n::* '''1''' ---> '''145''' (inclusive)\n::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)\n\n\n(One trillion = 1,000,000,000,000)\n\n\nShow here (on this page) the count of square-free integers from:\n::* '''1''' ---> one hundred (inclusive)\n::* '''1''' ---> one thousand (inclusive)\n::* '''1''' ---> ten thousand (inclusive)\n::* '''1''' ---> one hundred thousand (inclusive)\n::* '''1''' ---> one million (inclusive)\n\n\n;See also:\n:* the Wikipedia entry: square-free integer\n\n", "solution": "// Version 1.2.50\n\nimport kotlin.math.sqrt\n\nfun sieve(limit: Long): List {\n val primes = mutableListOf(2L)\n val c = BooleanArray(limit.toInt() + 1) // composite = true\n // no need to process even numbers > 2\n var p = 3\n while (true) {\n val p2 = p * p\n if (p2 > limit) break\n for (i in p2..limit step 2L * p) c[i.toInt()] = true\n do { p += 2 } while (c[p])\n }\n for (i in 3..limit step 2)\n if (!c[i.toInt()])\n primes.add(i)\n\n return primes\n}\n\nfun squareFree(r: LongProgression): List {\n val primes = sieve(sqrt(r.last.toDouble()).toLong())\n val results = mutableListOf()\n outer@ for (i in r) {\n for (p in primes) {\n val p2 = p * p\n if (p2 > i) break\n if (i % p2 == 0L) continue@outer\n }\n results.add(i)\n }\n return results\n}\n\nfun printResults(r: LongProgression, c: Int, f: Int) {\n println(\"Square-free integers from ${r.first} to ${r.last}:\")\n squareFree(r).chunked(c).forEach {\n println()\n it.forEach { print(\"%${f}d\".format(it)) }\n }\n println('\\n')\n}\n\nconst val TRILLION = 1000000_000000L\n\nfun main(args: Array) {\n printResults(1..145L, 20, 4)\n printResults(TRILLION..TRILLION + 145L, 5, 14)\n\n println(\"Number of square-free integers:\\n\")\n longArrayOf(100, 1000, 10000, 100000, 1000000).forEach {\n j -> println(\" from 1 to $j = ${squareFree(1..j).size}\")\n }\n}"} {"title": "Square but not cube", "language": "Kotlin", "task": "Show the first '''30''' positive integers which are squares but not cubes of such integers.\n\nOptionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.\n\n", "solution": "// Version 1.2.60\n\nfun main(args: Array) {\n var n = 1\n var count = 0\n while (count < 30) {\n val sq = n * n\n val cr = Math.cbrt(sq.toDouble()).toInt()\n if (cr * cr * cr != sq) {\n count++\n println(sq)\n }\n else {\n println(\"$sq is square and cube\")\n }\n n++\n }\n}"} {"title": "Stair-climbing puzzle", "language": "Kotlin from D", "task": "From Chung-Chieh Shan (LtU):\n\nYour stair-climbing robot has a very simple low-level API: the \"step\" function takes no argument and attempts to climb one step as a side effect. Unfortunately, sometimes the attempt fails and the robot clumsily falls one step instead. The \"step\" function detects what happens and returns a boolean flag: true on success, false on failure. \n\nWrite a function \"step_up\" that climbs one step up [from the initial position] (by repeating \"step\" attempts if necessary). Assume that the robot is not already at the top of the stairs, and neither does it ever reach the bottom of the stairs. How small can you make \"step_up\"? Can you avoid using variables (even immutable ones) and numbers?\n\nHere's a pseudo-code of a simple recursive solution without using variables:\n\nfunc step_up()\n{\n if not step() {\n step_up();\n step_up();\n }\n}\n\nInductive proof that step_up() steps up one step, if it terminates:\n* Base case (if the step() call returns true): it stepped up one step. QED\n* Inductive case (if the step() call returns false): Assume that recursive calls to step_up() step up one step. It stepped down one step (because step() returned false), but now we step up two steps using two step_up() calls. QED\n\n\nThe second (tail) recursion above can be turned into an iteration, as follows:\n\nfunc step_up()\n{\n while not step() {\n step_up();\n }\n}\n\n", "solution": "// version 1.2.0\n\nimport java.util.Random\n\nval rand = Random(6321L) // generates short repeatable sequence\nvar position = 0\n\nfun step(): Boolean {\n val r = rand.nextBoolean()\n if (r)\n println(\"Climbed up to ${++position}\")\n else\n println(\"Fell down to ${--position}\")\n return r\n}\n\nfun stepUp() {\n while (!step()) stepUp()\n}\n\nfun main(args: Array) {\n stepUp()\n}"} {"title": "Start from a main routine", "language": "Kotlin", "task": "Some languages (like Gambas and Visual Basic) support two startup modes. Applications written in these languages start with an open window that waits for events, and it is necessary to do some trickery to cause a main procedure to run instead. Data driven or event driven languages may also require similar trickery to force a startup procedure to run.\n\n\n;Task:\nDemonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.\n\nLanguages that always run from main() can be omitted from this task.\n\n", "solution": "The version of Kotlin which targets the JVM always starts from the main(args: Array) function unless it is running in REPL mode when it simply executes lines of executable code in the order presented. The REPL is started by typing, kotlinc, without any parameters at the command prompt. For example:\n\n"} {"title": "Statistics/Normal distribution", "language": "Kotlin from FreeBASIC", "task": "The derive normally distributed random numbers from a uniform generator.\n\n\n;The task:\n# Take a uniform random number generator and create a large (you decide how large) set of numbers that follow a normal (Gaussian) distribution. Calculate the dataset's mean and standard deviation, and show a histogram of the data.\n# Mention any native language support for the generation of normally distributed random numbers.\n\n\n;Reference:\n* You may refer to code in [[Statistics/Basic]] if available.\n\n", "solution": "// version 1.1.2\n\nval rand = java.util.Random()\n\nfun normalStats(sampleSize: Int) {\n if (sampleSize < 1) return\n val r = DoubleArray(sampleSize)\n val h = IntArray(12) // all zero by default\n /*\n Generate 'sampleSize' normally distributed random numbers with mean 0.5 and SD 0.25\n and calculate in which box they will fall when drawing the histogram\n */\n for (i in 0 until sampleSize) {\n r[i] = 0.5 + rand.nextGaussian() / 4.0\n when {\n r[i] < 0.0 -> h[0]++\n r[i] >= 1.0 -> h[11]++ \n else -> h[1 + (r[i] * 10).toInt()]++\n }\n } \n\n // adjust one of the h[] values if necessary to ensure they sum to sampleSize\n val adj = sampleSize - h.sum()\n if (adj != 0) {\n for (i in 0..11) {\n h[i] += adj\n if (h[i] >= 0) break\n h[i] -= adj\n }\n }\n\n val mean = r.average()\n val sd = Math.sqrt(r.map { (it - mean) * (it - mean) }.average())\n \n // Draw a histogram of the data with interval 0.1 \n var numStars: Int\n // If sample size > 300 then normalize histogram to 300 \n val scale = if (sampleSize <= 300) 1.0 else 300.0 / sampleSize \n println(\"Sample size $sampleSize\\n\")\n println(\" Mean ${\"%1.6f\".format(mean)} SD ${\"%1.6f\".format(sd)}\\n\") \n for (i in 0..11) {\n when (i) { \n 0 -> print(\"< 0.00 : \")\n 11 -> print(\">=1.00 : \")\n else -> print(\" %1.2f : \".format(i / 10.0))\n } \n print(\"%5d \".format(h[i]))\n numStars = (h[i] * scale + 0.5).toInt()\n println(\"*\".repeat(numStars))\n }\n println()\n}\n\nfun main(args: Array) {\n val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000) \n for (sampleSize in sampleSizes) normalStats(sampleSize)\n}"} {"title": "Stern-Brocot sequence", "language": "Kotlin", "task": "For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].\n\n# The first and second members of the sequence are both 1:\n#* 1, 1\n# Start by considering the second member of the sequence\n# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:\n#* 1, 1, 2\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1\n# Consider the next member of the series, (the third member i.e. 2)\n# GOTO 3\n#*\n#* --- Expanding another loop we get: ---\n#*\n# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:\n#* 1, 1, 2, 1, 3\n# Append the considered member of the sequence to the end of the sequence:\n#* 1, 1, 2, 1, 3, 2\n# Consider the next member of the series, (the fourth member i.e. 1)\n\n\n;The task is to:\n* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.\n* Show the first fifteen members of the sequence. (This should be: 1, 1, 2, 1, 3, 2, 3, 1, 4, 3, 5, 2, 5, 3, 4)\n* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.\n* Show the (1-based) index of where the number 100 first appears in the sequence.\n* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.\n\nShow your output on this page.\n\n\n;Related tasks:\n:* [[Fusc sequence]].\n:* [[Continued fraction/Arithmetic]]\n\n\n;Ref:\n* Infinite Fractions - Numberphile (Video).\n* Trees, Teeth, and Time: The mathematics of clock making.\n* A002487 The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "// version 1.1.0\n\nval sbs = mutableListOf(1, 1)\n\nfun sternBrocot(n: Int, fromStart: Boolean = true) {\n if (n < 4 || (n % 2 != 0)) throw IllegalArgumentException(\"n must be >= 4 and even\")\n var consider = if (fromStart) 1 else n / 2 - 1\n while (true) {\n val sum = sbs[consider] + sbs[consider - 1]\n sbs.add(sum)\n sbs.add(sbs[consider])\n if (sbs.size == n) break\n consider++\n }\n}\n\nfun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)\n\nfun main(args: Array) {\n var n = 16 // needs to be even to ensure 'considered' number is added\n println(\"First 15 members of the Stern-Brocot sequence\")\n sternBrocot(n)\n println(sbs.take(15))\n\n val firstFind = IntArray(11) // all zero by default\n firstFind[0] = -1 // needs to be non-zero for subsequent test\n for ((i, v) in sbs.withIndex())\n if (v <= 10 && firstFind[v] == 0) firstFind[v] = i + 1\n loop@ while (true) {\n n += 2\n sternBrocot(n, false)\n val vv = sbs.takeLast(2)\n var m = n - 1\n for (v in vv) {\n if (v <= 10 && firstFind[v] == 0) firstFind[v] = m\n if (firstFind.all { it != 0 }) break@loop\n m++\n }\n }\n println(\"\\nThe numbers 1 to 10 first appear at the following indices:\")\n for (i in 1..10) println(\"${\"%2d\".format(i)} -> ${firstFind[i]}\")\n\n print(\"\\n100 first appears at index \")\n while (true) {\n n += 2\n sternBrocot(n, false)\n val vv = sbs.takeLast(2)\n if (vv[0] == 100) {\n println(n - 1); break\n }\n if (vv[1] == 100) {\n println(n); break\n }\n }\n\n print(\"\\nThe GCDs of each pair of the series up to the 1000th member are \")\n for (p in 0..998 step 2) {\n if (gcd(sbs[p], sbs[p + 1]) != 1) {\n println(\"not all one\")\n return\n }\n }\n println(\"all one\")\n}"} {"title": "Stirling numbers of the first kind", "language": "Kotlin from Java", "task": "Stirling numbers of the first kind, or Stirling cycle numbers, count permutations according to their number\nof cycles (counting fixed points as cycles of length one).\n\nThey may be defined directly to be the number of permutations of '''n'''\nelements with '''k''' disjoint cycles.\n\nStirling numbers of the first kind express coefficients of polynomial expansions of falling or rising factorials.\n\nDepending on the application, Stirling numbers of the first kind may be \"signed\"\nor \"unsigned\". Signed Stirling numbers of the first kind arise when the\npolynomial expansion is expressed in terms of falling factorials; unsigned when\nexpressed in terms of rising factorials. The only substantial difference is that,\nfor signed Stirling numbers of the first kind, values of S1(n, k) are negative\nwhen n + k is odd.\n\nStirling numbers of the first kind follow the simple identities:\n\n S1(0, 0) = 1\n S1(n, 0) = 0 if n > 0\n S1(n, k) = 0 if k > n\n S1(n, k) = S1(n - 1, k - 1) + (n - 1) * S1(n - 1, k) # For unsigned\n ''or''\n S1(n, k) = S1(n - 1, k - 1) - (n - 1) * S1(n - 1, k) # For signed\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the first kind'''. There are several methods to generate Stirling numbers of the first kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the first kind, '''S1(n, k)''', up to '''S1(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S1(n, k) == 0 (when k > n). You may choose to show signed or unsigned Stirling numbers of the first kind, just make a note of which was chosen.\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S1(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the first kind'''\n:* '''OEIS:A008275 - Signed Stirling numbers of the first kind'''\n:* '''OEIS:A130534 - Unsigned Stirling numbers of the first kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the second kind'''\n:* '''Lah numbers'''\n\n\n", "solution": "import java.math.BigInteger\n\nfun main() {\n println(\"Unsigned Stirling numbers of the first kind:\")\n val max = 12\n print(\"n/k\")\n for (n in 0..max) {\n print(\"%10d\".format(n))\n }\n println()\n for (n in 0..max) {\n print(\"%-3d\".format(n))\n for (k in 0..n) {\n print(\"%10s\".format(sterling1(n, k)))\n }\n println()\n }\n println(\"The maximum value of S1(100, k) = \")\n var previous = BigInteger.ZERO\n for (k in 1..100) {\n val current = sterling1(100, k)\n previous = if (current!! > previous) {\n current\n } else {\n println(\"$previous\\n(${previous.toString().length} digits, k = ${k - 1})\")\n break\n }\n }\n}\n\nprivate val COMPUTED: MutableMap = HashMap()\nprivate fun sterling1(n: Int, k: Int): BigInteger? {\n val key = \"$n,$k\"\n if (COMPUTED.containsKey(key)) {\n return COMPUTED[key]\n }\n\n if (n == 0 && k == 0) {\n return BigInteger.valueOf(1)\n }\n if (n > 0 && k == 0) {\n return BigInteger.ZERO\n }\n if (k > n) {\n return BigInteger.ZERO\n }\n\n val result = sterling1(n - 1, k - 1)!!.add(BigInteger.valueOf(n - 1.toLong()).multiply(sterling1(n - 1, k)))\n COMPUTED[key] = result\n return result\n}"} {"title": "Stirling numbers of the second kind", "language": "Kotlin from Java", "task": "Stirling numbers of the second kind, or Stirling partition numbers, are the\nnumber of ways to partition a set of n objects into k non-empty subsets. They are\nclosely related to [[Bell numbers]], and may be derived from them.\n\n\nStirling numbers of the second kind obey the recurrence relation:\n\n S2(n, 0) and S2(0, k) = 0 # for n, k > 0\n S2(n, n) = 1\n S2(n + 1, k) = k * S2(n, k) + S2(n, k - 1)\n\n\n\n;Task:\n\n:* Write a routine (function, procedure, whatever) to find '''Stirling numbers of the second kind'''. There are several methods to generate Stirling numbers of the second kind. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.\n\n:* Using the routine, generate and show here, on this page, a table (or triangle) showing the Stirling numbers of the second kind, '''S2(n, k)''', up to '''S2(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where S2(n, k) == 0 (when k > n).\n\n:* If your language supports large integers, find and show here, on this page, the maximum value of '''S2(n, k)''' where '''n == 100'''.\n\n\n;See also:\n\n:* '''Wikipedia - Stirling numbers of the second kind'''\n:* '''OEIS:A008277 - Stirling numbers of the second kind'''\n\n\n;Related Tasks:\n\n:* '''Stirling numbers of the first kind'''\n:* '''Bell numbers'''\n:* '''Lah numbers'''\n\n\n", "solution": "import java.math.BigInteger\n\nfun main() {\n println(\"Stirling numbers of the second kind:\")\n val max = 12\n print(\"n/k\")\n for (n in 0..max) {\n print(\"%10d\".format(n))\n }\n println()\n for (n in 0..max) {\n print(\"%-3d\".format(n))\n for (k in 0..n) {\n print(\"%10s\".format(sterling2(n, k)))\n }\n println()\n }\n println(\"The maximum value of S2(100, k) = \")\n var previous = BigInteger.ZERO\n for (k in 1..100) {\n val current = sterling2(100, k)\n previous = if (current > previous) {\n current\n } else {\n println(\"%s%n(%d digits, k = %d)\".format(previous, previous.toString().length, k - 1))\n break\n }\n }\n}\n\nprivate val COMPUTED: MutableMap = HashMap()\nprivate fun sterling2(n: Int, k: Int): BigInteger {\n val key = \"$n,$k\"\n if (COMPUTED.containsKey(key)) {\n return COMPUTED[key]!!\n }\n if (n == 0 && k == 0) {\n return BigInteger.valueOf(1)\n }\n if (n > 0 && k == 0 || n == 0 && k > 0) {\n return BigInteger.ZERO\n }\n if (n == k) {\n return BigInteger.valueOf(1)\n }\n if (k > n) {\n return BigInteger.ZERO\n }\n\n val result = BigInteger.valueOf(k.toLong()) * sterling2(n - 1, k) + sterling2(n - 1, k - 1)\n COMPUTED[key] = result\n return result\n}"} {"title": "Stream merge", "language": "Kotlin", "task": " 2-stream merge\n: Read two sorted streams of items from external source (e.g. disk, or network), and write one stream of sorted items to external sink.\n: Common algorithm: keep 1 buffered item from each source, select minimal of them, write it, fetch another item from that stream from which the written item was.\n\n; ''N''-stream merge\n: The same as above, but reading from ''N'' sources.\n: Common algorithm: same as above, but keep buffered items and their source descriptors in a [[heap]].\n\n\nAssume streams are very big. You must not suck them whole in the memory, but read them as streams.\n\n", "solution": "// version 1.2.21\n\nimport java.io.File\n\nfun merge2(inputFile1: String, inputFile2: String, outputFile: String) {\n val file1 = File(inputFile1)\n val file2 = File(inputFile2)\n require(file1.exists() && file2.exists()) { \"Both input files must exist\" }\n val reader1 = file1.bufferedReader()\n val reader2 = file2.bufferedReader()\n val writer = File(outputFile).printWriter()\n var line1 = reader1.readLine()\n var line2 = reader2.readLine()\n while (line1 != null && line2 != null) {\n if (line1 <= line2) {\n writer.println(line1)\n line1 = reader1.readLine()\n }\n else {\n writer.println(line2)\n line2 = reader2.readLine()\n }\n }\n while (line1 != null) {\n writer.println(line1)\n line1 = reader1.readLine()\n }\n while (line2 != null) {\n writer.println(line2)\n line2 = reader2.readLine()\n }\n reader1.close()\n reader2.close()\n writer.close()\n}\n\nfun mergeN(inputFiles: List, outputFile: String) {\n val files = inputFiles.map { File(it) }\n require(files.all { it.exists() }) { \"All input files must exist\" }\n val readers = files.map { it.bufferedReader() }\n val writer = File(outputFile).printWriter()\n var lines = readers.map { it.readLine() }.toMutableList()\n while (lines.any { it != null }) {\n val line = lines.filterNotNull().min()\n val index = lines.indexOf(line)\n writer.println(line)\n lines[index] = readers[index].readLine()\n }\n readers.forEach { it.close() }\n writer.close()\n}\n\nfun main(args:Array) {\n val files = listOf(\"merge1.txt\", \"merge2.txt\", \"merge3.txt\", \"merge4.txt\")\n merge2(files[0], files[1], \"merged2.txt\")\n mergeN(files, \"mergedN.txt\")\n // check it worked\n println(File(\"merged2.txt\").readText()) \n println(File(\"mergedN.txt\").readText())\n}"} {"title": "Strip control codes and extended characters from a string", "language": "Kotlin", "task": "Strip control codes and extended characters from a string. \n\n\nThe solution should demonstrate how to achieve each of the following results:\n:* a string with control codes stripped (but extended characters not stripped)\n:* a string with control codes and extended characters stripped\n\n\nIn ASCII, the control codes have decimal codes 0 through to 31 and 127. \n\nOn an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table.\n\nOn a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.\n\n\n", "solution": "// version 1.1.2\n\nfun String.strip(extendedChars: Boolean = false): String {\n val sb = StringBuilder()\n for (c in this) {\n val i = c.toInt()\n if (i in 32..126 || (!extendedChars && i >= 128)) sb.append(c)\n }\n return sb.toString()\n}\n\nfun main(args: Array) {\n println(\"Originally:\")\n val s = \"123\\tabc\\u0007DEF\\u007F+-*/\u20ac\u00e6\u0167\u00f0\u0142\u00fe\"\n println(\"String = $s Length = ${s.length}\")\n println(\"\\nAfter stripping control characters:\")\n val t = s.strip()\n println(\"String = $t Length = ${t.length}\")\n println(\"\\nAfter stripping control and extended characters:\")\n val u = s.strip(true)\n println(\"String = $u Length = ${u.length}\")\n}"} {"title": "Subleq", "language": "Kotlin", "task": "One-Instruction Set Computer (OISC). \n\nIt is named after its only instruction, which is '''SU'''btract and '''B'''ranch if '''L'''ess than or '''EQ'''ual to zero. \n\n;Task\nYour task is to create an interpreter which emulates a SUBLEQ machine.\n\nThe machine's memory consists of an array of signed integers. These integers may be interpreted in three ways:\n::::* simple numeric values \n::::* memory addresses \n::::* characters for input or output\n\nAny reasonable word size that accommodates all three of the above uses is fine. \n\nThe program should load the initial contents of the emulated machine's memory, set the instruction pointer to the first address (which is defined to be address 0), and begin emulating the machine, which works as follows:\n:# Let '''A''' be the value in the memory location identified by the instruction pointer; let '''B''' and '''C''' be the values stored in the next two consecutive addresses in memory.\n:# Advance the instruction pointer three words, to point at the address ''after'' the address containing '''C'''.\n:# If '''A''' is '''-1''' (negative unity), then a character is read from the machine's input and its numeric value stored in the address given by '''B'''. '''C''' is unused.\n:# If '''B''' is '''-1''' (negative unity), then the number contained in the address given by '''A''' is interpreted as a character and written to the machine's output. '''C''' is unused.\n:# Otherwise, both '''A''' and '''B''' are treated as addresses. The number contained in address '''A''' is subtracted from the number in address '''B''' (and the difference left in address '''B'''). If the result is positive, execution continues uninterrupted; if the result is zero or negative, the number in '''C''' becomes the new instruction pointer.\n:# If the instruction pointer becomes negative, execution halts.\n\nYour solution may initialize the emulated machine's memory in any convenient manner, but if you accept it as input, it should be a separate input stream from the one fed to the emulated machine once it is running. And if fed as text input, it should be in the form of raw subleq \"machine code\" - whitespace-separated decimal numbers, with no symbolic names or other assembly-level extensions, to be loaded into memory starting at address '''0''' (zero).\n\nFor purposes of this task, show the output of your solution when fed the below \"Hello, world!\" program. \n\nAs written, this example assumes ASCII or a superset of it, such as any of the Latin-N character sets or Unicode; you may translate the numbers representing characters (starting with 72=ASCII 'H') into another character set if your implementation runs in a non-ASCII-compatible environment. If 0 is not an appropriate terminator in your character set, the program logic will need some adjustment as well.\n\n15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\n\nThe above \"machine code\" corresponds to something like this in a hypothetical assembler language for a signed 8-bit version of the machine:\n\nstart:\n 0f 11 ff subleq (zero), (message), -1\n 11 ff ff subleq (message), -1, -1 ; output character at message\n 10 01 ff subleq (neg1), (start+1), -1\n 10 03 ff subleq (neg1), (start+3), -1\n 0f 0f 00 subleq (zero), (zero), start\n; useful constants\nzero: \n 00 .data 0 \nneg1: \n ff .data -1\n; the message to print\nmessage: .data \"Hello, world!\\n\\0\"\n 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a 00\n\n", "solution": "// version 1.1.2\n\nfun subleq(program: String) {\n val words = program.split(' ').map { it.toInt() }.toTypedArray()\n val sb = StringBuilder()\n var ip = 0\n while (true) {\n val a = words[ip]\n val b = words[ip + 1]\n var c = words[ip + 2]\n ip += 3\n if (a < 0) {\n print(\"Enter a character : \")\n words[b] = readLine()!![0].toInt()\n }\n else if (b < 0) { \n sb.append(words[a].toChar())\n }\n else {\n words[b] -= words[a]\n if (words[b] <= 0) ip = c \n if (ip < 0) break \n }\n }\n print(sb) \n}\n\nfun main(args: Array) {\n val program = \"15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0\"\n subleq(program)\n}"} {"title": "Substring/Top and tail", "language": "Kotlin", "task": "The task is to demonstrate how to remove the first and last characters from a string. \n\nThe solution should demonstrate how to obtain the following results:\n\n* String with first character removed\n* String with last character removed\n* String with both the first and last characters removed\n\n\nIf the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. \n\nThe program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. \n\nPrograms for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters.\n\n\n\n", "solution": "// version 1.0.6\nfun main(args: Array) {\n val s = \"Rosetta\"\n println(s.drop(1))\n println(s.dropLast(1))\n println(s.drop(1).dropLast(1))\n}"} {"title": "Sum and product puzzle", "language": "Kotlin", "task": "* Wikipedia: Sum and Product Puzzle\n\n", "solution": "// version 1.1.4-3\n\ndata class P(val x: Int, val y: Int, val sum: Int, val prod: Int)\n\nfun main(args: Array) {\n val candidates = mutableListOf

() \n for (x in 2..49) {\n for (y in x + 1..100 - x) {\n candidates.add(P(x, y, x + y, x * y))\n }\n }\n \n val sums = candidates.groupBy { it.sum }\n val prods = candidates.groupBy { it.prod }\n\n val fact1 = candidates.filter { sums[it.sum]!!.all { prods[it.prod]!!.size > 1 } }\n val fact2 = fact1.filter { prods[it.prod]!!.intersect(fact1).size == 1 }\n val fact3 = fact2.filter { sums[it.sum]!!.intersect(fact2).size == 1 }\n print(\"The only solution is : \")\n for ((x, y, _, _) in fact3) println(\"x = $x, y = $y\") \n}"} {"title": "Sum digits of an integer", "language": "Kotlin", "task": "Take a Natural Number in a given base and return the sum of its digits:\n:* '''1'''10 sums to '''1'''\n:* '''1234'''10 sums to '''10'''\n:* '''fe'''16 sums to '''29'''\n:* '''f0e'''16 sums to '''29'''\n\n", "solution": "// version 1.1.0\n\nconst val digits = \"0123456789abcdefghijklmnopqrstuvwxyz\"\n\nfun sumDigits(ns: String, base: Int): Int {\n val n = ns.toLowerCase().trim()\n if (base !in 2..36) throw IllegalArgumentException(\"Base must be between 2 and 36\")\n if (n.isEmpty()) throw IllegalArgumentException(\"Number string can't be blank or empty\")\n var sum = 0\n for (digit in n) {\n val index = digits.indexOf(digit)\n if (index == -1 || index >= base) throw IllegalArgumentException(\"Number string contains an invalid digit\")\n sum += index\n }\n return sum\n}\n\nfun main(args: Array) {\n val numbers = mapOf(\"1\" to 10, \"1234\" to 10, \"fe\" to 16, \"f0e\" to 16, \"1010\" to 2, \"777\" to 8, \"16xyz\" to 36)\n println(\"The sum of digits is:\")\n for ((number, base) in numbers) println(\"$number\\tbase $base\\t-> ${sumDigits(number, base)}\")\n}"} {"title": "Sum multiples of 3 and 5", "language": "Kotlin", "task": "The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below ''n''. \n\nShow output for ''n'' = 1000.\n\nThis is is the same as Project Euler problem 1.\n\n'''Extra credit:''' do this efficiently for ''n'' = 1e20 or higher.\n\n", "solution": "// version 1.1.2\n\nimport java.math.BigInteger\n\nval big2 = BigInteger.valueOf(2)\nval big3 = BigInteger.valueOf(3)\nval big5 = BigInteger.valueOf(5)\nval big15 = big3 * big5\n\nfun sum35(n: Int) = (3 until n).filter { it % 3 == 0 || it % 5 == 0}.sum()\n\nfun sum35(n: BigInteger): BigInteger {\n val nn = n - BigInteger.ONE\n val num3 = nn / big3\n val end3 = num3 * big3\n val sum3 = (big3 + end3) * num3 / big2\n val num5 = nn / big5\n val end5 = num5 * big5\n val sum5 = (big5 + end5) * num5 / big2\n val num15 = nn / big15\n val end15 = num15 * big15\n val sum15 = (big15 + end15) * num15 / big2\n return sum3 + sum5 - sum15\n}\n\nfun main(args: Array) {\n println(\"The sum of multiples of 3 or 5 below 1000 is ${sum35(1000)}\")\n val big100k = BigInteger.valueOf(100_000L)\n val e20 = big100k * big100k * big100k * big100k\n println(\"The sum of multiples of 3 or 5 below 1e20 is ${sum35(e20)}\")\n}"} {"title": "Sum to 100", "language": "Kotlin from C++", "task": "Find solutions to the ''sum to one hundred'' puzzle.\n\n\nAdd (insert) the mathematical\noperators '''+''' or '''-''' (plus\nor minus) before any of the digits in the\ndecimal numeric string '''123456789''' such that the\nresulting mathematical expression adds up to a\nparticular sum (in this iconic case, '''100''').\n\n\nExample: \n 123 + 4 - 5 + 67 - 89 = 100 \n\nShow all output here.\n\n\n:* Show all solutions that sum to '''100''' \n:* Show the sum that has the maximum ''number'' of solutions (from zero to infinity++)\n:* Show the lowest positive sum that ''can't'' be expressed (has no solutions), using the rules for this task\n:* Show the ten highest numbers that can be expressed using the rules for this task (extra credit)\n\n++ (where ''infinity'' would be a relatively small 123,456,789)\n\n\nAn example of a sum that can't be expressed (within the rules of this task) is: '''5074'''\n(which, of course, isn't the lowest positive sum that can't be expressed).\n\n", "solution": "// version 1.1.51\n\nclass Expression {\n\n private enum class Op { ADD, SUB, JOIN }\n private val code = Array(NUMBER_OF_DIGITS) { Op.ADD }\n\n companion object {\n private const val NUMBER_OF_DIGITS = 9\n private const val THREE_POW_4 = 3 * 3 * 3 * 3\n private const val FMT = \"%9d\"\n const val NUMBER_OF_EXPRESSIONS = 2 * THREE_POW_4 * THREE_POW_4\n\n fun print(givenSum: Int) {\n var expression = Expression()\n repeat(Expression.NUMBER_OF_EXPRESSIONS) {\n if (expression.toInt() == givenSum) println(\"${FMT.format(givenSum)} = $expression\")\n expression++\n }\n }\n }\n\n operator fun inc(): Expression {\n for (i in 0 until code.size) {\n code[i] = when (code[i]) {\n Op.ADD -> Op.SUB\n Op.SUB -> Op.JOIN\n Op.JOIN -> Op.ADD\n }\n if (code[i] != Op.ADD) break\n }\n return this\n }\n\n fun toInt(): Int {\n var value = 0\n var number = 0\n var sign = +1\n for (digit in 1..9) {\n when (code[NUMBER_OF_DIGITS - digit]) {\n Op.ADD -> { value += sign * number; number = digit; sign = +1 }\n Op.SUB -> { value += sign * number; number = digit; sign = -1 }\n Op.JOIN -> { number = 10 * number + digit }\n }\n }\n return value + sign * number\n }\n\n override fun toString(): String {\n val sb = StringBuilder()\n for (digit in 1..NUMBER_OF_DIGITS) {\n when (code[NUMBER_OF_DIGITS - digit]) {\n Op.ADD -> if (digit > 1) sb.append(\" + \")\n Op.SUB -> sb.append(\" - \")\n Op.JOIN -> {}\n }\n sb.append(digit)\n }\n return sb.toString().trimStart()\n }\n}\n\nclass Stat {\n\n val countSum = mutableMapOf()\n val sumCount = mutableMapOf>()\n\n init {\n var expression = Expression()\n repeat (Expression.NUMBER_OF_EXPRESSIONS) {\n val sum = expression.toInt()\n countSum.put(sum, 1 + (countSum[sum] ?: 0))\n expression++\n }\n for ((k, v) in countSum) {\n val set = if (sumCount.containsKey(v))\n sumCount[v]!!\n else\n mutableSetOf()\n set.add(k)\n sumCount.put(v, set)\n }\n }\n}\n\nfun main(args: Array) {\n println(\"100 has the following solutions:\\n\")\n Expression.print(100)\n\n val stat = Stat()\n val maxCount = stat.sumCount.keys.max()\n val maxSum = stat.sumCount[maxCount]!!.max()\n println(\"\\n$maxSum has the maximum number of solutions, namely $maxCount\")\n\n var value = 0\n while (stat.countSum.containsKey(value)) value++\n println(\"\\n$value is the lowest positive number with no solutions\")\n\n println(\"\\nThe ten highest numbers that do have solutions are:\\n\")\n stat.countSum.keys.toIntArray().sorted().reversed().take(10).forEach { Expression.print(it) }\n}"} {"title": "Summarize and say sequence", "language": "Kotlin", "task": "There are several ways to generate a self-referential sequence. One very common one (the [[Look-and-say sequence]]) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:\n 0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...\nThe terms generated grow in length geometrically and never converge.\n\nAnother way to generate a self-referential sequence is to summarize the previous term.\n\nCount how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.\n 0, 10, 1110, 3110, 132110, 13123110, 23124110 ... \nSort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.\n\nDepending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, I'll use converge to mean an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)\n\n\n;Task:\nFind all the positive integer seed values under 1000000, for the above convergent self-referential sequence, that takes the largest number of iterations before converging. Then print out the number of iterations and the sequence they return. Note that different permutations of the digits of the seed will yield the same sequence. For this task, assume leading zeros are not permitted. \n\nSeed Value(s): 9009 9090 9900\n\nIterations: 21 \n\nSequence: (same for all three seeds except for first element)\n9009\n2920\n192210\n19222110\n19323110\n1923123110\n1923224110\n191413323110\n191433125110\n19151423125110\n19251413226110\n1916151413325110\n1916251423127110\n191716151413326110\n191726151423128110\n19181716151413327110\n19182716151423129110\n29181716151413328110\n19281716151423228110\n19281716151413427110\n19182716152413228110\n\n\n;Related tasks:\n* [[Fours is the number of letters in the ...]]\n* [[Look-and-say sequence]]\n* [[Number names]]\n* [[Self-describing numbers]]\n* [[Spelling of ordinal numbers]]\n\n\n\n\n\n;Also see:\n* The On-Line Encyclopedia of Integer Sequences.\n\n", "solution": "// version 1.1.2\n\nconst val LIMIT = 1_000_000\n\nval sb = StringBuilder()\n\nfun selfRefSeq(s: String): String {\n sb.setLength(0) // faster than using a local StringBuilder object\n for (d in '9' downTo '0') {\n if (d !in s) continue\n val count = s.count { it == d } \n sb.append(\"$count$d\")\n } \n return sb.toString()\n}\n\nfun permute(input: List): List> {\n if (input.size == 1) return listOf(input)\n val perms = mutableListOf>()\n val toInsert = input[0]\n for (perm in permute(input.drop(1))) {\n for (i in 0..perm.size) {\n val newPerm = perm.toMutableList()\n newPerm.add(i, toInsert)\n perms.add(newPerm)\n }\n }\n return perms\n}\n\nfun main(args: Array) {\n val sieve = IntArray(LIMIT) // all zero by default\n val elements = mutableListOf()\n for (n in 1 until LIMIT) {\n if (sieve[n] > 0) continue\n elements.clear() \n var next = n.toString()\n elements.add(next)\n while (true) {\n next = selfRefSeq(next)\n if (next in elements) {\n val size = elements.size\n sieve[n] = size\n if (n > 9) {\n val perms = permute(n.toString().toList()).distinct()\n for (perm in perms) {\n if (perm[0] == '0') continue\n val k = perm.joinToString(\"\").toInt()\n sieve[k] = size\n }\n } \n break\n }\n elements.add(next)\n }\n }\n val maxIterations = sieve.max()!!\n for (n in 1 until LIMIT) {\n if (sieve[n] < maxIterations) continue\n println(\"$n -> Iterations = $maxIterations\")\n var next = n.toString()\n for (i in 1..maxIterations) {\n println(next)\n next = selfRefSeq(next)\n }\n println()\n } \n}"} {"title": "Super-d numbers", "language": "Kotlin from Java", "task": "A super-d number is a positive, decimal (base ten) integer '''n''' such that '''d x nd''' has at least '''d''' consecutive digits '''d''' where\n 2 <= d <= 9\nFor instance, 753 is a super-3 number because 3 x 7533 = 1280873331.\n\n\n'''Super-d''' numbers are also shown on '''MathWorld'''(tm) as '''super-''d'' ''' or '''super-''d'''''.\n\n\n;Task:\n:* Write a function/procedure/routine to find super-d numbers.\n:* For '''d=2''' through '''d=6''', use the routine to show the first '''10''' super-d numbers.\n\n\n;Extra credit:\n:* Show the first '''10''' super-7, super-8, and/or super-9 numbers (optional).\n\n\n;See also:\n:* Wolfram MathWorld - Super-d Number.\n:* OEIS: A014569 - Super-3 Numbers.\n\n", "solution": "import java.math.BigInteger\n\nfun superD(d: Int, max: Int) {\n val start = System.currentTimeMillis()\n var test = \"\"\n for (i in 0 until d) {\n test += d\n }\n\n var n = 0\n var i = 0\n println(\"First $max super-$d numbers:\")\n while (n < max) {\n i++\n val value: Any = BigInteger.valueOf(d.toLong()) * BigInteger.valueOf(i.toLong()).pow(d)\n if (value.toString().contains(test)) {\n n++\n print(\"$i \")\n }\n }\n val end = System.currentTimeMillis()\n println(\"\\nRun time ${end - start} ms\\n\")\n}\n\nfun main() {\n for (i in 2..9) {\n superD(i, 10)\n }\n}"} {"title": "Superellipse", "language": "Kotlin", "task": "A superellipse is a geometric figure defined as the set of all points (x, y) with \n\n\n::: \\left|\\frac{x}{a}\\right|^n\\! + \\left|\\frac{y}{b}\\right|^n\\! = 1,\n\nwhere ''n'', ''a'', and ''b'' are positive numbers.\n\n\n;Task\nDraw a superellipse with n = 2.5, and a = b = 200\n\n", "solution": "// version 1.1.2\n\nimport java.awt.*\nimport java.awt.geom.Path2D\nimport javax.swing.*\nimport java.lang.Math.pow\n\n/* assumes a == b */\nclass SuperEllipse(val n: Double, val a: Int) : JPanel() {\n init {\n require(n > 0.0 && a > 0)\n preferredSize = Dimension(650, 650)\n background = Color.black\n }\n\n private fun drawEllipse(g: Graphics2D) {\n val points = DoubleArray(a + 1)\n val p = Path2D.Double()\n p.moveTo(a.toDouble(), 0.0)\n\n // calculate first quadrant\n for (x in a downTo 0) {\n points[x] = pow(pow(a.toDouble(), n) - pow(x.toDouble(), n), 1.0 / n) \n p.lineTo(x.toDouble(), -points[x])\n }\n \n // mirror to others\n for (x in 0..a) p.lineTo(x.toDouble(), points[x]) \n for (x in a downTo 0) p.lineTo(-x.toDouble(), points[x])\n for (x in 0..a) p.lineTo(-x.toDouble(), -points[x])\n\n with(g) {\n translate(width / 2, height / 2)\n color = Color.yellow\n fill(p)\n }\n }\n\n override fun paintComponent(gg: Graphics) {\n super.paintComponent(gg)\n val g = gg as Graphics2D\n g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,\n RenderingHints.VALUE_ANTIALIAS_ON)\n g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,\n RenderingHints.VALUE_TEXT_ANTIALIAS_ON)\n drawEllipse(g)\n } \n}\n\nfun main(args: Array) {\n SwingUtilities.invokeLater {\n val f = JFrame()\n with (f) {\n defaultCloseOperation = JFrame.EXIT_ON_CLOSE\n title = \"Super Ellipse\"\n isResizable = false\n add(SuperEllipse(2.5, 200), BorderLayout.CENTER) \n pack()\n setLocationRelativeTo(null)\n isVisible = true\n }\n }\n}"} {"title": "Superpermutation minimisation", "language": "Kotlin from C", "task": "A superpermutation of N different characters is a string consisting of an arrangement of multiple copies of those N different characters in which every permutation of those characters can be found as a substring.\n\nFor example, representing the characters as A..Z, using N=2 we choose to use the first two characters 'AB'. \nThe permutations of 'AB' are the two, (i.e. two-factorial), strings: 'AB' and 'BA'.\n\nA too obvious method of generating a superpermutation is to just join all the permutations together forming 'ABBA'.\n\nA little thought will produce the shorter (in fact the shortest) superpermutation of 'ABA' - it contains 'AB' at the beginning and contains 'BA' from the middle to the end.\n\nThe \"too obvious\" method of creation generates a string of length N!*N. Using this as a yardstick, the task is to investigate other methods of generating superpermutations of N from 1-to-7 characters, that never generate larger superpermutations.\n\nShow descriptions and comparisons of algorithms used here, and select the \"Best\" algorithm as being the one generating shorter superpermutations.\n\nThe problem of generating the shortest superpermutation for each N ''might'' be NP complete, although the minimal strings for small values of N have been found by brute -force searches.\n\n\n\n\n;Reference:\n* The Minimal Superpermutation Problem. by Nathaniel Johnston.\n* oeis A180632 gives 0-5 as 0, 1, 3, 9, 33, 153. 6 is thought to be 872.\n* Superpermutations - Numberphile. A video\n* Superpermutations: the maths problem solved by 4chan - Standupmaths. A video of recent (2018) mathematical progress.\n* New Superpermutations Discovered! Standupmaths & Numberphile.\n\n", "solution": "// version 1.1.2\n\nconst val MAX = 12\n\nvar sp = CharArray(0)\nval count = IntArray(MAX)\nvar pos = 0\n\nfun factSum(n: Int): Int {\n var s = 0\n var x = 0\n var f = 1 \n while (x < n) {\n f *= ++x\n s += f\n }\n return s\n}\n\nfun r(n: Int): Boolean {\n if (n == 0) return false\n val c = sp[pos - n]\n if (--count[n] == 0) {\n count[n] = n\n if (!r(n - 1)) return false\n }\n sp[pos++] = c\n return true\n}\n\nfun superPerm(n: Int) {\n pos = n\n val len = factSum(n)\n if (len > 0) sp = CharArray(len) \n for (i in 0..n) count[i] = i\n for (i in 1..n) sp[i - 1] = '0' + i \n while (r(n)) {}\n}\n\nfun main(args: Array) {\n for (n in 0 until MAX) {\n superPerm(n)\n println(\"superPerm(${\"%2d\".format(n)}) len = ${sp.size}\") \n }\n}"} {"title": "Tarjan", "language": "Kotlin", "task": "{{wikipedia|Graph}}\n\n\n\nTarjan's algorithm is an algorithm in graph theory for finding the strongly connected components of a graph. \n\nIt runs in linear time, matching the time bound for alternative methods including Kosaraju's algorithm and the path-based strong component algorithm. \n\nTarjan's Algorithm is named for its discoverer, Robert Tarjan.\n\n\n;References:\n* The article on Wikipedia.\n\nSee also: [[Kosaraju]]\n\n", "solution": "// version 1.1.3\n\nimport java.util.Stack\n\ntypealias Nodes = List\n\nclass Node(val n: Int) {\n var index = -1 // -1 signifies undefined\n var lowLink = -1\n var onStack = false\n\n override fun toString() = n.toString()\n}\n\nclass DirectedGraph(val vs: Nodes, val es: Map)\n\nfun tarjan(g: DirectedGraph): List {\n val sccs = mutableListOf()\n var index = 0\n val s = Stack()\n\n fun strongConnect(v: Node) {\n // Set the depth index for v to the smallest unused index\n v.index = index\n v.lowLink = index\n index++\n s.push(v)\n v.onStack = true\n\n // consider successors of v\n for (w in g.es[v]!!) {\n if (w.index < 0) {\n // Successor w has not yet been visited; recurse on it\n strongConnect(w)\n v.lowLink = minOf(v.lowLink, w.lowLink)\n }\n else if (w.onStack) {\n // Successor w is in stack s and hence in the current SCC\n v.lowLink = minOf(v.lowLink, w.index)\n }\n }\n\n // If v is a root node, pop the stack and generate an SCC\n if (v.lowLink == v.index) {\n val scc = mutableListOf()\n do {\n val w = s.pop()\n w.onStack = false\n scc.add(w)\n }\n while (w != v)\n sccs.add(scc)\n }\n }\n\n for (v in g.vs) if (v.index < 0) strongConnect(v)\n return sccs\n}\n\nfun main(args: Array) {\n val vs = (0..7).map { Node(it) }\n val es = mapOf(\n vs[0] to listOf(vs[1]),\n vs[2] to listOf(vs[0]),\n vs[5] to listOf(vs[2], vs[6]),\n vs[6] to listOf(vs[5]),\n vs[1] to listOf(vs[2]),\n vs[3] to listOf(vs[1], vs[2], vs[4]),\n vs[4] to listOf(vs[5], vs[3]),\n vs[7] to listOf(vs[4], vs[7], vs[6])\n )\n val g = DirectedGraph(vs, es)\n val sccs = tarjan(g)\n println(sccs.joinToString(\"\\n\"))\n}"} {"title": "Temperature conversion", "language": "Kotlin", "task": "There are quite a number of temperature scales. For this task we will concentrate on four of the perhaps best-known ones: \nRankine.\n\nThe Celsius and Kelvin scales have the same magnitude, but different null points.\n \n: 0 degrees Celsius corresponds to 273.15 kelvin.\n: 0 kelvin is absolute zero.\n\nThe Fahrenheit and Rankine scales also have the same magnitude, but different null points.\n\n: 0 degrees Fahrenheit corresponds to 459.67 degrees Rankine.\n: 0 degrees Rankine is absolute zero.\n\nThe Celsius/Kelvin and Fahrenheit/Rankine scales have a ratio of 5 : 9.\n\n\n;Task\nWrite code that accepts a value of kelvin, converts it to values of the three other scales, and prints the result. \n\n\n;Example:\n\nK 21.00\n\nC -252.15\n\nF -421.87\n\nR 37.80\n\n\n", "solution": "// version 1.1.2\n\nclass Kelvin(val degrees: Double) {\n fun toCelsius() = degrees - 273.15\n\n fun toFahreneit() = (degrees - 273.15) * 1.8 + 32.0\n\n fun toRankine() = (degrees - 273.15) * 1.8 + 32.0 + 459.67\n}\n\nfun main(args: Array) {\n print(\"Enter the temperature in degrees Kelvin : \")\n val degrees = readLine()!!.toDouble()\n val k = Kelvin(degrees)\n val f = \"% 1.2f\"\n println() \n println(\"K ${f.format(k.degrees)}\\n\")\n println(\"C ${f.format(k.toCelsius())}\\n\")\n println(\"F ${f.format(k.toFahreneit())}\\n\")\n println(\"R ${f.format(k.toRankine())}\")\n}"} {"title": "Test integerness", "language": "Kotlin", "task": "{| class=\"wikitable\"\n|-\n! colspan=2 | Input\n! colspan=2 | Output\n! rowspan=2 | Comment\n|-\n! Type\n! Value\n! exact\n! tolerance = 0.00001\n|-\n| rowspan=3 | decimal\n| 25.000000\n| colspan=2 | true\n| \n|-\n| 24.999999\n| false\n| true\n| \n|-\n| 25.000100\n| colspan=2 | false\n| \n|-\n| rowspan=4 | floating-point\n| -2.1e120\n| colspan=2 | true\n| This one is tricky, because in most languages it is too large to fit into a native integer type.It is, nonetheless, mathematically an integer, and your code should identify it as such.\n|-\n| -5e-2\n| colspan=2 | false\n| \n|-\n| NaN\n| colspan=2 | false\n| \n|-\n| Inf\n| colspan=2 | false\n| This one is debatable. If your code considers it an integer, that's okay too.\n|-\n| rowspan=2 | complex\n| 5.0+0.0i\n| colspan=2 | true\n| \n|-\n| 5-5i\n| colspan=2 | false\n| \n|}\n\n(The types and notations shown in these tables are merely examples - you should use the native data types and number literals of your programming language and standard library. Use a different set of test-cases, if this one doesn't demonstrate all relevant behavior.)\n\n\n", "solution": "// version 1.1.2\n\nimport java.math.BigInteger\nimport java.math.BigDecimal\n\nfun Double.isLong(tolerance: Double = 0.0) =\n (this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance\n\nfun BigDecimal.isBigInteger() = \n try {\n this.toBigIntegerExact()\n true\n }\n catch (ex: ArithmeticException) {\n false\n }\n\nclass Rational(val num: Long, val denom: Long) {\n fun isLong() = num % denom == 0L\n \n override fun toString() = \"$num/$denom\"\n}\n \nclass Complex(val real: Double, val imag: Double) {\n fun isLong() = real.isLong() && imag == 0.0\n\n override fun toString() = \n if (imag >= 0.0)\n \"$real + ${imag}i\"\n else\n \"$real - ${-imag}i\"\n}\n \nfun main(args: Array) {\n val da = doubleArrayOf(25.000000, 24.999999, 25.000100)\n for (d in da) {\n val exact = d.isLong()\n println(\"${\"%.6f\".format(d)} is ${if (exact) \"an\" else \"not an\"} integer\")\n }\n val tolerance = 0.00001 \n println(\"\\nWith a tolerance of ${\"%.5f\".format(tolerance)}:\")\n for (d in da) {\n val fuzzy = d.isLong(tolerance)\n println(\"${\"%.6f\".format(d)} is ${if (fuzzy) \"an\" else \"not an\"} integer\")\n }\n\n println()\n val fa = doubleArrayOf(-2.1e120, -5e-2, Double.NaN, Double.POSITIVE_INFINITY) \n for (f in fa) {\n val exact = if (f.isNaN() || f.isInfinite()) false \n else BigDecimal(f.toString()).isBigInteger()\n println(\"$f is ${if (exact) \"an\" else \"not an\"} integer\")\n }\n \n println()\n val ca = arrayOf(Complex(5.0, 0.0), Complex(5.0, -5.0))\n for (c in ca) {\n val exact = c.isLong()\n println(\"$c is ${if (exact) \"an\" else \"not an\"} integer\")\n }\n\n println()\n val ra = arrayOf(Rational(24, 8), Rational(-5, 1), Rational(17, 2))\n for (r in ra) {\n val exact = r.isLong()\n println(\"$r is ${if (exact) \"an\" else \"not an\"} integer\")\n }\n}"} {"title": "Textonyms", "language": "Kotlin", "task": "When entering text on a phone's digital pad it is possible that a particular combination of digits corresponds to more than one word. Such are called textonyms.\n\nAssuming the digit keys are mapped to letters as follows:\n 2 -> ABC\n 3 -> DEF\n 4 -> GHI\n 5 -> JKL\n 6 -> MNO\n 7 -> PQRS\n 8 -> TUV\n 9 -> WXYZ \n\n\n;Task:\nWrite a program that finds textonyms in a list of words such as \n[[Textonyms/wordlist]] or \nunixdict.txt.\n\nThe task should produce a report:\n\n There are #{0} words in #{1} which can be represented by the digit key mapping.\n They require #{2} digit combinations to represent them.\n #{3} digit combinations represent Textonyms.\n\nWhere:\n #{0} is the number of words in the list which can be represented by the digit key mapping.\n #{1} is the URL of the wordlist being used.\n #{2} is the number of digit combinations required to represent the words in #{0}.\n #{3} is the number of #{2} which represent more than one word.\n\nAt your discretion show a couple of examples of your solution displaying Textonyms. \n\nE.G.:\n\n 2748424767 -> \"Briticisms\", \"criticisms\"\n\n\n;Extra credit:\nUse a word list and keypad mapping other than English.\n\n\n\n", "solution": "// version 1.1.4-3\n\nimport java.io.File\n\nval wordList = \"unixdict.txt\"\nval url = \"http://www.puzzlers.org/pub/wordlists/unixdict.txt\"\n\nconst val DIGITS = \"22233344455566677778889999\"\n\nval map = mutableMapOf>()\n\nfun processList() {\n var countValid = 0\n val f = File(wordList)\n val sb = StringBuilder()\n\n f.forEachLine { word->\n var valid = true\n sb.setLength(0)\n for (c in word.toLowerCase()) {\n if (c !in 'a'..'z') {\n valid = false\n break\n } \n sb.append(DIGITS[c - 'a'])\n }\n if (valid) {\n countValid++\n val key = sb.toString()\n if (map.containsKey(key)) {\n map[key]!!.add(word)\n }\n else {\n map.put(key, mutableListOf(word))\n }\n } \n }\n var textonyms = map.filter { it.value.size > 1 }.toList() \n val report = \"There are $countValid words in '$url' \" +\n \"which can be represented by the digit key mapping.\\n\" +\n \"They require ${map.size} digit combinations to represent them.\\n\" +\n \"${textonyms.size} digit combinations represent Textonyms.\\n\"\n println(report)\n\n val longest = textonyms.sortedByDescending { it.first.length }\n val ambiguous = longest.sortedByDescending { it.second.size }\n\n println(\"Top 8 in ambiguity:\\n\")\n println(\"Count Textonym Words\")\n println(\"====== ======== =====\")\n var fmt = \"%4d %-8s %s\"\n for (a in ambiguous.take(8)) println(fmt.format(a.second.size, a.first, a.second))\n\n fmt = fmt.replace(\"8\", \"14\")\n println(\"\\nTop 6 in length:\\n\")\n println(\"Length Textonym Words\")\n println(\"====== ============== =====\")\n for (l in longest.take(6)) println(fmt.format(l.first.length, l.first, l.second)) \n}\n\nfun main(args: Array) {\n processList()\n}"} {"title": "The Name Game", "language": "Kotlin", "task": "Write a program that accepts a name as input and outputs the lyrics to the Shirley Ellis song \"The Name Game\".\n\n\nThe regular verse\n\nUnless your name begins with a vowel (A, E, I, O, U), 'B', 'F' or 'M' you don't have to care about special rules.\nThe verse for the name 'Gary' would be like this:\n\n Gary, Gary, bo-bary\n Banana-fana fo-fary\n Fee-fi-mo-mary\n Gary! \n\nAt the end of every line, the name gets repeated without the first letter: Gary becomes ary\nIf we take (X) as the full name (Gary) and (Y) as the name without the first letter (ary) the verse would look like this:\n\n (X), (X), bo-b(Y)\n Banana-fana fo-f(Y)\n Fee-fi-mo-m(Y)\n (X)! \n\nVowel as first letter of the name\n\nIf you have a vowel as the first letter of your name (e.g. Earl) you do not truncate the name.\nThe verse looks like this:\n\n Earl, Earl, bo-bearl\n Banana-fana fo-fearl\n Fee-fi-mo-mearl\n Earl! \n\n'B', 'F' or 'M' as first letter of the name\n\nIn case of a 'B', an 'F' or an 'M' (e.g. Billy, Felix, Mary) there is a special rule.\nThe line which would 'rebuild' the name (e.g. bo-billy) is sung without the first letter of the name.\nThe verse for the name Billy looks like this:\n\n Billy, Billy, bo-illy\n Banana-fana fo-filly\n Fee-fi-mo-milly\n Billy! \n\nFor the name 'Felix', this would be right:\n\n Felix, Felix, bo-belix\n Banana-fana fo-elix\n Fee-fi-mo-melix\n Felix!\n\n\n", "solution": "// version 1.2.31\n\nfun printVerse(name: String) {\n val x = name.toLowerCase().capitalize()\n val y = if (x[0] in \"AEIOU\") x.toLowerCase() else x.substring(1)\n var b = \"b$y\"\n var f = \"f$y\"\n var m = \"m$y\"\n when (x[0]) {\n 'B' -> b = \"$y\"\n 'F' -> f = \"$y\"\n 'M' -> m = \"$y\"\n else -> {} // no adjustment needed\n }\n println(\"$x, $x, bo-$b\")\n println(\"Banana-fana fo-$f\")\n println(\"Fee-fi-mo-$m\")\n println(\"$x!\\n\")\n}\n\nfun main(args: Array) {\n listOf(\"Gary\", \"Earl\", \"Billy\", \"Felix\", \"Mary\", \"Steve\").forEach { printVerse(it) }\n}"} {"title": "The Twelve Days of Christmas", "language": "Kotlin from C#", "task": "Write a program that outputs the lyrics of the Christmas carol ''The Twelve Days of Christmas''. \nThe lyrics can be found here. \n\n(You must reproduce the words in the correct order, but case, format, and punctuation are left to your discretion.)\n\n\n\n", "solution": "enum class Day {\n first, second, third, fourth, fifth, sixth, seventh, eighth, ninth, tenth, eleventh, twelfth;\n val header = \"On the \" + this + \" day of Christmas, my true love sent to me\\n\\t\"\n}\n\nfun main(x: Array) {\n val gifts = listOf(\"A partridge in a pear tree\",\n \"Two turtle doves and\",\n \"Three french hens\",\n \"Four calling birds\",\n \"Five golden rings\",\n \"Six geese a-laying\",\n \"Seven swans a-swimming\",\n \"Eight maids a-milking\",\n \"Nine ladies dancing\",\n \"Ten lords a-leaping\",\n \"Eleven pipers piping\",\n \"Twelve drummers drumming\")\n\n Day.values().forEachIndexed { i, d -> println(d.header + gifts.slice(0..i).asReversed().joinToString(\"\\n\\t\")) }\n}"} {"title": "Thue-Morse", "language": "Kotlin from Java", "task": "Create a Thue-Morse sequence.\n\n\n;See also\n* YouTube entry: The Fairest Sharing Sequence Ever\n* YouTube entry: Math and OCD - My story with the Thue-Morse sequence\n* Task: [[Fairshare between two and more]]\n\n", "solution": "fun thueMorse(n: Int): String {\n val sb0 = StringBuilder(\"0\")\n val sb1 = StringBuilder(\"1\")\n repeat(n) {\n val tmp = sb0.toString()\n sb0.append(sb1)\n sb1.append(tmp)\n }\n return sb0.toString()\n}\n\nfun main() {\n for (i in 0..6) println(\"$i : ${thueMorse(i)}\")\n}"} {"title": "Tonelli-Shanks algorithm", "language": "Kotlin from Go", "task": "{{wikipedia}}\n\n\nIn computational number theory, the Tonelli-Shanks algorithm is a technique for solving for '''x''' in a congruence of the form:\n\n:: x2 n (mod p)\n\nwhere '''n''' is an integer which is a quadratic residue (mod p), '''p''' is an odd prime, and '''x,n Fp''' where Fp = {0, 1, ..., p - 1}.\n\nIt is used in cryptography techniques.\n\n\nTo apply the algorithm, we need the Legendre symbol:\n\nThe Legendre symbol '''(a | p)''' denotes the value of a(p-1)/2 (mod p).\n* '''(a | p) 1''' if '''a''' is a square (mod p)\n* '''(a | p) -1''' if '''a''' is not a square (mod p)\n* '''(a | p) 0''' if '''a''' 0 (mod p) \n\n\n;Algorithm pseudo-code:\n\nAll are taken to mean (mod p) unless stated otherwise.\n\n* Input: '''p''' an odd prime, and an integer '''n''' .\n* Step 0: Check that '''n''' is indeed a square: (n | p) must be 1 .\n* Step 1: By factoring out powers of 2 from p - 1, find '''q''' and '''s''' such that p - 1 = q2s with '''q''' odd .\n** If p 3 (mod 4) (i.e. s = 1), output the two solutions r +- n(p+1)/4 .\n* Step 2: Select a non-square '''z''' such that (z | p) -1 and set c zq .\n* Step 3: Set r n(q+1)/2, t nq, m = s .\n* Step 4: Loop the following:\n** If t 1, output '''r''' and '''p - r''' .\n** Otherwise find, by repeated squaring, the lowest '''i''', 0 < i < m , such that t2i 1 .\n** Let b c2(m - i - 1), and set r rb, t tb2, c b2 and m = i .\n\n\n\n;Task:\nImplement the above algorithm. \n\nFind solutions (if any) for \n* n = 10 p = 13\n* n = 56 p = 101\n* n = 1030 p = 10009\n* n = 1032 p = 10009\n* n = 44402 p = 100049 \n\n;Extra credit:\n* n = 665820697 p = 1000000009 \n* n = 881398088036 p = 1000000000039 \n* n = 41660815127637347468140745042827704103445750172002 p = 10^50 + 577 \t\n\n\n;See also:\n* [[Modular exponentiation]]\n* [[Cipolla's algorithm]]\n\n", "solution": "// version 1.1.3\n\nimport java.math.BigInteger\n\ndata class Solution(val root1: BigInteger, val root2: BigInteger, val exists: Boolean)\n \nval bigZero = BigInteger.ZERO\nval bigOne = BigInteger.ONE\nval bigTwo = BigInteger.valueOf(2L)\nval bigFour = BigInteger.valueOf(4L)\nval bigTen = BigInteger.TEN\n\nfun ts(n: Long, p: Long) = ts(BigInteger.valueOf(n), BigInteger.valueOf(p))\n\nfun ts(n: BigInteger, p: BigInteger): Solution {\n\n fun powModP(a: BigInteger, e: BigInteger) = a.modPow(e, p)\n\n fun ls(a: BigInteger) = powModP(a, (p - bigOne) / bigTwo)\n\n if (ls(n) != bigOne) return Solution(bigZero, bigZero, false)\n var q = p - bigOne\n var ss = bigZero\n while (q.and(bigOne) == bigZero) {\n ss = ss + bigOne\n q = q.shiftRight(1)\n }\n\n if (ss == bigOne) {\n val r1 = powModP(n, (p + bigOne) / bigFour)\n return Solution(r1, p - r1, true)\n }\n\n var z = bigTwo\n while (ls(z) != p - bigOne) z = z + bigOne\n var c = powModP(z, q)\n var r = powModP(n, (q + bigOne) / bigTwo)\n var t = powModP(n, q)\n var m = ss\n\n while (true) {\n if (t == bigOne) return Solution(r, p - r, true)\n var i = bigZero\n var zz = t\n while (zz != bigOne && i < m - bigOne) {\n zz = zz * zz % p\n i = i + bigOne\n }\n var b = c\n var e = m - i - bigOne\n while (e > bigZero) {\n b = b * b % p\n e = e - bigOne\n }\n r = r * b % p\n c = b * b % p\n t = t * c % p\n m = i\n }\n}\n\nfun main(args: Array) {\n val pairs = listOf>(\n 10L to 13L, \n 56L to 101L, \n 1030L to 10009L,\n 1032L to 10009L,\n 44402L to 100049L,\n 665820697L to 1000000009L,\n 881398088036L to 1000000000039L\n )\n\n for (pair in pairs) {\n val (n, p) = pair\n val (root1, root2, exists) = ts(n, p)\n println(\"n = $n\")\n println(\"p = $p\")\n if (exists) {\n println(\"root1 = $root1\")\n println(\"root2 = $root2\")\n }\n else println(\"No solution exists\")\n println()\n }\n\n val bn = BigInteger(\"41660815127637347468140745042827704103445750172002\")\n val bp = bigTen.pow(50) + BigInteger.valueOf(577L)\n val (broot1, broot2, bexists) = ts(bn, bp)\n println(\"n = $bn\")\n println(\"p = $bp\")\n if (bexists) {\n println(\"root1 = $broot1\")\n println(\"root2 = $broot2\")\n }\n else println(\"No solution exists\") \n}"} {"title": "Top rank per group", "language": "Kotlin", "task": "Find the top ''N'' salaries in each department, where ''N'' is provided as a parameter.\n\nUse this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:\n\nEmployee Name,Employee ID,Salary,Department\nTyler Bennett,E10297,32000,D101\nJohn Rappl,E21437,47000,D050\nGeorge Woltman,E00127,53500,D101\nAdam Smith,E63535,18000,D202\nClaire Buckman,E39876,27800,D202\nDavid McClellan,E04242,41500,D101\nRich Holcomb,E01234,49500,D202\nNathan Adams,E41298,21900,D050\nRichard Potter,E43128,15900,D101\nDavid Motsinger,E27002,19250,D202\nTim Sampair,E03033,27000,D101\nKim Arlich,E10001,57000,D190\nTimothy Grove,E16398,29900,D190\n\n\n", "solution": "// version 1.1.2\n\ndata class Employee(val name: String, val id: String, val salary: Int, val dept: String)\n\nconst val N = 2 //say\n\nfun main(args: Array) {\n val employees = listOf(\n Employee(\"Tyler Bennett\", \"E10297\", 32000, \"D101\"),\n Employee(\"John Rappl\", \"E21437\", 47000, \"D050\"),\n Employee(\"George Woltman\" , \"E00127\", 53500, \"D101\"),\n Employee(\"Adam Smith\", \"E63535\", 18000, \"D202\"),\n Employee(\"Claire Buckman\", \"E39876\", 27800, \"D202\"),\n Employee(\"David McClellan\", \"E04242\", 41500, \"D101\"),\n Employee(\"Rich Holcomb\", \"E01234\", 49500, \"D202\"),\n Employee(\"Nathan Adams\", \"E41298\", 21900, \"D050\"),\n Employee(\"Richard Potter\", \"E43128\", 15900, \"D101\"),\n Employee(\"David Motsinger\", \"E27002\", 19250, \"D202\"),\n Employee(\"Tim Sampair\", \"E03033\", 27000, \"D101\"),\n Employee(\"Kim Arlich\", \"E10001\", 57000, \"D190\"),\n Employee(\"Timothy Grove\", \"E16398\", 29900, \"D190\")\n )\n val employeesByDept = employees.sortedBy { it.dept }.groupBy { it.dept }\n println(\"Highest $N salaries by department:\\n\")\n for ((key, value) in employeesByDept) {\n val topRanked = value.sortedByDescending { it.salary }.take(N)\n println(\"Dept $key => \")\n for (i in 0 until N) with (topRanked[i]) { println(\"${name.padEnd(15)} $id $salary\") }\n println()\n }\n}"} {"title": "Topic variable", "language": "Kotlin", "task": "Several programming languages offer syntax shortcuts to deal with the notion of \"current\" or \"topic\" variable.\n\nA topic variable is a special variable with a very short name which can also often be omitted.\n\nDemonstrate the utilization and behaviour of the topic variable within the language and explain or demonstrate how the topic variable behaves under different levels of nesting or scope, if this applies, within the language.\n\nFor instance you can (but you don't have to) show how the topic variable can be used by assigning the number 3 to it and then computing its square and square root.\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n 3.let {\n println(it)\n println(it * it)\n println(Math.sqrt(it.toDouble()))\n }\n}"} {"title": "Topswops", "language": "Kotlin from Java", "task": "Topswops is a card game created by John Conway in the 1970's.\n\n\nAssume you have a particular permutation of a set of n cards numbered 1..n on both of their faces, for example the arrangement of four cards given by [2, 4, 1, 3] where the leftmost card is on top. \n\nA round is composed of reversing the first m cards where m is the value of the topmost card. \n\nRounds are repeated until the topmost card is the number 1 and the number of swaps is recorded. \n\n\nFor our example the swaps produce:\n \n [2, 4, 1, 3] # Initial shuffle\n [4, 2, 1, 3]\n [3, 1, 2, 4]\n [2, 1, 3, 4]\n [1, 2, 3, 4]\n\n\nFor a total of four swaps from the initial ordering to produce the terminating case where 1 is on top.\n\n\nFor a particular number n of cards, topswops(n) is the maximum swaps needed for any starting permutation of the n cards.\n\n\n;Task:\nThe task is to generate and show here a table of n vs topswops(n) for n in the range 1..10 inclusive.\n\n\n;Note:\nTopswops is also known as Fannkuch from the German word ''Pfannkuchen'' meaning pancake.\n\n\n;Related tasks:\n* [[Number reversal game]]\n* [[Sorting algorithms/Pancake sort]]\n\n", "solution": "// version 1.1.2\n\nval best = IntArray(32)\n\nfun trySwaps(deck: IntArray, f: Int, d: Int, n: Int) {\n if (d > best[n]) best[n] = d\n for (i in n - 1 downTo 0) {\n if (deck[i] == -1 || deck[i] == i) break\n if (d + best[i] <= best[n]) return\n }\n val deck2 = deck.copyOf()\n for (i in 1 until n) {\n val k = 1 shl i\n if (deck2[i] == -1) {\n if ((f and k) != 0) continue\n }\n else if (deck2[i] != i) continue\n deck2[0] = i\n for (j in i - 1 downTo 0) deck2[i - j] = deck[j] \n trySwaps(deck2, f or k, d + 1, n)\n }\n}\n\nfun topswops(n: Int): Int {\n require(n > 0 && n < best.size)\n best[n] = 0\n val deck0 = IntArray(n + 1)\n for (i in 1 until n) deck0[i] = -1\n trySwaps(deck0, 1, 0, n)\n return best[n]\n}\n\nfun main(args: Array) {\n for (i in 1..10) println(\"${\"%2d\".format(i)} : ${topswops(i)}\")\n}"} {"title": "Total circles area", "language": "Kotlin from Python", "task": "Example circles\nExample circles filtered\n\nGiven some partially overlapping circles on the plane, compute and show the total area covered by them, with four or six (or a little more) decimal digits of precision. The area covered by two or more disks needs to be counted only once. \n\nOne point of this Task is also to compare and discuss the relative merits of various solution strategies, their performance, precision and simplicity. This means keeping both slower and faster solutions for a language (like C) is welcome.\n\nTo allow a better comparison of the different implementations, solve the problem with this standard dataset, each line contains the '''x''' and '''y''' coordinates of the centers of the disks and their radii (11 disks are fully contained inside other disks):\n\n xc yc radius\n 1.6417233788 1.6121789534 0.0848270516\n -1.4944608174 1.2077959613 1.1039549836\n 0.6110294452 -0.6907087527 0.9089162485\n 0.3844862411 0.2923344616 0.2375743054\n -0.2495892950 -0.3832854473 1.0845181219\n 1.7813504266 1.6178237031 0.8162655711\n -0.1985249206 -0.8343333301 0.0538864941\n -1.7011985145 -0.1263820964 0.4776976918\n -0.4319462812 1.4104420482 0.7886291537\n 0.2178372997 -0.9499557344 0.0357871187\n -0.6294854565 -1.3078893852 0.7653357688\n 1.7952608455 0.6281269104 0.2727652452\n 1.4168575317 1.0683357171 1.1016025378\n 1.4637371396 0.9463877418 1.1846214562\n -0.5263668798 1.7315156631 1.4428514068\n -1.2197352481 0.9144146579 1.0727263474\n -0.1389358881 0.1092805780 0.7350208828\n 1.5293954595 0.0030278255 1.2472867347\n -0.5258728625 1.3782633069 1.3495508831\n -0.1403562064 0.2437382535 1.3804956588\n 0.8055826339 -0.0482092025 0.3327165165\n -0.6311979224 0.7184578971 0.2491045282\n 1.4685857879 -0.8347049536 1.3670667538\n -0.6855727502 1.6465021616 1.0593087096\n 0.0152957411 0.0638919221 0.9771215985\n\n\nThe result is 21.56503660... .\n\n\n;Related task:\n* [[Circles of given radius through two points]].\n\n\n;See also:\n* http://www.reddit.com/r/dailyprogrammer/comments/zff9o/9062012_challenge_96_difficult_water_droplets/\n* http://stackoverflow.com/a/1667789/10562\n\n", "solution": "// version 1.1.2\n\nclass Point(val x: Double, val y: Double)\n\nclass Circle(val x: Double, val y: Double, val r: Double)\n\nval circles = arrayOf(\n Circle( 1.6417233788, 1.6121789534, 0.0848270516),\n Circle(-1.4944608174, 1.2077959613, 1.1039549836),\n Circle( 0.6110294452, -0.6907087527, 0.9089162485),\n Circle( 0.3844862411, 0.2923344616, 0.2375743054),\n Circle(-0.2495892950, -0.3832854473, 1.0845181219),\n Circle( 1.7813504266, 1.6178237031, 0.8162655711),\n Circle(-0.1985249206, -0.8343333301, 0.0538864941),\n Circle(-1.7011985145, -0.1263820964, 0.4776976918),\n Circle(-0.4319462812, 1.4104420482, 0.7886291537),\n Circle( 0.2178372997, -0.9499557344, 0.0357871187),\n Circle(-0.6294854565, -1.3078893852, 0.7653357688),\n Circle( 1.7952608455, 0.6281269104, 0.2727652452),\n Circle( 1.4168575317, 1.0683357171, 1.1016025378),\n Circle( 1.4637371396, 0.9463877418, 1.1846214562),\n Circle(-0.5263668798, 1.7315156631, 1.4428514068),\n Circle(-1.2197352481, 0.9144146579, 1.0727263474),\n Circle(-0.1389358881, 0.1092805780, 0.7350208828),\n Circle( 1.5293954595, 0.0030278255, 1.2472867347),\n Circle(-0.5258728625, 1.3782633069, 1.3495508831),\n Circle(-0.1403562064, 0.2437382535, 1.3804956588),\n Circle( 0.8055826339, -0.0482092025, 0.3327165165),\n Circle(-0.6311979224, 0.7184578971, 0.2491045282),\n Circle( 1.4685857879, -0.8347049536, 1.3670667538),\n Circle(-0.6855727502, 1.6465021616, 1.0593087096),\n Circle( 0.0152957411, 0.0638919221, 0.9771215985)\n)\n\nfun Double.sq() = this * this\n\nfun areaScan(precision: Double): Double {\n fun sect(c: Circle, y: Double): Point {\n val dr = Math.sqrt(c.r.sq() - (y - c.y).sq())\n return Point(c.x - dr, c.x + dr)\n }\n\n val ys = circles.map { it.y + it.r } + circles.map { it.y - it.r }\n val mins = Math.floor(ys.min()!! / precision).toInt()\n val maxs = Math.ceil(ys.max()!! / precision).toInt()\n var total = 0.0\n for (x in mins..maxs) {\n val y = x * precision\n var right = Double.NEGATIVE_INFINITY\n val points = circles.filter { Math.abs(y - it.y) < it.r }\n .map { sect(it, y) }\n .sortedBy { it.x } \n for (p in points) {\n if (p.y <= right) continue\n total += p.y - maxOf(p.x, right)\n right = p.y\n }\n }\n return total * precision\n}\n\nfun main(args: Array) {\n val p = 1e-6\n println(\"Approximate area = ${areaScan(p)}\")\n}"} {"title": "Trabb Pardo\u2013Knuth algorithm", "language": "Kotlin", "task": "The TPK algorithm is an early example of a programming chrestomathy. \nIt was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages. \nThe report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.\n\nFrom the wikipedia entry:\n\n '''ask''' for 11 numbers to be read into a sequence ''S''\n '''reverse''' sequence ''S''\n '''for each''' ''item'' '''in''' sequence ''S''\n ''result'' ''':=''' '''call''' a function to do an ''operation''\n '''if''' ''result'' overflows\n '''alert''' user\n '''else'''\n '''print''' ''result''\n\nThe task is to implement the algorithm:\n# Use the function: f(x) = |x|^{0.5} + 5x^3\n# The overflow condition is an answer of greater than 400.\n# The 'user alert' should not stop processing of other items of the sequence.\n# Print a prompt before accepting '''eleven''', textual, numeric inputs.\n# You may optionally print the item as well as its associated result, but the results must be in reverse order of input.\n# The sequence ''' ''S'' ''' may be 'implied' and so not shown explicitly.\n# ''Print and show the program in action from a typical run here''. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).\n\n", "solution": "// version 1.1.2\n\nfun f(x: Double) = Math.sqrt(Math.abs(x)) + 5.0 * x * x * x\n \nfun main(args: Array) {\n val da = DoubleArray(11)\n println(\"Please enter 11 numbers:\")\n var i = 0\n while (i < 11) {\n print(\" ${\"%2d\".format(i + 1)}: \")\n val d = readLine()!!.toDoubleOrNull()\n if (d == null)\n println(\"Not a valid number, try again\")\n else\n da[i++] = d\n }\n println(\"\\nThe sequence you just entered in reverse is:\")\n da.reverse()\n println(da.contentToString())\n println(\"\\nProcessing this sequence...\")\n for (j in 0..10) {\n val v = f(da[j])\n print(\" ${\"%2d\".format(j + 1)}: \") \n if (v > 400.0) \n println(\"Overflow!\")\n else\n println(v)\n }\n}"} {"title": "Truncate a file", "language": "Kotlin", "task": "Truncate a file to a specific length. This should be implemented as a routine that takes two parameters: the filename and the required file length (in bytes).\n\n\nTruncation can be achieved using system or library calls intended for such a task, if such methods exist, or by creating a temporary file of a reduced size and renaming it, after first deleting the original file, if no other method is available. The file may contain non human readable binary data in an unspecified format, so the routine should be \"binary safe\", leaving the contents of the untruncated part of the file unchanged.\n\nIf the specified filename does not exist, or the provided length is not less than the current file length, then the routine should raise an appropriate error condition. \n\nOn some systems, the provided file truncation facilities might not change the file or may extend the file, if the specified length is greater than the current length of the file. \n\nThis task permits the use of such facilities. However, such behaviour should be noted, or optionally a warning message relating to an non change or increase in file size may be implemented.\n\n", "solution": "// version 1.1.2\n\nimport java.io.FileOutputStream\nimport java.nio.channels.FileChannel\n\nfun truncateFile(fileName: String, newSize: Long) {\n var fc: FileChannel? = null\n try {\n fc = FileOutputStream(fileName, true).channel\n if (newSize >= fc.size()) \n println(\"Requested file size isn't less than existing size\")\n else\n fc.truncate(newSize)\n }\n catch (ex: Exception) {\n println(ex.message)\n }\n finally {\n fc!!.close()\n }\n}\n\nfun main(args: Array) {\n truncateFile(\"test.txt\", 10)\n}"} {"title": "Truth table", "language": "Kotlin from D", "task": "A truth table is a display of the inputs to, and the output of a Boolean function organized as a table where each row gives one combination of input values and the corresponding value of the function.\n\n\n;Task:\n# Input a Boolean function from the user as a string then calculate and print a formatted truth table for the given function. (One can assume that the user input is correct).\n# Print and show output for Boolean functions of two and three input variables, but any program should not be limited to that many variables in the function. \n# Either reverse-polish or infix notation expressions are allowed.\n\n\n;Related tasks:\n* [[Boolean values]]\n* [[Ternary logic]]\n\n\n;See also:\n* Wolfram MathWorld entry on truth tables.\n* some \"truth table\" examples from Google.\n\n", "solution": "// Version 1.2.31\n\nimport java.util.Stack\n\nclass Variable(val name: Char, var value: Boolean = false)\n\nlateinit var expr: String\nvar variables = mutableListOf()\n\nfun Char.isOperator() = this in \"&|!^\"\n\nfun Char.isVariable() = this in variables.map { it.name }\n\nfun evalExpression(): Boolean {\n val stack = Stack()\n\n for (e in expr) {\n stack.push(\n if (e == 'T')\n true\n else if (e == 'F')\n false\n else if (e.isVariable())\n variables.single { it.name == e }.value\n else when (e) {\n '&' -> stack.pop() and stack.pop()\n '|' -> stack.pop() or stack.pop()\n '!' -> !stack.pop()\n '^' -> stack.pop() xor stack.pop()\n else -> throw RuntimeException(\"Non-conformant character '$e' in expression\")\n }\n )\n }\n\n require(stack.size == 1)\n return stack.peek()\n}\n\nfun setVariables(pos: Int) {\n require(pos <= variables.size)\n if (pos == variables.size) {\n val vs = variables.map { if (it.value) \"T\" else \"F\" }.joinToString(\" \")\n val es = if (evalExpression()) \"T\" else \"F\"\n return println(\"$vs $es\")\n }\n variables[pos].value = false\n setVariables(pos + 1)\n variables[pos].value = true\n setVariables(pos + 1)\n}\n\nfun main(args: Array) {\n println(\"Accepts single-character variables (except for 'T' and 'F',\")\n println(\"which specify explicit true or false values), postfix, with\")\n println(\"&|!^ for and, or, not, xor, respectively; optionally\")\n println(\"seperated by spaces or tabs. Just enter nothing to quit.\")\n\n while (true) {\n print(\"\\nBoolean expression: \")\n expr = readLine()!!.toUpperCase().replace(\" \", \"\").replace(\"\\t\", \"\")\n if (expr == \"\") return\n variables.clear()\n for (e in expr) {\n if (!e.isOperator() && e !in \"TF\" && !e.isVariable()) variables.add(Variable(e))\n }\n if (variables.isEmpty()) return\n val vs = variables.map { it.name }.joinToString(\" \")\n println(\"\\n$vs $expr\")\n val h = vs.length + expr.length + 2\n repeat(h) { print(\"=\") }\n println(\"\\n\")\n setVariables(0)\n }\n}"} {"title": "Two bullet roulette", "language": "Kotlin from C", "task": "The following is supposedly a question given to mathematics graduates seeking jobs on Wall Street:\n\n A revolver handgun has a revolving cylinder with six chambers for bullets.\n \n It is loaded with the following procedure:\n\n 1. Check the first chamber to the right of the trigger for a bullet. If a bullet\n is seen, the cylinder is rotated one chamber clockwise and the next chamber\n checked until an empty chamber is found.\n\n 2. A cartridge containing a bullet is placed in the empty chamber.\n\n 3. The cylinder is then rotated one chamber clockwise.\n \n To randomize the cylinder's position, the cylinder is spun, which causes the cylinder to take\n a random position from 1 to 6 chamber rotations clockwise from its starting position.\n \n When the trigger is pulled the gun will fire if there is a bullet in position 0, which is just\n counterclockwise from the loading position.\n \n The gun is unloaded by removing all cartridges from the cylinder.\n \n According to the legend, a suicidal Russian imperial military officer plays a game of Russian\n roulette by putting two bullets in a six-chamber cylinder and pulls the trigger twice.\n If the gun fires with a trigger pull, this is considered a successful suicide.\n \n The cylinder is always spun before the first shot, but it may or may not be spun after putting\n in the first bullet and may or may not be spun after taking the first shot.\n \n Which of the following situations produces the highest probability of suicide?\n \n A. Spinning the cylinder after loading the first bullet, and spinning again after the first shot.\n\n B. Spinning the cylinder after loading the first bullet only.\n\n C. Spinning the cylinder after firing the first shot only.\n\n D. Not spinning the cylinder either after loading the first bullet or after the first shot.\n\n E. The probability is the same for all cases.\n\n\n;Task:\n# Run a repeated simulation of each of the above scenario, calculating the percentage of suicide with a randomization of the four spinning, loading and firing order scenarios.\n# Show the results as a percentage of deaths for each type of scenario.\n# The hand calculated probabilities are 5/9, 7/12, 5/9, and 1/2. A correct program should produce results close enough to those to allow a correct response to the interview question. \n\n\n;Reference:\nYoutube video on the Russian 1895 Nagant revolver [[https://www.youtube.com/watch?v=Dh1mojMaEtM]]\n\n", "solution": "import kotlin.random.Random\n\nval cylinder = Array(6) { false }\n\nfun rShift() {\n val t = cylinder[cylinder.size - 1]\n for (i in (0 until cylinder.size - 1).reversed()) {\n cylinder[i + 1] = cylinder[i]\n }\n cylinder[0] = t\n}\n\nfun unload() {\n for (i in cylinder.indices) {\n cylinder[i] = false\n }\n}\n\nfun load() {\n while (cylinder[0]) {\n rShift()\n }\n cylinder[0] = true\n rShift()\n}\n\nfun spin() {\n val lim = Random.nextInt(0, 6) + 1\n for (i in 1..lim) {\n rShift()\n }\n}\n\nfun fire(): Boolean {\n val shot = cylinder[0]\n rShift()\n return shot\n}\n\nfun method(s: String): Int {\n unload()\n for (c in s) {\n when (c) {\n 'L' -> {\n load()\n }\n 'S' -> {\n spin()\n }\n 'F' -> {\n if (fire()) {\n return 1\n }\n }\n }\n }\n return 0\n}\n\nfun mString(s: String): String {\n val buf = StringBuilder()\n fun append(txt: String) {\n if (buf.isNotEmpty()) {\n buf.append(\", \")\n }\n buf.append(txt)\n }\n for (c in s) {\n when (c) {\n 'L' -> {\n append(\"load\")\n }\n 'S' -> {\n append(\"spin\")\n }\n 'F' -> {\n append(\"fire\")\n }\n }\n }\n return buf.toString()\n}\n\nfun test(src: String) {\n val tests = 100000\n var sum = 0\n\n for (t in 0..tests) {\n sum += method(src)\n }\n\n val str = mString(src)\n val pc = 100.0 * sum / tests\n println(\"%-40s produces %6.3f%% deaths.\".format(str, pc))\n}\n\nfun main() {\n test(\"LSLSFSF\");\n test(\"LSLSFF\");\n test(\"LLSFSF\");\n test(\"LLSFF\");\n}"} {"title": "UPC", "language": "Kotlin from C", "task": "Goal: \nConvert UPC bar codes to decimal.\n\n\nSpecifically:\n\nThe UPC standard is actually a collection of standards -- physical standards, data format standards, product reference standards... \n\nHere, in this task, we will focus on some of the data format standards, with an imaginary physical+electrical implementation which converts physical UPC bar codes to ASCII (with spaces and '''#''' characters representing the presence or absence of ink).\n\n\n;Sample input:\nBelow, we have a representation of ten different UPC-A bar codes read by our imaginary bar code reader:\n\n # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \n # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \n # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \n # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \n # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \n # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \n # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \n # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \n # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \n # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \n\nSome of these were entered upside down, and one entry has a timing error.\n\n\n;Task:\nImplement code to find the corresponding decimal representation of each, rejecting the error. \n\nExtra credit for handling the rows entered upside down (the other option is to reject them).\n\n\n;Notes:\nEach digit is represented by 7 bits:\n\n 0: 0 0 0 1 1 0 1\n 1: 0 0 1 1 0 0 1\n 2: 0 0 1 0 0 1 1\n 3: 0 1 1 1 1 0 1\n 4: 0 1 0 0 0 1 1\n 5: 0 1 1 0 0 0 1\n 6: 0 1 0 1 1 1 1\n 7: 0 1 1 1 0 1 1\n 8: 0 1 1 0 1 1 1\n 9: 0 0 0 1 0 1 1\n\nOn the left hand side of the bar code a space represents a '''0''' and a '''#''' represents a '''1'''. \nOn the right hand side of the bar code, a '''#''' represents a '''0''' and a space represents a '''1''' \nAlternatively (for the above): spaces always represent zeros and '''#''' characters always represent ones, but the representation is logically negated -- '''1'''s and '''0'''s are flipped -- on the right hand side of the bar code.\n\n\n\n;The UPC-A bar code structure:\n::* It begins with at least 9 spaces (which our imaginary bar code reader unfortunately doesn't always reproduce properly), \n::* then has a ''' # # ''' sequence marking the start of the sequence, \n::* then has the six \"left hand\" digits, \n::* then has a ''' # # ''' sequence in the middle, \n::* then has the six \"right hand digits\", \n::* then has another ''' # # ''' (end sequence), and finally, \n::* then ends with nine trailing spaces (which might be eaten by wiki edits, and in any event, were not quite captured correctly by our imaginary bar code reader).\n\n\nFinally, the last digit is a checksum digit which may be used to help detect errors. \n\n\n;Verification:\nMultiply each digit in the represented 12 digit sequence by the corresponding number in (3,1,3,1,3,1,3,1,3,1,3,1) and add the products.\n\nThe sum (mod 10) must be '''0''' (must have a zero as its last digit) if the UPC number has been read correctly.\n\n", "solution": "val LEFT_DIGITS = mapOf(\n \" ## #\" to 0,\n \" ## #\" to 1,\n \" # ##\" to 2,\n \" #### #\" to 3,\n \" # ##\" to 4,\n \" ## #\" to 5,\n \" # ####\" to 6,\n \" ### ##\" to 7,\n \" ## ###\" to 8,\n \" # ##\" to 9\n)\nval RIGHT_DIGITS = LEFT_DIGITS.mapKeys {\n it.key.replace(' ', 's').replace('#', ' ').replace('s', '#')\n}\n\nconst val END_SENTINEL = \"# #\"\nconst val MID_SENTINEL = \" # # \"\n\nfun decodeUPC(input: String) {\n fun decode(candidate: String): Pair> {\n var pos = 0\n var part = candidate.slice(pos until pos + END_SENTINEL.length)\n if (part == END_SENTINEL) {\n pos += END_SENTINEL.length\n } else {\n return Pair(false, emptyList())\n }\n\n val output = mutableListOf()\n for (i in 0 until 6) {\n part = candidate.slice(pos until pos + 7)\n pos += 7\n\n if (LEFT_DIGITS.containsKey(part)) {\n output.add(LEFT_DIGITS.getOrDefault(part, -1))\n } else {\n return Pair(false, output.toList())\n }\n }\n\n part = candidate.slice(pos until pos + MID_SENTINEL.length)\n if (part == MID_SENTINEL) {\n pos += MID_SENTINEL.length\n } else {\n return Pair(false, output.toList())\n }\n\n for (i in 0 until 6) {\n part = candidate.slice(pos until pos + 7)\n pos += 7\n\n if (RIGHT_DIGITS.containsKey(part)) {\n output.add(RIGHT_DIGITS.getOrDefault(part, -1))\n } else {\n return Pair(false, output.toList())\n }\n }\n\n part = candidate.slice(pos until pos + END_SENTINEL.length)\n if (part == END_SENTINEL) {\n pos += END_SENTINEL.length\n } else {\n return Pair(false, output.toList())\n }\n\n val sum = output.mapIndexed { i, v -> if (i % 2 == 0) v * 3 else v }.sum()\n return Pair(sum % 10 == 0, output.toList())\n }\n\n val candidate = input.trim()\n\n var out = decode(candidate)\n if (out.first) {\n println(out.second)\n } else {\n out = decode(candidate.reversed())\n if (out.first) {\n print(out.second)\n println(\" Upside down\")\n } else {\n if (out.second.size == 12) {\n println(\"Invalid checksum\")\n } else {\n println(\"Invalid digit(s)\")\n }\n }\n }\n\n}\n\nfun main() {\n val barcodes = listOf(\n \" # # # ## # ## # ## ### ## ### ## #### # # # ## ## # # ## ## ### # ## ## ### # # # \",\n \" # # # ## ## # #### # # ## # ## # ## # # # ### # ### ## ## ### # # ### ### # # # \",\n \" # # # # # ### # # # # # # # # # # ## # ## # ## # ## # # #### ### ## # # \",\n \" # # ## ## ## ## # # # # ### # ## ## # # # ## ## # ### ## ## # # #### ## # # # \",\n \" # # ### ## # ## ## ### ## # ## # # ## # # ### # ## ## # # ### # ## ## # # # \",\n \" # # # # ## ## # # # # ## ## # # # # # #### # ## # #### #### # # ## # #### # # \",\n \" # # # ## ## # # ## ## # ### ## ## # # # # # # # # ### # # ### # # # # # \",\n \" # # # # ## ## # # ## ## ### # # # # # ### ## ## ### ## ### ### ## # ## ### ## # # \",\n \" # # ### ## ## # # #### # ## # #### # #### # # # # # ### # # ### # # # ### # # # \",\n \" # # # #### ## # #### # # ## ## ### #### # # # # ### # ### ### # # ### # # # ### # # \",\n )\n\n for (barcode in barcodes) {\n decodeUPC(barcode)\n }\n}"} {"title": "URL decoding", "language": "Kotlin", "task": "This task (the reverse of [[URL encoding]] and distinct from [[URL parser]]) is to provide a function \nor mechanism to convert an URL-encoded string into its original unencoded form.\n\n\n;Test cases:\n* The encoded string \"http%3A%2F%2Ffoo%20bar%2F\" should be reverted to the unencoded form \"http://foo bar/\".\n\n* The encoded string \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\" should revert to the unencoded form \"google.com/search?q=`Abdu'l-Baha\".\n\n* The encoded string \"%25%32%35\" should revert to the unencoded form \"%25\" and '''not''' \"%\".\n\n", "solution": "// version 1.1.2\n\nimport java.net.URLDecoder\n\nfun main(args: Array) {\n val encoded = arrayOf(\"http%3A%2F%2Ffoo%20bar%2F\", \"google.com/search?q=%60Abdu%27l-Bah%C3%A1\")\n for (e in encoded) println(URLDecoder.decode(e, \"UTF-8\"))\n}"} {"title": "URL encoding", "language": "Kotlin", "task": "Provide a function or mechanism to convert a provided string into URL encoding representation.\n\nIn URL encoding, special characters, control characters and extended characters \nare converted into a percent symbol followed by a two digit hexadecimal code, \nSo a space character encodes into %20 within the string.\n\nFor the purposes of this task, every character except 0-9, A-Z and a-z requires conversion, so the following characters all require conversion by default:\n\n* ASCII control codes (Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal).\n* ASCII symbols (Character ranges 32-47 decimal (20-2F hex))\n* ASCII symbols (Character ranges 58-64 decimal (3A-40 hex))\n* ASCII symbols (Character ranges 91-96 decimal (5B-60 hex))\n* ASCII symbols (Character ranges 123-126 decimal (7B-7E hex))\n* Extended characters with character codes of 128 decimal (80 hex) and above.\n\n\n;Example:\nThe string \"http://foo bar/\" would be encoded as \"http%3A%2F%2Ffoo%20bar%2F\".\n\n\n;Variations:\n* Lowercase escapes are legal, as in \"http%3a%2f%2ffoo%20bar%2f\".\n* Special characters have different encodings for different standards:\n** RFC 3986, ''Uniform Resource Identifier (URI): Generic Syntax'', section 2.3, says to preserve \"-._~\".\n** HTML 5, section 4.10.22.5 URL-encoded form data, says to preserve \"-._*\", and to encode space \" \" to \"+\".\n** encodeURI function in Javascript will preserve \"-._~\" (RFC 3986) and \";,/?:@&=+$!*'()#\".\n\n;Options:\nIt is permissible to use an exception string (containing a set of symbols \nthat do not need to be converted). \nHowever, this is an optional feature and is not a requirement of this task.\n\n\n;Related tasks: \n* [[URL decoding]]\n* [[URL parser]]\n\n", "solution": "// version 1.1.2\n\nimport java.net.URLEncoder\n\nfun main(args: Array) {\n val url = \"http://foo bar/\"\n println(URLEncoder.encode(url, \"utf-8\")) // note: encodes space to + not %20\n}"} {"title": "URL parser", "language": "Kotlin", "task": "URLs are strings with a simple syntax:\n scheme://[username:password@]domain[:port]/path?query_string#fragment_id\n\n\n;Task:\nParse a well-formed URL to retrieve the relevant information: '''scheme''', '''domain''', '''path''', ...\n\n\nNote: this task has nothing to do with [[URL encoding]] or [[URL decoding]].\n\n\nAccording to the standards, the characters:\n:::: ! * ' ( ) ; : @ & = + $ , / ? % # [ ] \nonly need to be percent-encoded ('''%''') in case of possible confusion. \n\nAlso note that the '''path''', '''query''' and '''fragment''' are case sensitive, even if the '''scheme''' and '''domain''' are not.\n\nThe way the returned information is provided (set of variables, array, structured, record, object,...) \nis language-dependent and left to the programmer, but the code should be clear enough to reuse.\n\nExtra credit is given for clear error diagnostics.\n\n* Here is the official standard: https://tools.ietf.org/html/rfc3986, \n* and here is a simpler BNF: http://www.w3.org/Addressing/URL/5_URI_BNF.html.\n\n\n;Test cases:\nAccording to T. Berners-Lee\n \n'''foo://example.com:8042/over/there?name=ferret#nose''' should parse into:\n::* scheme = foo\n::* domain = example.com\n::* port = :8042\n::* path = over/there\n::* query = name=ferret\n::* fragment = nose\n\n\n'''urn:example:animal:ferret:nose''' should parse into:\n::* scheme = urn\n::* path = example:animal:ferret:nose\n\n\n'''other URLs that must be parsed include:'''\n:* jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true \n:* ftp://ftp.is.co.za/rfc/rfc1808.txt \n:* http://www.ietf.org/rfc/rfc2396.txt#header1 \n:* ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two \n:* mailto:John.Doe@example.com \n:* news:comp.infosystems.www.servers.unix \n:* tel:+1-816-555-1212 \n:* telnet://192.0.2.16:80/ \n:* urn:oasis:names:specification:docbook:dtd:xml:4.1.2 \n\n", "solution": "// version 1.1.2\n\nimport java.net.URL\nimport java.net.MalformedURLException\n\nfun parseUrl(url: String) {\n var u: URL\n var scheme: String\n try {\n u = URL(url)\n scheme = u.protocol \n }\n catch (ex: MalformedURLException) {\n val index = url.indexOf(':')\n scheme = url.take(index)\n u = URL(\"http\" + url.drop(index))\n }\n println(\"Parsing $url\") \n println(\" scheme = $scheme\") \n \n with(u) { \n if (userInfo != null) println(\" userinfo = $userInfo\") \n if (!host.isEmpty()) println(\" domain = $host\")\n if (port != -1) println(\" port = $port\")\n if (!path.isEmpty()) println(\" path = $path\")\n if (query != null) println(\" query = $query\")\n if (ref != null) println(\" fragment = $ref\") \n }\n println()\n}\n\nfun main(args: Array){\n val urls = arrayOf(\n \"foo://example.com:8042/over/there?name=ferret#nose\",\n \"urn:example:animal:ferret:nose\",\n \"jdbc:mysql://test_user:ouupppssss@localhost:3306/sakila?profileSQL=true\",\n \"ftp://ftp.is.co.za/rfc/rfc1808.txt\",\n \"http://www.ietf.org/rfc/rfc2396.txt#header1\",\n \"ldap://[2001:db8::7]/c=GB?objectClass=one&objectClass=two\",\n \"mailto:John.Doe@example.com\",\n \"news:comp.infosystems.www.servers.unix\",\n \"tel:+1-816-555-1212\",\n \"telnet://192.0.2.16:80/\",\n \"urn:oasis:names:specification:docbook:dtd:xml:4.1.2\",\n \"ssh://alice@example.com\",\n \"https://bob:pass@example.com/place\",\n \"http://example.com/?a=1&b=2+2&c=3&c=4&d=%65%6e%63%6F%64%65%64\"\n ) \n for (url in urls) parseUrl(url)\n}"} {"title": "UTF-8 encode and decode", "language": "Kotlin", "task": "As described in Wikipedia, UTF-8 is a popular encoding of (multi-byte) [[Unicode]] code-points into eight-bit octets.\n\nThe goal of this task is to write a encoder that takes a unicode code-point (an integer representing a unicode character) and returns a sequence of 1-4 bytes representing that character in the UTF-8 encoding. \n\nThen you have to write the corresponding decoder that takes a sequence of 1-4 UTF-8 encoded bytes and return the corresponding unicode character.\n\nDemonstrate the functionality of your encoder and decoder on the following five characters:\n\n\nCharacter Name Unicode UTF-8 encoding (hex)\n---------------------------------------------------------------------------------\nA LATIN CAPITAL LETTER A U+0041 41\no LATIN SMALL LETTER O WITH DIAERESIS U+00F6 C3 B6\nZh CYRILLIC CAPITAL LETTER ZHE U+0416 D0 96\nEUR EURO SIGN U+20AC E2 82 AC\n MUSICAL SYMBOL G CLEF U+1D11E F0 9D 84 9E\n\n\nProvided below is a reference implementation in Common Lisp.\n\n", "solution": "// version 1.1.2\n\nfun utf8Encode(codePoint: Int) = String(intArrayOf(codePoint), 0, 1).toByteArray(Charsets.UTF_8)\n\nfun utf8Decode(bytes: ByteArray) = String(bytes, Charsets.UTF_8).codePointAt(0)\n\nfun main(args: Array) {\n val codePoints = intArrayOf(0x0041, 0x00F6, 0x0416, 0x20AC, 0x1D11E)\n println(\"Char Name Unicode UTF-8 Decoded\")\n for (codePoint in codePoints) {\n var n = if(codePoint <= 0xFFFF) 4 else 5 \n System.out.printf(\"%-${n}c %-35s U+%05X \", codePoint, Character.getName(codePoint), codePoint) \n val bytes = utf8Encode(codePoint)\n var s = \"\"\n for (byte in bytes) s += \"%02X \".format(byte)\n val decoded = utf8Decode(bytes)\n n = if(decoded.toInt() <= 0xFFFF) 12 else 11 \n System.out.printf(\"%-${n}s %c\\n\", s, decoded) \n } \n}"} {"title": "Unbias a random generator", "language": "Kotlin from Java", "task": "Given a weighted one-bit generator of random numbers where the probability of a one occurring, P_1, is not the same as P_0, the probability of a zero occurring, the probability of the occurrence of a one followed by a zero is P_1 x P_0, assuming independence. This is the same as the probability of a zero followed by a one: P_0 x P_1.\n\n;Task details:\n* Use your language's random number generator to create a function/method/subroutine/... '''randN''' that returns a one or a zero, but with one occurring, on average, 1 out of N times, where N is an integer from the range 3 to 6 inclusive.\n* Create a function '''unbiased''' that uses only randN as its source of randomness to become an unbiased generator of random ones and zeroes.\n* For N over its range, generate and show counts of the outputs of randN and unbiased(randN).\n\n\nThe actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN.\n\nThis task is an implementation of Von Neumann debiasing, first described in a 1951 paper.\n\n", "solution": "// version 1.1.2\n\nfun biased(n: Int) = Math.random() < 1.0 / n\n\nfun unbiased(n: Int): Boolean {\n var a: Boolean\n var b: Boolean\n do {\n a = biased(n) \n b = biased(n)\n }\n while (a == b)\n return a\n}\n\nfun main(args: Array) {\n val m = 50_000\n val f = \"%d: %2.2f%% %2.2f%%\"\n for (n in 3..6) {\n var c1 = 0\n var c2 = 0 \n for (i in 0 until m) {\n if (biased(n)) c1++\n if (unbiased(n)) c2++\n }\n println(f.format(n, 100.0 * c1 / m, 100.0 * c2 / m))\n }\n}"} {"title": "Unicode strings", "language": "Kotlin", "task": "As the world gets smaller each day, internationalization becomes more and more important. For handling multiple languages, [[Unicode]] is your best friend. \n\nIt is a very capable tool, but also quite complex compared to older single- and double-byte character encodings. \n\nHow well prepared is your programming language for Unicode? \n\n\n;Task:\nDiscuss and demonstrate its unicode awareness and capabilities. \n\n\nSome suggested topics:\n:* How easy is it to present Unicode strings in source code? \n:* Can Unicode literals be written directly, or be part of identifiers/keywords/etc?\n:* How well can the language communicate with the rest of the world? \n:* Is it good at input/output with Unicode?\n:* Is it convenient to manipulate Unicode strings in the language?\n:* How broad/deep does the language support Unicode? \n:* What encodings (e.g. UTF-8, UTF-16, etc) can be used? \n:* Does it support normalization?\n\n\n;Note:\nThis task is a bit unusual in that it encourages general discussion rather than clever coding.\n\n\n;See also:\n* [[Unicode variable names]]\n* [[Terminal control/Display an extended character]]\n\n", "solution": "// version 1.1.2\n\nfun main(args: Array) {\n val \u00e5\u00e4\u00f6 = \"as\u20dddf\u0305 \u2665\u2666\u2663\u2660 \u9830\"\n println(\u00e5\u00e4\u00f6)\n}"} {"title": "Universal Turing machine", "language": "Kotlin from C", "task": "One of the foundational mathematical constructs behind computer science \nis the universal Turing Machine. \n\n\n(Alan Turing introduced the idea of such a machine in 1936-1937.)\n\nIndeed one way to definitively prove that a language \nis turing-complete \nis to implement a universal Turing machine in it.\n\n\n;Task:\nSimulate such a machine capable \nof taking the definition of any other Turing machine and executing it. \n \nOf course, you will not have an infinite tape, \nbut you should emulate this as much as is possible. \n\nThe three permissible actions on the tape are \"left\", \"right\" and \"stay\".\n\nTo test your universal Turing machine (and prove your programming language \nis Turing complete!), you should execute the following two Turing machines \nbased on the following definitions.\n\n\n'''Simple incrementer'''\n* '''States:''' q0, qf\n* '''Initial state:''' q0\n* '''Terminating states:''' qf\n* '''Permissible symbols:''' B, 1\n* '''Blank symbol:''' B\n* '''Rules:'''\n** (q0, 1, 1, right, q0)\n** (q0, B, 1, stay, qf)\n\n\nThe input for this machine should be a tape of 1 1 1\n\n\n'''Three-state busy beaver'''\n* '''States:''' a, b, c, halt\n* '''Initial state:''' a\n* '''Terminating states:''' halt\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (a, 0, 1, right, b)\n** (a, 1, 1, left, c)\n** (b, 0, 1, left, a)\n** (b, 1, 1, right, b)\n** (c, 0, 1, left, b)\n** (c, 1, 1, stay, halt)\n\n\nThe input for this machine should be an empty tape.\n\n\n'''Bonus:'''\n\n'''5-state, 2-symbol probable Busy Beaver machine from Wikipedia'''\n* '''States:''' A, B, C, D, E, H\n* '''Initial state:''' A\n* '''Terminating states:''' H\n* '''Permissible symbols:''' 0, 1\n* '''Blank symbol:''' 0\n* '''Rules:'''\n** (A, 0, 1, right, B)\n** (A, 1, 1, left, C)\n** (B, 0, 1, right, C)\n** (B, 1, 1, right, B)\n** (C, 0, 1, right, D)\n** (C, 1, 0, left, E)\n** (D, 0, 1, left, A)\n** (D, 1, 1, left, D)\n** (E, 0, 1, stay, H)\n** (E, 1, 0, left, A)\n\n\nThe input for this machine should be an empty tape.\n\nThis machine runs for more than 47 millions steps.\n\n", "solution": "// version 1.2.10\n\nenum class Dir { LEFT, RIGHT, STAY }\n\nclass Rule(\n val state1: String,\n val symbol1: Char,\n val symbol2: Char,\n val dir: Dir,\n val state2: String\n)\n\nclass Tape(\n var symbol: Char,\n var left: Tape? = null,\n var right: Tape? = null\n)\n\nclass Turing(\n val states: List,\n val finalStates: List,\n val symbols: CharArray,\n val blank: Char,\n var state: String,\n tapeInput: CharArray,\n rules: List\n) {\n var tape: Tape? = null\n val transitions = Array(states.size) { arrayOfNulls(symbols.size) }\n\n init {\n for (i in 0 until tapeInput.size) {\n move(Dir.RIGHT)\n tape!!.symbol = tapeInput[i]\n }\n if (tapeInput.size == 0) move(Dir.RIGHT)\n while (tape!!.left != null) tape = tape!!.left\n for (i in 0 until rules.size) {\n val rule = rules[i]\n transitions[stateIndex(rule.state1)][symbolIndex(rule.symbol1)] = rule\n } \n }\n\n private fun stateIndex(state: String): Int {\n val i = states.indexOf(state)\n return if (i >= 0) i else 0\n }\n\n private fun symbolIndex(symbol: Char): Int {\n val i = symbols.indexOf(symbol)\n return if (i >= 0) i else 0\n }\n\n private fun move(dir: Dir) {\n val orig = tape\n when (dir) {\n Dir.RIGHT -> {\n if (orig != null && orig.right != null) {\n tape = orig.right\n }\n else {\n tape = Tape(blank)\n if (orig != null) {\n tape!!.left = orig\n orig.right = tape\n }\n }\n }\n\n Dir.LEFT -> {\n if (orig != null && orig.left != null) {\n tape = orig.left\n }\n else {\n tape = Tape(blank)\n if (orig != null) {\n tape!!.right = orig\n orig.left = tape\n }\n }\n }\n\n Dir.STAY -> {}\n }\n }\n\n fun printState() {\n print(\"%-10s \".format(state))\n var t = tape\n while (t!!.left != null ) t = t.left\n while (t != null) {\n if (t == tape) print(\"[${t.symbol}]\")\n else print(\" ${t.symbol} \")\n t = t.right\n }\n println()\n }\n\n fun run(maxLines: Int = 20) {\n var lines = 0\n while (true) {\n printState()\n for (finalState in finalStates) {\n if (finalState == state) return\n }\n if (++lines == maxLines) {\n println(\"(Only the first $maxLines lines displayed)\")\n return\n }\n val rule = transitions[stateIndex(state)][symbolIndex(tape!!.symbol)]\n tape!!.symbol = rule!!.symbol2\n move(rule.dir)\n state = rule.state2\n }\n }\n}\n\nfun main(args: Array) {\n println(\"Simple incrementer\")\n Turing(\n states = listOf(\"q0\", \"qf\"),\n finalStates = listOf(\"qf\"),\n symbols = charArrayOf('B', '1'),\n blank = 'B',\n state = \"q0\",\n tapeInput = charArrayOf('1', '1', '1'),\n rules = listOf(\n Rule(\"q0\", '1', '1', Dir.RIGHT, \"q0\"),\n Rule(\"q0\", 'B', '1', Dir.STAY, \"qf\")\n )\n ).run()\n\n println(\"\\nThree-state busy beaver\")\n Turing(\n states = listOf(\"a\", \"b\", \"c\", \"halt\"),\n finalStates = listOf(\"halt\"),\n symbols = charArrayOf('0', '1'),\n blank = '0',\n state = \"a\",\n tapeInput = charArrayOf(),\n rules = listOf(\n Rule(\"a\", '0', '1', Dir.RIGHT, \"b\"),\n Rule(\"a\", '1', '1', Dir.LEFT, \"c\"),\n Rule(\"b\", '0', '1', Dir.LEFT, \"a\"),\n Rule(\"b\", '1', '1', Dir.RIGHT, \"b\"),\n Rule(\"c\", '0', '1', Dir.LEFT, \"b\"),\n Rule(\"c\", '1', '1', Dir.STAY, \"halt\")\n )\n ).run()\n\n println(\"\\nFive-state two-symbol probable busy beaver\")\n Turing(\n states = listOf(\"A\", \"B\", \"C\", \"D\", \"E\", \"H\"),\n finalStates = listOf(\"H\"),\n symbols = charArrayOf('0', '1'),\n blank = '0',\n state = \"A\",\n tapeInput = charArrayOf(),\n rules = listOf(\n Rule(\"A\", '0', '1', Dir.RIGHT, \"B\"),\n Rule(\"A\", '1', '1', Dir.LEFT, \"C\"),\n Rule(\"B\", '0', '1', Dir.RIGHT, \"C\"),\n Rule(\"B\", '1', '1', Dir.RIGHT, \"B\"),\n Rule(\"C\", '0', '1', Dir.RIGHT, \"D\"),\n Rule(\"C\", '1', '0', Dir.LEFT, \"E\"),\n Rule(\"D\", '0', '1', Dir.LEFT, \"A\"),\n Rule(\"D\", '1', '1', Dir.LEFT, \"D\"),\n Rule(\"E\", '0', '1', Dir.STAY, \"H\"),\n Rule(\"E\", '1', '0', Dir.LEFT, \"A\")\n )\n ).run()\n}"} {"title": "Unix/ls", "language": "Kotlin", "task": "Write a program that will list everything in the current folder, similar to:\n:::* the Unix utility \"ls\" [http://man7.org/linux/man-pages/man1/ls.1.html] or \n:::* the Windows terminal command \"DIR\" \n\n\nThe output must be sorted, but printing extended details and producing multi-column output is not required.\n\n\n;Example output\nFor the list of paths:\n\n/foo/bar\n/foo/bar/1\n/foo/bar/2\n/foo/bar/a\n/foo/bar/b\n\n\n\nWhen the program is executed in `/foo`, it should print:\n\nbar\n\nand when the program is executed in `/foo/bar`, it should print:\n\n1\n2\na\nb\n\n\n", "solution": "// Version 1.2.41\n\nimport java.io.File\n\nfun ls(directory: String) {\n val d = File(directory)\n if (!d.isDirectory) {\n println(\"$directory is not a directory\")\n return\n }\n d.listFiles().map { it.name }\n .sortedBy { it.toLowerCase() } // case insensitive\n .forEach { println(it) }\n}\n\nfun main(args: Array) {\n ls(\".\") // list files in current directory, say\n}"} {"title": "Validate International Securities Identification Number", "language": "Kotlin", "task": "An International Securities Identification Number (ISIN) is a unique international identifier for a financial security such as a stock or bond. \n\n\n;Task:\nWrite a function or program that takes a string as input, and checks whether it is a valid ISIN.\n\nIt is only valid if it has the correct format, ''and'' the embedded checksum is correct.\n\nDemonstrate that your code passes the test-cases listed below.\n\n\n;Details:\nThe format of an ISIN is as follows:\n\n\n\n+------------- a 2-character ISO country code (A-Z)\n| +----------- a 9-character security code (A-Z, 0-9)\n| | +-- a checksum digit (0-9)\nAU0000XVGZA3\n\n\n\n\nFor this task, you may assume that any 2-character alphabetic sequence is a valid country code.\n\nThe checksum can be validated as follows:\n# '''Replace letters with digits''', by converting each character from base 36 to base 10, e.g. AU0000XVGZA3 -1030000033311635103.\n# '''Perform the Luhn test on this base-10 number.'''There is a separate task for this test: ''[[Luhn test of credit card numbers]]''.You don't have to replicate the implementation of this test here --- you can just call the existing function from that task. (Add a comment stating if you did this.)\n\n\n;Test cases:\n:::: {| class=\"wikitable\"\n! ISIN\n! Validity\n! Comment\n|-\n| US0378331005 || valid || \n|-\n| US0373831005 || not valid || The transposition typo is caught by the checksum constraint.\n|-\n| U50378331005 || not valid || The substitution typo is caught by the format constraint.\n|-\n| US03378331005 || not valid || The duplication typo is caught by the format constraint.\n|-\n| AU0000XVGZA3 || valid || \n|-\n| AU0000VXGZA3 || valid || Unfortunately, not ''all'' transposition typos are caught by the checksum constraint.\n|-\n| FR0000988040 || valid || \n|}\n\n(The comments are just informational. Your function should simply return a Boolean result. See [[#Raku]] for a reference solution.)\n\n\nRelated task:\n* [[Luhn test of credit card numbers]]\n\n\n;Also see:\n* Interactive online ISIN validator\n* Wikipedia article: International Securities Identification Number\n\n", "solution": "// version 1.1\n\nobject Isin {\n val r = Regex(\"^[A-Z]{2}[A-Z0-9]{9}[0-9]$\")\n\n fun isValid(s: String): Boolean {\n // check format\n if (!s.matches(r)) return false\n // validate checksum\n val sb = StringBuilder()\n for (c in s) {\n when (c) {\n in '0'..'9' -> sb.append(c)\n in 'A'..'Z' -> sb.append((c.toInt() - 55).toString().padStart(2, '0'))\n }\n }\n return luhn(sb.toString())\n }\n\n private fun luhn(s: String): Boolean {\n fun sumDigits(n: Int) = n / 10 + n % 10\n val t = s.reversed()\n val s1 = t.filterIndexed { i, _ -> i % 2 == 0 }.sumBy { it - '0' }\n val s2 = t.filterIndexed { i, _ -> i % 2 == 1 }.map { sumDigits((it - '0') * 2) }.sum()\n return (s1 + s2) % 10 == 0\n }\n}\n\nfun main(args: Array) {\n val isins = arrayOf(\n \"US0378331005\", \"US0373831005\", \"U50378331005\", \"US03378331005\",\n \"AU0000XVGZA3\", \"AU0000VXGZA3\", \"FR0000988040\"\n )\n for (isin in isins) {\n println(\"$isin\\t -> ${if (Isin.isValid(isin)) \"valid\" else \"not valid\"}\")\n }\n}"} {"title": "Van Eck sequence", "language": "Kotlin from Java", "task": "The sequence is generated by following this pseudo-code:\n\nA: The first term is zero.\n Repeatedly apply:\n If the last term is *new* to the sequence so far then:\nB: The next term is zero.\n Otherwise:\nC: The next term is how far back this last term occured previously.\n\n\n\n;Example:\nUsing A:\n:0\nUsing B:\n:0 0\nUsing C:\n:0 0 1\nUsing B:\n:0 0 1 0\nUsing C: (zero last occurred two steps back - before the one)\n:0 0 1 0 2\nUsing B:\n:0 0 1 0 2 0\nUsing C: (two last occurred two steps back - before the zero)\n:0 0 1 0 2 0 2 2\nUsing C: (two last occurred one step back)\n:0 0 1 0 2 0 2 2 1\nUsing C: (one last appeared six steps back)\n:0 0 1 0 2 0 2 2 1 6\n...\n\n\n;Task:\n# Create a function/procedure/method/subroutine/... to generate the Van Eck sequence of numbers.\n# Use it to display here, on this page:\n:# The first ten terms of the sequence.\n:# Terms 991 - to - 1000 of the sequence.\n\n\n;References:\n* Don't Know (the Van Eck Sequence) - Numberphile video.\n* Wikipedia Article: Van Eck's Sequence.\n* OEIS sequence: A181391.\n\n", "solution": "fun main() {\n println(\"First 10 terms of Van Eck's sequence:\")\n vanEck(1, 10)\n println(\"\")\n println(\"Terms 991 to 1000 of Van Eck's sequence:\")\n vanEck(991, 1000)\n}\n\nprivate fun vanEck(firstIndex: Int, lastIndex: Int) {\n val vanEckMap = mutableMapOf()\n var last = 0\n if (firstIndex == 1) {\n println(\"VanEck[1] = 0\")\n }\n for (n in 2..lastIndex) {\n val vanEck = if (vanEckMap.containsKey(last)) n - vanEckMap[last]!! else 0\n vanEckMap[last] = n\n last = vanEck\n if (n >= firstIndex) {\n println(\"VanEck[$n] = $vanEck\")\n }\n }\n}"} {"title": "Van der Corput sequence", "language": "Kotlin from C", "task": "When counting integers in binary, if you put a (binary) point to the right of the count then the column immediately to the left denotes a digit with a multiplier of 2^0; the digit in the next column to the left has a multiplier of 2^1; and so on.\n\nSo in the following table:\n 0.\n 1.\n 10.\n 11.\n ...\nthe binary number \"10\" is 1 \\times 2^1 + 0 \\times 2^0.\n\nYou can also have binary digits to the right of the \"point\", just as in the decimal number system. In that case, the digit in the place immediately to the right of the point has a weight of 2^{-1}, or 1/2. \nThe weight for the second column to the right of the point is 2^{-2} or 1/4. And so on.\n\nIf you take the integer binary count of the first table, and ''reflect'' the digits about the binary point, you end up with '''the van der Corput sequence of numbers in base 2'''.\n\n .0\n .1\n .01\n .11\n ...\n\nThe third member of the sequence, binary 0.01, is therefore 0 \\times 2^{-1} + 1 \\times 2^{-2} or 1/4.\n\n Monte Carlo simulations. \nThis sequence is also a superset of the numbers representable by the \"fraction\" field of an old IEEE floating point standard. In that standard, the \"fraction\" field represented the fractional part of a binary number beginning with \"1.\" e.g. 1.101001101.\n\n'''Hint'''\n\nA ''hint'' at a way to generate members of the sequence is to modify a routine used to change the base of an integer:\n>>> def base10change(n, base):\n\tdigits = []\n\twhile n:\n\t\tn,remainder = divmod(n, base)\n\t\tdigits.insert(0, remainder)\n\treturn digits\n\n>>> base10change(11, 2)\n[1, 0, 1, 1]\nthe above showing that 11 in decimal is 1\\times 2^3 + 0\\times 2^2 + 1\\times 2^1 + 1\\times 2^0.\nReflected this would become .1101 or 1\\times 2^{-1} + 1\\times 2^{-2} + 0\\times 2^{-3} + 1\\times 2^{-4}\n\n\n;Task description:\n* Create a function/method/routine that given ''n'', generates the ''n'''th term of the van der Corput sequence in base 2.\n* Use the function to compute ''and display'' the first ten members of the sequence. (The first member of the sequence is for ''n''=0).\n\n* As a stretch goal/extra credit, compute and show members of the sequence for bases other than 2.\n\n\n\n;See also:\n* The Basic Low Discrepancy Sequences\n* [[Non-decimal radices/Convert]]\n* Van der Corput sequence\n\n", "solution": "// version 1.1.2\n\ndata class Rational(val num: Int, val denom: Int)\n\nfun vdc(n: Int, base: Int): Rational {\n var p = 0\n var q = 1\n var nn = n\n while (nn != 0) {\n p = p * base + nn % base\n q *= base\n nn /= base\n }\n val num = p\n val denom = q\n while (p != 0) {\n nn = p\n p = q % p\n q = nn\n }\n return Rational(num / q, denom / q)\n}\n\nfun main(args: Array) {\n for (b in 2..5) {\n print(\"base $b:\")\n for (i in 0..9) {\n val(num, denom) = vdc(i, b)\n if (num != 0) print(\" $num/$denom\")\n else print(\" 0\")\n }\n println()\n }\n}"} {"title": "Vector products", "language": "Kotlin", "task": "A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z). \n\nIf you imagine a graph with the '''x''' and '''y''' axis being at right angles to each other and having a third, '''z''' axis coming out of the page, then a triplet of numbers, (X, Y, Z) would represent a point in the region, and a vector from the origin to the point.\n\nGiven the vectors:\n A = (a1, a2, a3) \n B = (b1, b2, b3) \n C = (c1, c2, c3) \nthen the following common vector products are defined:\n* '''The dot product''' (a scalar quantity)\n:::: A * B = a1b1 + a2b2 + a3b3 \n* '''The cross product''' (a vector quantity)\n:::: A x B = (a2b3 - a3b2, a3b1 - a1b3, a1b2 - a2b1) \n* '''The scalar triple product''' (a scalar quantity)\n:::: A * (B x C) \n* '''The vector triple product''' (a vector quantity)\n:::: A x (B x C) \n\n\n;Task:\nGiven the three vectors: \n a = ( 3, 4, 5)\n b = ( 4, 3, 5)\n c = (-5, -12, -13)\n# Create a named function/subroutine/method to compute the dot product of two vectors.\n# Create a function to compute the cross product of two vectors.\n# Optionally create a function to compute the scalar triple product of three vectors.\n# Optionally create a function to compute the vector triple product of three vectors.\n# Compute and display: a * b\n# Compute and display: a x b\n# Compute and display: a * (b x c), the scalar triple product.\n# Compute and display: a x (b x c), the vector triple product.\n\n\n;References:\n* A starting page on Wolfram MathWorld is {{Wolfram|Vector|Multiplication}}.\n* Wikipedia dot product. \n* Wikipedia cross product. \n* Wikipedia triple product.\n\n\n;Related tasks:\n* [[Dot product]]\n* [[Quaternion type]]\n\n", "solution": "// version 1.1.2\n\nclass Vector3D(val x: Double, val y: Double, val z: Double) {\n infix fun dot(v: Vector3D) = x * v.x + y * v.y + z * v.z\n\n infix fun cross(v: Vector3D) = \n Vector3D(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x)\n\n fun scalarTriple(v: Vector3D, w: Vector3D) = this dot (v cross w)\n\n fun vectorTriple(v: Vector3D, w: Vector3D) = this cross (v cross w)\n\n override fun toString() = \"($x, $y, $z)\"\n}\n\nfun main(args: Array) {\n val a = Vector3D(3.0, 4.0, 5.0)\n val b = Vector3D(4.0, 3.0, 5.0)\n val c = Vector3D(-5.0, -12.0, -13.0)\n println(\"a = $a\")\n println(\"b = $b\")\n println(\"c = $c\")\n println()\n println(\"a . b = ${a dot b}\")\n println(\"a x b = ${a cross b}\")\n println(\"a . b x c = ${a.scalarTriple(b, c)}\")\n println(\"a x b x c = ${a.vectorTriple(b, c)}\")\n}"} {"title": "Visualize a tree", "language": "Kotlin from C", "task": "A tree structure (i.e. a rooted, connected acyclic graph) is often used in programming. \n\nIt's often helpful to visually examine such a structure. \n\nThere are many ways to represent trees to a reader, such as:\n:::* indented text (a la unix tree command)\n:::* nested HTML tables\n:::* hierarchical GUI widgets\n:::* 2D or 3D images\n:::* etc.\n\n;Task:\nWrite a program to produce a visual representation of some tree. \n\nThe content of the tree doesn't matter, nor does the output format, the only requirement being that the output is human friendly. \n\nMake do with the vague term \"friendly\" the best you can.\n\n", "solution": "// version 1.2.0\n\nimport java.util.Random\n\nclass Stem(var str: String? = null, var next: Stem? = null)\n\nconst val SDOWN = \" |\"\nconst val SLAST = \" `\"\nconst val SNONE = \" \"\n\nval rand = Random()\n\nfun tree(root: Int, head: Stem?) {\n val col = Stem()\n var head2 = head\n var tail = head\n while (tail != null) {\n print(tail.str)\n if (tail.next == null) break\n tail = tail.next\n }\n println(\"--$root\")\n if (root <= 1) return\n if (tail != null && tail.str == SLAST) tail.str = SNONE\n if (tail == null) {\n head2 = col\n tail = head2\n }\n else {\n tail.next = col\n }\n var root2 = root\n while (root2 != 0) { // make a tree by doing something random\n val r = 1 + rand.nextInt(root2)\n root2 -= r\n col.str = if (root2 != 0) SDOWN else SLAST\n tree(r, head2)\n }\n tail.next = null\n}\n\nfun main(args: Array) {\n val n = 8\n tree(n, null)\n}"} {"title": "Vogel's approximation method", "language": "Kotlin from Java", "task": "Vogel's Approximation Method (VAM) is a technique for finding a good initial feasible solution to an allocation problem.\n\nThe powers that be have identified 5 tasks that need to be solved urgently. Being imaginative chaps, they have called them \"A\", \"B\", \"C\", \"D\", and \"E\". They estimate that:\n* A will require 30 hours of work,\n* B will require 20 hours of work,\n* C will require 70 hours of work,\n* D will require 30 hours of work, and\n* E will require 60 hours of work.\n\nThey have identified 4 contractors willing to do the work, called \"W\", \"X\", \"Y\", and \"Z\".\n* W has 50 hours available to commit to working,\n* X has 60 hours available,\n* Y has 50 hours available, and\n* Z has 50 hours available.\nThe cost per hour for each contractor for each task is summarized by the following table:\n\n\n A B C D E\nW 16 16 13 22 17\nX 14 14 13 19 15\nY 19 19 20 23 50\nZ 50 12 50 15 11\n\n\nThe task is to use VAM to allocate contractors to tasks. It scales to large problems, so ideally keep sorts out of the iterative cycle. It works as follows:\n\n:Step 1: Balance the given transportation problem if either (total supply>total demand) or (total supply\n A B C D E W X Y Z\n1 2 2 0 4 4 3 1 0 1 E-Z(50)\n\n\nDetermine the largest difference (D or E above). In the case of ties I shall choose the one with the lowest price (in this case E because the lowest price for D is Z=15, whereas for E it is Z=11). For your choice determine the minimum cost (chosen E above so Z=11 is chosen now). Allocate as much as possible from Z to E (50 in this case limited by Z's supply).\nAdjust the supply and demand accordingly. If demand or supply becomes 0 for a given task or contractor it plays no further part. In this case Z is out of it. If you choose arbitrarily, and chose D see here for the working.\n\nRepeat until all supply and demand is met:\n\n2 2 2 0 3 2 3 1 0 - C-W(50)\n3 5 5 7 4 35 - 1 0 - E-X(10)\n4 5 5 7 4 - - 1 0 - C-X(20)\n5 5 5 - 4 - - 0 0 - A-X(30)\n6 - 19 - 23 - - - 4 - D-Y(30)\n - - - - - - - - - B-Y(20)\n\nFinally calculate the cost of your solution. In the example given it is PS3100:\n\n A B C D E\nW 50\nX 30 20 10\nY 20 30\nZ 50\n\n\nThe optimal solution determined by GLPK is PS3100:\n\n A B C D E\nW 50\nX 10 20 20 10\nY 20 30\nZ 50\n\n\n;Cf.\n* Transportation problem\n\n", "solution": "// version 1.1.3\n\nval supply = intArrayOf(50, 60, 50, 50)\nval demand = intArrayOf(30, 20, 70, 30, 60)\n\nval costs = arrayOf(\n intArrayOf(16, 16, 13, 22, 17),\n intArrayOf(14, 14, 13, 19, 15),\n intArrayOf(19, 19, 20, 23, 50),\n intArrayOf(50, 12, 50, 15, 11)\n)\n\nval nRows = supply.size\nval nCols = demand.size\n\nval rowDone = BooleanArray(nRows)\nval colDone = BooleanArray(nCols)\nval results = Array(nRows) { IntArray(nCols) }\n\nfun nextCell(): IntArray {\n val res1 = maxPenalty(nRows, nCols, true)\n val res2 = maxPenalty(nCols, nRows, false)\n if (res1[3] == res2[3]) \n return if (res1[2] < res2[2]) res1 else res2\n return if (res1[3] > res2[3]) res2 else res1\n}\n \nfun diff(j: Int, len: Int, isRow: Boolean): IntArray {\n var min1 = Int.MAX_VALUE\n var min2 = min1\n var minP = -1\n for (i in 0 until len) {\n val done = if (isRow) colDone[i] else rowDone[i]\n if (done) continue\n val c = if (isRow) costs[j][i] else costs[i][j]\n if (c < min1) {\n min2 = min1\n min1 = c\n minP = i\n }\n else if (c < min2) min2 = c\n }\n return intArrayOf(min2 - min1, min1, minP)\n}\n\nfun maxPenalty(len1: Int, len2: Int, isRow: Boolean): IntArray {\n var md = Int.MIN_VALUE\n var pc = -1\n var pm = -1\n var mc = -1\n for (i in 0 until len1) {\n val done = if (isRow) rowDone[i] else colDone[i]\n if (done) continue\n val res = diff(i, len2, isRow)\n if (res[0] > md) {\n md = res[0] // max diff\n pm = i // pos of max diff\n mc = res[1] // min cost\n pc = res[2] // pos of min cost\n }\n }\n return if (isRow) intArrayOf(pm, pc, mc, md) else\n intArrayOf(pc, pm, mc, md)\n}\n \nfun main(args: Array) {\n var supplyLeft = supply.sum()\n var totalCost = 0\n while (supplyLeft > 0) {\n val cell = nextCell()\n val r = cell[0]\n val c = cell[1]\n val q = minOf(demand[c], supply[r])\n demand[c] -= q\n if (demand[c] == 0) colDone[c] = true\n supply[r] -= q\n if (supply[r] == 0) rowDone[r] = true\n results[r][c] = q\n supplyLeft -= q\n totalCost += q * costs[r][c]\n }\n\n println(\" A B C D E\")\n for ((i, result) in results.withIndex()) {\n print(('W'.toInt() + i).toChar())\n for (item in result) print(\" %2d\".format(item))\n println()\n }\n println(\"\\nTotal Cost = $totalCost\")\n}"} {"title": "Voronoi diagram", "language": "Kotlin from Java", "task": "A Voronoi diagram is a diagram consisting of a number of sites. \n\nEach Voronoi site ''s'' also has a Voronoi cell consisting of all points closest to ''s''.\n\n\n;Task:\nDemonstrate how to generate and display a Voroni diagram. \n\n\nSee algo [[K-means++ clustering]].\n\n", "solution": "// version 1.1.3\n\nimport java.awt.Color\nimport java.awt.Graphics\nimport java.awt.Graphics2D\nimport java.awt.geom.Ellipse2D\nimport java.awt.image.BufferedImage\nimport java.util.Random\nimport javax.swing.JFrame\n\nfun distSq(x1: Int, x2: Int, y1: Int, y2: Int): Int {\n val x = x1 - x2\n val y = y1 - y2\n return x * x + y * y\n}\n\nclass Voronoi(val cells: Int, val size: Int) : JFrame(\"Voronoi Diagram\") {\n val bi: BufferedImage\n\n init { \n setBounds(0, 0, size, size)\n defaultCloseOperation = EXIT_ON_CLOSE\n val r = Random()\n bi = BufferedImage(size, size, BufferedImage.TYPE_INT_RGB)\n val px = IntArray(cells) { r.nextInt(size) }\n val py = IntArray(cells) { r.nextInt(size) }\n val cl = IntArray(cells) { r.nextInt(16777215) }\n for (x in 0 until size) {\n for (y in 0 until size) {\n var n = 0\n for (i in 0 until cells) {\n if (distSq(px[i], x, py[i], y) < distSq(px[n], x, py[n], y)) n = i \n }\n bi.setRGB(x, y, cl[n])\n }\n }\n val g = bi.createGraphics()\n g.color = Color.BLACK\n for (i in 0 until cells) {\n g.fill(Ellipse2D.Double(px[i] - 2.5, py[i] - 2.5, 5.0, 5.0))\n } \n }\n\n override fun paint(g: Graphics) {\n g.drawImage(bi, 0, 0, this)\n }\n}\n\nfun main(args: Array) {\n Voronoi(70, 700).isVisible = true\n}"} {"title": "Water collected between towers", "language": "Kotlin from Python", "task": "In a two-dimensional world, we begin with any bar-chart (or row of close-packed 'towers', each of unit width), and then it rains, \ncompletely filling all convex enclosures in the chart with water. \n\n \n9 ## 9 ## \n8 ## 8 ## \n7 ## ## 7 #### \n6 ## ## ## 6 ###### \n5 ## ## ## #### 5 ########## \n4 ## ## ######## 4 ############ \n3 ###### ######## 3 ############## \n2 ################ ## 2 ##################\n1 #################### 1 ####################\n \n\nIn the example above, a bar chart representing the values [5, 3, 7, 2, 6, 4, 5, 9, 1, 2] has filled, collecting 14 units of water.\n\nWrite a function, in your language, from a given array of heights, to the number of water units that can be held in this way, by a corresponding bar chart.\n\nCalculate the number of water units that could be collected by bar charts representing each of the following seven series:\n\n [[1, 5, 3, 7, 2],\n [5, 3, 7, 2, 6, 4, 5, 9, 1, 2],\n [2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1],\n [5, 5, 5, 5],\n [5, 6, 7, 8],\n [8, 7, 7, 6],\n [6, 7, 10, 7, 6]]\n\n\nSee, also:\n\n* Four Solutions to a Trivial Problem - a Google Tech Talk by Guy Steele\n* Water collected between towers on Stack Overflow, from which the example above is taken)\n* An interesting Haskell solution, using the Tardis monad, by Phil Freeman in a Github gist.\n\n\n\n", "solution": "// version 1.1.2\n\nfun waterCollected(tower: IntArray): Int {\n val n = tower.size\n val highLeft = listOf(0) + (1 until n).map { tower.slice(0 until it).max()!! }\n val highRight = (1 until n).map { tower.slice(it until n).max()!! } + 0\n return (0 until n).map { maxOf(minOf(highLeft[it], highRight[it]) - tower[it], 0) }.sum()\n}\n\nfun main(args: Array) {\n val towers = listOf(\n intArrayOf(1, 5, 3, 7, 2),\n intArrayOf(5, 3, 7, 2, 6, 4, 5, 9, 1, 2),\n intArrayOf(2, 6, 3, 5, 2, 8, 1, 4, 2, 2, 5, 3, 5, 7, 4, 1),\n intArrayOf(5, 5, 5, 5),\n intArrayOf(5, 6, 7, 8),\n intArrayOf(8, 7, 7, 6),\n intArrayOf(6, 7, 10, 7, 6)\n )\n for (tower in towers) { \n println(\"${\"%2d\".format(waterCollected(tower))} from ${tower.contentToString()}\")\n }\n}"} {"title": "Weird numbers", "language": "Kotlin from Go", "task": "In number theory, a perfect either).\n\nIn other words, the sum of the proper divisors of the number (divisors including 1 but not itself) is greater than the number itself (the number is ''abundant''), but no subset of those divisors sums to the number itself (the number is not ''semiperfect'').\n\nFor example:\n\n* '''12''' is ''not'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 3, 4, 6''' sum to '''16''' (which ''is'' > 12),\n** but it ''is'' semiperfect, e.g.: '''6 + 4 + 2 == 12'''.\n* '''70''' ''is'' a weird number.\n** It is abundant; its proper divisors '''1, 2, 5, 7, 10, 14, 35''' sum to '''74''' (which ''is'' > 70),\n** and there is no subset of proper divisors that sum to '''70'''.\n\n\n;Task:\nFind and display, here on this page, the first '''25''' weird numbers.\n\n\n;Related tasks:\n:* Abundant, deficient and perfect number classifications\n:* Proper divisors\n\n\n;See also:\n:* OEIS: A006037 weird numbers\n:* Wikipedia: weird number\n:* MathWorld: weird number\n\n", "solution": "fun divisors(n: Int): List {\n val divs = mutableListOf(1)\n val divs2 = mutableListOf()\n var i = 2\n while (i * i <= n) {\n if (n % i == 0) {\n val j = n / i\n divs.add(i)\n if (i != j) divs2.add(j)\n }\n i++\n }\n divs2.addAll(divs.asReversed())\n return divs2\n}\n\nfun abundant(n: Int, divs: List) = divs.sum() > n\n\nfun semiperfect(n: Int, divs: List): Boolean {\n if (divs.size > 0) {\n val h = divs[0]\n val t = divs.subList(1, divs.size)\n if (n < h) {\n return semiperfect(n, t)\n } else {\n return n == h || semiperfect(n-h, t) || semiperfect(n, t)\n }\n } else {\n return false\n }\n}\n\nfun sieve(limit: Int): BooleanArray {\n // false denotes abundant and not semi-perfect.\n // Only interested in even numbers >= 2\n val w = BooleanArray(limit)\n for (i in 2 until limit step 2) {\n if (w[i]) continue\n val divs = divisors(i)\n if (!abundant(i, divs)) {\n w[i] = true\n } else if (semiperfect(i, divs)) {\n for (j in i until limit step i) w[j] = true\n }\n }\n return w\n}\n\nfun main() {\n val w = sieve(17000)\n var count = 0\n val max = 25\n println(\"The first 25 weird numbers are:\")\n var n = 2\n while (count < max) {\n if (!w[n]) {\n print(\"$n \")\n count++\n }\n n += 2\n }\n println()\n}\n\n"} {"title": "Word frequency", "language": "Kotlin", "task": "Given a text file and an integer '''n''', print/display the '''n''' most\ncommon words in the file (and the number of their occurrences) in decreasing frequency.\n\n\nFor the purposes of this task:\n* A word is a sequence of one or more contiguous letters.\n* You are free to define what a ''letter'' is. \n* Underscores, accented letters, apostrophes, hyphens, and other special characters can be handled at your discretion.\n* You may treat a compound word like '''well-dressed''' as either one word or two. \n* The word '''it's''' could also be one or two words as you see fit. \n* You may also choose not to support non US-ASCII characters. \n* Assume words will not span multiple lines.\n* Don't worry about normalization of word spelling differences. \n* Treat '''color''' and '''colour''' as two distinct words.\n* Uppercase letters are considered equivalent to their lowercase counterparts.\n* Words of equal frequency can be listed in any order.\n* Feel free to explicitly state the thoughts behind the program decisions.\n\n\nShow example output using Les Miserables from Project Gutenberg as the text file input and display the top '''10''' most used words.\n\n\n;History:\nThis task was originally taken from programming pearls from Communications of the ACM June 1986 Volume 29 Number 6\nwhere this problem is solved by Donald Knuth using literate programming and then critiqued by Doug McIlroy,\ndemonstrating solving the problem in a 6 line Unix shell script (provided as an example below).\n\n\n;References:\n*McIlroy's program\n\n\n\n\n", "solution": "// version 1.1.3\n\nimport java.io.File\n\nfun main(args: Array) {\n val text = File(\"135-0.txt\").readText().toLowerCase()\n val r = Regex(\"\"\"\\p{javaLowerCase}+\"\"\")\n val matches = r.findAll(text)\n val wordGroups = matches.map { it.value }\n .groupBy { it }\n .map { Pair(it.key, it.value.size) }\n .sortedByDescending { it.second }\n .take(10)\n println(\"Rank Word Frequency\")\n println(\"==== ==== =========\")\n var rank = 1\n for ((word, freq) in wordGroups) \n System.out.printf(\"%2d %-4s %5d\\n\", rank++, word, freq) \n}"} {"title": "Word search", "language": "Kotlin from Java", "task": "A word search puzzle typically consists of a grid of letters in which words are hidden.\n\nThere are many varieties of word search puzzles. For the task at hand we will use a rectangular grid in which the words may be placed horizontally, vertically, or diagonally. The words may also be spelled backwards.\n\nThe words may overlap but are not allowed to zigzag, or wrap around.\n\n;Task \nCreate a 10 by 10 word search and fill it using words from the unixdict. Use only words that are longer than 2, and contain no non-alphabetic characters.\n\nThe cells not used by the hidden words should contain the message: ''Rosetta Code'', read from left to right, top to bottom. These letters should be somewhat evenly distributed over the grid, not clumped together. The message should be in upper case, the hidden words in lower case. All cells should either contain letters from the hidden words or from the message. \n\nPack a minimum of 25 words into the grid.\n\nPrint the resulting grid and the solutions.\n\n;Example\n\n\n 0 1 2 3 4 5 6 7 8 9\n\n0 n a y r y R e l m f \n1 y O r e t s g n a g \n2 t n e d i S k y h E \n3 n o t n c p c w t T \n4 a l s u u n T m a x \n5 r o k p a r i s h h \n6 a A c f p a e a c C \n7 u b u t t t O l u n \n8 g y h w a D h p m u \n9 m i r p E h o g a n \n\nparish (3,5)(8,5) gangster (9,1)(2,1)\npaucity (4,6)(4,0) guaranty (0,8)(0,1)\nprim (3,9)(0,9) huckster (2,8)(2,1)\nplasm (7,8)(7,4) fancy (3,6)(7,2)\nhogan (5,9)(9,9) nolo (1,2)(1,5)\nunder (3,4)(3,0) chatham (8,6)(8,0)\nate (4,8)(6,6) nun (9,7)(9,9)\nbutt (1,7)(4,7) hawk (9,5)(6,2)\nwhy (3,8)(1,8) ryan (3,0)(0,0)\nfay (9,0)(7,2) much (8,8)(8,5)\ntar (5,7)(5,5) elm (6,0)(8,0)\nmax (7,4)(9,4) pup (5,3)(3,5)\nmph (8,8)(6,8)\n\n\n", "solution": "// version 1.2.0\n\nimport java.util.Random\nimport java.io.File\n\nval dirs = listOf(\n intArrayOf( 1, 0), intArrayOf(0, 1), intArrayOf( 1, 1), intArrayOf( 1, -1),\n intArrayOf(-1, 0), intArrayOf(0, -1), intArrayOf(-1, -1), intArrayOf(-1, 1)\n)\n\nval nRows = 10\nval nCols = 10\nval gridSize = nRows * nCols\nval minWords = 25\nval rand = Random()\n\nclass Grid {\n var numAttempts = 0\n val cells = List(nRows) { CharArray(nCols) }\n val solutions = mutableListOf()\n}\n\nfun readWords(fileName: String): List {\n val maxLen = maxOf(nRows, nCols)\n val rx = Regex(\"^[a-z]{3,$maxLen}$\")\n val f = File(fileName)\n return f.readLines().map { it.trim().toLowerCase() }\n .filter { it.matches(rx) }\n}\n\nfun createWordSearch(words: List): Grid {\n var numAttempts = 0\n lateinit var grid: Grid\n outer@ while (++numAttempts < 100) {\n grid = Grid()\n val messageLen = placeMessage(grid, \"Rosetta Code\")\n val target = gridSize - messageLen\n var cellsFilled = 0\n for (word in words.shuffled()) {\n cellsFilled += tryPlaceWord(grid, word)\n if (cellsFilled == target) {\n if (grid.solutions.size >= minWords) {\n grid.numAttempts = numAttempts\n break@outer\n }\n else { // grid is full but we didn't pack enough words, start over\n break\n }\n }\n }\n }\n return grid\n}\n\nfun placeMessage(grid: Grid, msg: String): Int {\n val rx = Regex(\"[^A-Z]\")\n val msg2 = msg.toUpperCase().replace(rx, \"\")\n val messageLen = msg2.length\n if (messageLen in (1 until gridSize)) {\n val gapSize = gridSize / messageLen\n for (i in 0 until messageLen) {\n val pos = i * gapSize + rand.nextInt(gapSize)\n grid.cells[pos / nCols][pos % nCols] = msg2[i]\n }\n return messageLen\n }\n return 0\n}\n\nfun tryPlaceWord(grid: Grid, word: String): Int {\n val randDir = rand.nextInt(dirs.size)\n val randPos = rand.nextInt(gridSize)\n for (d in 0 until dirs.size) {\n val dir = (d + randDir) % dirs.size\n for (p in 0 until gridSize) {\n val pos = (p + randPos) % gridSize\n val lettersPlaced = tryLocation(grid, word, dir, pos)\n if (lettersPlaced > 0) return lettersPlaced\n }\n }\n return 0\n}\n\nfun tryLocation(grid: Grid, word: String, dir: Int, pos: Int): Int {\n val r = pos / nCols\n val c = pos % nCols\n val len = word.length\n\n // check bounds\n if ((dirs[dir][0] == 1 && (len + c) > nCols)\n || (dirs[dir][0] == -1 && (len - 1) > c)\n || (dirs[dir][1] == 1 && (len + r) > nRows)\n || (dirs[dir][1] == -1 && (len - 1) > r)) return 0\n var overlaps = 0\n\n // check cells\n var rr = r\n var cc = c\n for (i in 0 until len) {\n if (grid.cells[rr][cc] != '\\u0000' && grid.cells[rr][cc] != word[i]) return 0\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n\n // place\n rr = r\n cc = c\n for (i in 0 until len) {\n if (grid.cells[rr][cc] == word[i])\n overlaps++\n else\n grid.cells[rr][cc] = word[i]\n\n if (i < len - 1) {\n cc += dirs[dir][0]\n rr += dirs[dir][1]\n }\n }\n\n val lettersPlaced = len - overlaps\n if (lettersPlaced > 0) {\n grid.solutions.add(String.format(\"%-10s (%d,%d)(%d,%d)\", word, c, r, cc, rr))\n }\n return lettersPlaced\n}\n\nfun printResult(grid: Grid) {\n if (grid.numAttempts == 0) {\n println(\"No grid to display\")\n return\n }\n val size = grid.solutions.size\n println(\"Attempts: ${grid.numAttempts}\")\n println(\"Number of words: $size\")\n println(\"\\n 0 1 2 3 4 5 6 7 8 9\")\n for (r in 0 until nRows) {\n print(\"\\n$r \")\n for (c in 0 until nCols) print(\" ${grid.cells[r][c]} \")\n }\n\n println(\"\\n\")\n\n for (i in 0 until size - 1 step 2) {\n println(\"${grid.solutions[i]} ${grid.solutions[i + 1]}\")\n }\n if (size % 2 == 1) println(grid.solutions[size - 1])\n}\n\nfun main(args: Array) {\n printResult(createWordSearch(readWords(\"unixdict.txt\")))\n}"} {"title": "Word wrap", "language": "Kotlin", "task": "Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column. \n\n\n;Basic task:\nThe basic task is to wrap a paragraph of text in a simple way in your language. \n\nIf there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia.\n\nShow your routine working on a sample of text at two different wrap columns.\n\n\n;Extra credit:\nWrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. \nIf your language provides this, you get easy extra credit, \nbut you ''must reference documentation'' indicating that the algorithm \nis something better than a simple minimum length algorithm.\n\nIf you have both basic and extra credit solutions, show an example where \nthe two algorithms give different results.\n\n\n\n", "solution": "// version 1.1.3\n\nval text = \n \"In olden times when wishing still helped one, there lived a king \" +\n \"whose daughters were all beautiful, but the youngest was so beautiful \" +\n \"that the sun itself, which has seen so much, was astonished whenever \" +\n \"it shone in her face. Close by the king's castle lay a great dark \" +\n \"forest, and under an old lime tree in the forest was a well, and when \" +\n \"the day was very warm, the king's child went out into the forest and \" +\n \"sat down by the side of the cool fountain, and when she was bored she \" +\n \"took a golden ball, and threw it up on high and caught it, and this \" +\n \"ball was her favorite plaything.\"\n\nfun greedyWordwrap(text: String, lineWidth: Int): String {\n val words = text.split(' ') \n val sb = StringBuilder(words[0]) \n var spaceLeft = lineWidth - words[0].length\n for (word in words.drop(1)) {\n val len = word.length\n if (len + 1 > spaceLeft) {\n sb.append(\"\\n\").append(word) \n spaceLeft = lineWidth - len\n }\n else {\n sb.append(\" \").append(word)\n spaceLeft -= (len + 1)\n }\n }\n return sb.toString()\n}\n\nfun main(args: Array) {\n println(\"Greedy algorithm - wrapped at 72:\")\n println(greedyWordwrap(text, 72))\n println(\"\\nGreedy algorithm - wrapped at 80:\")\n println(greedyWordwrap(text, 80))\n}"} {"title": "World Cup group stage", "language": "Kotlin from Java", "task": "It's World Cup season (or at least it was when this page was created)! \n\nThe World Cup is an international football/soccer tournament that happens every 4 years. Countries put their international teams together in the years between tournaments and qualify for the tournament based on their performance in other international games. Once a team has qualified they are put into a group with 3 other teams. \n\nFor the first part of the World Cup tournament the teams play in \"group stage\" games where each of the four teams in a group plays all three other teams once. The results of these games determine which teams will move on to the \"knockout stage\" which is a standard single-elimination tournament. The two teams from each group with the most standings points move on to the knockout stage. \n\nEach game can result in a win for one team and a loss for the other team or it can result in a draw/tie for each team. \n:::* A win is worth three points.\n:::* A draw/tie is worth one point. \n:::* A loss is worth zero points.\n\n\n;Task:\n:* Generate all possible outcome combinations for the six group stage games. With three possible outcomes for each game there should be 36 = 729 of them. \n:* Calculate the standings points for each team with each combination of outcomes. \n:* Show a histogram (graphical, ASCII art, or straight counts--whichever is easiest/most fun) of the standings points for all four teams over all possible outcomes.\n\n\nDon't worry about tiebreakers as they can get complicated. We are basically looking to answer the question \"if a team gets x standings points, where can they expect to end up in the group standings?\".\n\n''Hint: there should be no possible way to end up in second place with less than two points as well as no way to end up in first with less than three. Oddly enough, there is no way to get 8 points at all.''\n\n", "solution": "// version 1.1.2\n\nval games = arrayOf(\"12\", \"13\", \"14\", \"23\", \"24\", \"34\")\nvar results = \"000000\"\n\nfun nextResult(): Boolean {\n if (results == \"222222\") return false\n val res = results.toInt(3) + 1\n results = res.toString(3).padStart(6, '0')\n return true\n}\n\nfun main(args: Array) {\n val points = Array(4) { IntArray(10) }\n do {\n val records = IntArray(4)\n for (i in 0..5) {\n when (results[i]) {\n '2' -> records[games[i][0] - '1'] += 3\n '1' -> { records[games[i][0] - '1']++ ; records[games[i][1] - '1']++ }\n '0' -> records[games[i][1] - '1'] += 3\n }\n }\n records.sort()\n for (i in 0..3) points[i][records[i]]++\n }\n while(nextResult())\n println(\"POINTS 0 1 2 3 4 5 6 7 8 9\")\n println(\"-------------------------------------------------------------\") \n val places = arrayOf(\"1st\", \"2nd\", \"3rd\", \"4th\")\n for (i in 0..3) {\n print(\"${places[i]} place \")\n points[3 - i].forEach { print(\"%-5d\".format(it)) }\n println()\n }\n}"} {"title": "Write float arrays to a text file", "language": "Kotlin", "task": "Write two equal-sized numerical arrays 'x' and 'y' to \na two-column text file named 'filename'.\n\nThe first column of the file contains values from an 'x'-array with a \ngiven 'xprecision', the second -- values from 'y'-array with 'yprecision'.\n\nFor example, considering:\n x = {1, 2, 3, 1e11};\n y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}; \n /* sqrt(x) */\n xprecision = 3;\n yprecision = 5;\n\nThe file should look like:\n 1 1\n 2 1.4142\n 3 1.7321\n 1e+011 3.1623e+005\n\nThis task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].\n\n", "solution": "// version 1.1.2\n\nimport java.io.File\n\nfun main(args: Array) {\n val x = doubleArrayOf(1.0, 2.0, 3.0, 1e11)\n val y = doubleArrayOf(1.0, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)\n val xp = 3\n val yp = 5\n val f = \"%.${xp}g\\t%.${yp}g\\n\"\n val writer = File(\"output.txt\").writer()\n writer.use {\n for (i in 0 until x.size) {\n val s = f.format(x[i], y[i])\n writer.write(s)\n }\n }\n}"} {"title": "Write language name in 3D ASCII", "language": "Kotlin from Java", "task": "Write/display a language's name in '''3D''' ASCII. \n\n\n(We can leave the definition of \"3D ASCII\" fuzzy, \nso long as the result is interesting or amusing, \nnot a cheap hack to satisfy the task.)\n\n\n;Related tasks:\n* draw a sphere\n* draw a cuboid\n* draw a rotating cube\n* draw a Deathstar\n\n", "solution": "// version 1.1\n\nclass Ascii3D(s: String) {\n val z = charArrayOf(' ', ' ', '_', '/')\n\n val f = arrayOf(\n longArrayOf(87381, 87381, 87381, 87381, 87381, 87381, 87381),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(742741, 768853, 742837, 742837, 768853, 349525, 349525),\n longArrayOf(349525, 375733, 742741, 742741, 375733, 349525, 349525),\n longArrayOf(349621, 375733, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(349525, 375637, 768949, 742741, 375733, 349525, 349525),\n longArrayOf(351157, 374101, 768949, 374101, 374101, 349525, 349525),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 351157),\n longArrayOf(742741, 768853, 742837, 742837, 742837, 349525, 349525),\n longArrayOf(181, 85, 181, 181, 181, 85, 85),\n longArrayOf(1461, 1365, 1461, 1461, 1461, 1461, 2901),\n longArrayOf(742741, 744277, 767317, 744277, 742837, 349525, 349525),\n longArrayOf(181, 181, 181, 181, 181, 85, 85),\n longArrayOf(1431655765, 3149249365L, 3042661813L, 3042661813L, 3042661813L, 1431655765, 1431655765),\n longArrayOf(349525, 768853, 742837, 742837, 742837, 349525, 349525),\n longArrayOf(349525, 375637, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(349525, 768853, 742837, 742837, 768853, 742741, 742741),\n longArrayOf(349525, 375733, 742837, 742837, 375733, 349621, 349621),\n longArrayOf(349525, 744373, 767317, 742741, 742741, 349525, 349525),\n longArrayOf(349525, 375733, 767317, 351157, 768853, 349525, 349525),\n longArrayOf(374101, 768949, 374101, 374101, 351157, 349525, 349525),\n longArrayOf(349525, 742837, 742837, 742837, 375733, 349525, 349525),\n longArrayOf(5592405, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405),\n longArrayOf(366503875925L, 778827027893L, 778827027893L, 392374737749L, 368114513237L, 366503875925L, 366503875925L),\n longArrayOf(349525, 742837, 375637, 742837, 742837, 349525, 349525),\n longArrayOf(349525, 742837, 742837, 742837, 375733, 349621, 375637),\n longArrayOf(349525, 768949, 351061, 374101, 768949, 349525, 349525),\n longArrayOf(375637, 742837, 768949, 742837, 742837, 349525, 349525),\n longArrayOf(768853, 742837, 768853, 742837, 768853, 349525, 349525),\n longArrayOf(375733, 742741, 742741, 742741, 375733, 349525, 349525),\n longArrayOf(192213, 185709, 185709, 185709, 192213, 87381, 87381),\n longArrayOf(1817525, 1791317, 1817429, 1791317, 1817525, 1398101, 1398101),\n longArrayOf(768949, 742741, 768853, 742741, 742741, 349525, 349525),\n longArrayOf(375733, 742741, 744373, 742837, 375733, 349525, 349525),\n longArrayOf(742837, 742837, 768949, 742837, 742837, 349525, 349525),\n longArrayOf(48053, 23381, 23381, 23381, 48053, 21845, 21845),\n longArrayOf(349621, 349621, 349621, 742837, 375637, 349525, 349525),\n longArrayOf(742837, 744277, 767317, 744277, 742837, 349525, 349525),\n longArrayOf(742741, 742741, 742741, 742741, 768949, 349525, 349525),\n longArrayOf(11883957, 12278709, 11908533, 11883957, 11883957, 5592405, 5592405),\n longArrayOf(11883957, 12277173, 11908533, 11885493, 11883957, 5592405, 5592405),\n longArrayOf(375637, 742837, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(768853, 742837, 768853, 742741, 742741, 349525, 349525),\n longArrayOf(6010197, 11885397, 11909973, 11885397, 6010293, 5592405, 5592405),\n longArrayOf(768853, 742837, 768853, 742837, 742837, 349525, 349525),\n longArrayOf(375733, 742741, 375637, 349621, 768853, 349525, 349525),\n longArrayOf(12303285, 5616981, 5616981, 5616981, 5616981, 5592405, 5592405),\n longArrayOf(742837, 742837, 742837, 742837, 375637, 349525, 349525),\n longArrayOf(11883957, 11883957, 11883957, 5987157, 5616981, 5592405, 5592405),\n longArrayOf(3042268597L, 3042268597L, 3042661813L, 1532713813, 1437971797, 1431655765, 1431655765),\n longArrayOf(11883957, 5987157, 5616981, 5987157, 11883957, 5592405, 5592405),\n longArrayOf(11883957, 5987157, 5616981, 5616981, 5616981, 5592405, 5592405),\n longArrayOf(12303285, 5593941, 5616981, 5985621, 12303285, 5592405, 5592405)\n )\n\n init {\n val o = Array(7) { StringBuilder() }\n for (i in 0 until s.length) {\n var c = s[i].toInt()\n if (c in 65..90) {\n c -= 39\n } else if (c in 97..122) {\n c -= 97\n } else {\n c = -1\n }\n val d = f[++c]\n for (j in 0 until 7) {\n val b = StringBuilder()\n var v = d[j]\n while (v > 0) {\n b.append(z[(v and 3).toInt()])\n v = v shr 2\n }\n o[j].append(b.reverse().toString())\n }\n }\n for (i in 0 until 7) {\n for (j in 0 until 7 - i) print(' ')\n println(o[i])\n }\n }\n}\n\nfun main(args: Array) {\n Ascii3D(\"KOTLIN\")\n Ascii3D(\"with thanks\")\n Ascii3D(\"to the author\")\n Ascii3D(\"of the\")\n Ascii3D(\"Java entry\")\n}"} {"title": "Write to Windows event log", "language": "Kotlin", "task": "Write script status to the Windows Event Log\n\n", "solution": "// version 1.1.4-3\n\nfun main(args: Array) {\n val command = \"EventCreate\" +\n \" /t INFORMATION\" +\n \" /id 123\" +\n \" /l APPLICATION\" +\n \" /so Kotlin\" +\n \" /d \\\"Rosetta Code Example\\\"\"\n\n Runtime.getRuntime().exec(command)\n}"} {"title": "Yellowstone sequence", "language": "Kotlin from Java", "task": "The '''Yellowstone sequence''', also called the '''Yellowstone permutation''', is defined as:\n\nFor n <= 3,\n\n a(n) = n\n\nFor n >= 4,\n\n a(n) = the smallest number not already in sequence such that a(n) is relatively prime to a(n-1) and \n is not relatively prime to a(n-2).\n\n\nThe sequence is a permutation of the natural numbers, and gets its name from what its authors felt was a spiking, geyser like appearance of a plot of the sequence.\n\n\n;Example:\na(4) is 4 because 4 is the smallest number following 1, 2, 3 in the sequence that is relatively prime to the entry before it (3), and is not relatively prime to the number two entries before it (2).\n\n\n;Task\n: Find and show as output the first '''30''' Yellowstone numbers.\n\n\n;Extra\n: Demonstrate how to plot, with x = n and y coordinate a(n), the first 100 Yellowstone numbers.\n\n\n;Related tasks:\n:* Greatest common divisor.\n:* Plot coordinate pairs.\n\n\n;See also:\n:* The OEIS entry: A098550 The Yellowstone permutation.\n:* Applegate et al, 2015: The Yellowstone Permutation [https://arxiv.org/abs/1501.01669].\n\n", "solution": "fun main() {\n println(\"First 30 values in the yellowstone sequence:\")\n println(yellowstoneSequence(30))\n}\n\nprivate fun yellowstoneSequence(sequenceCount: Int): List {\n val yellowstoneList = mutableListOf(1, 2, 3)\n var num = 4\n val notYellowstoneList = mutableListOf()\n var yellowSize = 3\n while (yellowSize < sequenceCount) {\n var found = -1\n for (index in notYellowstoneList.indices) {\n val test = notYellowstoneList[index]\n if (gcd(yellowstoneList[yellowSize - 2], test) > 1 && gcd(\n yellowstoneList[yellowSize - 1], test\n ) == 1\n ) {\n found = index\n break\n }\n }\n if (found >= 0) {\n yellowstoneList.add(notYellowstoneList.removeAt(found))\n yellowSize++\n } else {\n while (true) {\n if (gcd(yellowstoneList[yellowSize - 2], num) > 1 && gcd(\n yellowstoneList[yellowSize - 1], num\n ) == 1\n ) {\n yellowstoneList.add(num)\n yellowSize++\n num++\n break\n }\n notYellowstoneList.add(num)\n num++\n }\n }\n }\n return yellowstoneList\n}\n\nprivate fun gcd(a: Int, b: Int): Int {\n return if (b == 0) {\n a\n } else gcd(b, a % b)\n}"} {"title": "Zeckendorf number representation", "language": "Kotlin", "task": "Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series.\n\nRecall that the first six distinct Fibonacci numbers are: 1, 2, 3, 5, 8, 13. \n\nThe decimal number eleven can be written as 0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1 or 010100 in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes 10100.\n\n10100 is not the only way to make 11 from the Fibonacci numbers however; 0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1 or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that ''no two consecutive Fibonacci numbers can be used'' which leads to the former unique solution.\n\n\n;Task:\nGenerate and show here a table of the Zeckendorf number representations of the decimal numbers zero to twenty, in order. \n\nThe intention in this task to find the Zeckendorf form of an arbitrary integer. The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task. \n\n\n;Also see:\n* OEIS A014417 for the the sequence of required results.\n* Brown's Criterion - Numberphile\n\n\n;Related task:\n* [[Fibonacci sequence]]\n\n", "solution": "// version 1.0.6\n\nconst val LIMIT = 46 // to stay within range of signed 32 bit integer\nval fibs = fibonacci(LIMIT)\n\nfun fibonacci(n: Int): IntArray {\n if (n !in 2..LIMIT) throw IllegalArgumentException(\"n must be between 2 and $LIMIT\")\n val fibs = IntArray(n)\n fibs[0] = 1\n fibs[1] = 1\n for (i in 2 until n) fibs[i] = fibs[i - 1] + fibs[i - 2]\n return fibs\n}\n\nfun zeckendorf(n: Int): String {\n if (n < 0) throw IllegalArgumentException(\"n must be non-negative\")\n if (n < 2) return n.toString()\n var lastFibIndex = 1\n for (i in 2..LIMIT)\n if (fibs[i] > n) {\n lastFibIndex = i - 1\n break\n }\n var nn = n - fibs[lastFibIndex--]\n val zr = StringBuilder(\"1\")\n for (i in lastFibIndex downTo 1)\n if (fibs[i] <= nn) {\n zr.append('1')\n nn -= fibs[i]\n } else {\n zr.append('0')\n }\n return zr.toString()\n}\n\nfun main(args: Array) {\n println(\" n z\")\n for (i in 0..20) println(\"${\"%2d\".format(i)} : ${zeckendorf(i)}\")\n}"} {"title": "Zero to the zero power", "language": "Kotlin", "task": "Some computer programming languages are not exactly consistent (with other computer programming languages) \nwhen ''raising zero to the zeroth power'': 00\n\n\n;Task:\nShow the results of raising zero to the zeroth power.\n\n\nIf your computer language objects to '''0**0''' or '''0^0''' at compile time, you may also try something like:\n x = 0\n y = 0\n z = x**y\n say 'z=' z\n\n\n'''Show the result here.'''\nAnd of course use any symbols or notation that is supported in your computer programming language for exponentiation. \n\n\n;See also:\n* The Wiki entry: Zero to the power of zero. \n* The Wiki entry: Zero to the power of zero: History.\n* The MathWorld(tm) entry: exponent laws.\n** Also, in the above MathWorld(tm) entry, see formula ('''9'''): x^0=1.\n* The OEIS entry: The special case of zero to the zeroth power\n\n", "solution": "import kotlin.math.pow\n\nfun main() {\n println(0.0.pow(0))\n}"} {"title": "Zhang-Suen thinning algorithm", "language": "Kotlin from Java", "task": "This is an algorithm used to thin a black and white i.e. one bit per pixel images. \n\nFor example, with an input image of:\n \n ################# ############# \n ################## ################ \n ################### ################## \n ######## ####### ################### \n ###### ####### ####### ###### \n ###### ####### ####### \n ################# ####### \n ################ ####### \n ################# ####### \n ###### ####### ####### \n ###### ####### ####### \n ###### ####### ####### ###### \n ######## ####### ################### \n ######## ####### ###### ################## ###### \n ######## ####### ###### ################ ###### \n ######## ####### ###### ############# ###### \n \nIt produces the thinned output:\n \n \n # ########## ####### \n ## # #### # \n # # ## \n # # # \n # # # \n # # # \n ############ # \n # # # \n # # # \n # # # \n # # # \n # ## \n # ############ \n ### ### \n \n \n\n;Algorithm:\nAssume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes.\n\nThe algorithm operates on all black pixels P1 that can have eight neighbours. \n\nThe neighbours are, in order, arranged as:\n\n\n P9 P2 P3 \n P8 P1 P4 \n P7 P6 P5 \n\n\n\nObviously the boundary pixels of the image cannot have the full eight neighbours.\n\n* Define A(P1) = the number of transitions from white to black, (0 -> 1) in the sequence P2,P3,P4,P5,P6,P7,P8,P9,P2. (Note the extra P2 at the end - it is circular).\n* Define B(P1) = The number of black pixel neighbours of P1. ( = sum(P2 .. P9) )\n\n\n;Step 1:\nAll pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and P6 is white\n* (4) At least one of P4 and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.\n\n\n;Step 2:\nAll pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.\n* (0) The pixel is black and has eight neighbours\n* (1) 2 <= B(P1) <= 6\n* (2) A(P1) = 1\n* (3) At least one of P2 and P4 and '''P8''' is white\n* (4) At least one of '''P2''' and P6 and P8 is white\n\nAfter iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.\n\n\n;Iteration:\nIf any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.\n\n\n;Task:\n# Write a routine to perform Zhang-Suen thinning on an image matrix of ones and zeroes.\n# Use the routine to thin the following image and show the output here on this page as either a matrix of ones and zeroes, an image, or an ASCII-art image of space/non-space characters. \n\n 00000000000000000000000000000000\n 01111111110000000111111110000000\n 01110001111000001111001111000000\n 01110000111000001110000111000000\n 01110001111000001110000000000000\n 01111111110000001110000000000000\n 01110111100000001110000111000000\n 01110011110011101111001111011100\n 01110001111011100111111110011100\n 00000000000000000000000000000000\n\n\n;Reference:\n* Zhang-Suen Thinning Algorithm, Java Implementation by Nayef Reza.\n* \"Character Recognition Systems: A Guide for Students and Practitioners\" By Mohamed Cheriet, Nawwaf Kharma, Cheng-Lin Liu, Ching Suen\n\n", "solution": "// version 1.1.2\n\nclass Point(val x: Int, val y: Int)\n\nval image = arrayOf(\n \" \",\n \" ################# ############# \",\n \" ################## ################ \",\n \" ################### ################## \",\n \" ######## ####### ################### \",\n \" ###### ####### ####### ###### \",\n \" ###### ####### ####### \",\n \" ################# ####### \",\n \" ################ ####### \",\n \" ################# ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### \",\n \" ###### ####### ####### ###### \",\n \" ######## ####### ################### \",\n \" ######## ####### ###### ################## ###### \",\n \" ######## ####### ###### ################ ###### \",\n \" ######## ####### ###### ############# ###### \",\n \" \" \n)\n\nval nbrs = arrayOf(\n intArrayOf( 0, -1), intArrayOf( 1, -1), intArrayOf( 1, 0), \n intArrayOf( 1, 1), intArrayOf( 0, 1), intArrayOf(-1, 1), \n intArrayOf(-1, 0), intArrayOf(-1, -1), intArrayOf( 0, -1)\n)\n\nval nbrGroups = arrayOf(\n arrayOf(intArrayOf(0, 2, 4), intArrayOf(2, 4, 6)),\n arrayOf(intArrayOf(0, 2, 6), intArrayOf(0, 4, 6))\n)\n\nval toWhite = mutableListOf()\nval grid = Array(image.size) { image[it].toCharArray() }\n\nfun thinImage() {\n var firstStep = false\n var hasChanged: Boolean\n do {\n hasChanged = false\n firstStep = !firstStep\n for (r in 1 until grid.size - 1) {\n for (c in 1 until grid[0].size - 1) {\n if (grid[r][c] != '#') continue\n val nn = numNeighbors(r, c)\n if (nn !in 2..6) continue \n if (numTransitions(r, c) != 1) continue\n val step = if (firstStep) 0 else 1\n if (!atLeastOneIsWhite(r, c, step)) continue\n toWhite.add(Point(c, r))\n hasChanged = true\n }\n }\n for (p in toWhite) grid[p.y][p.x] = ' '\n toWhite.clear()\n }\n while (firstStep || hasChanged)\n for (row in grid) println(row)\n}\n\nfun numNeighbors(r: Int, c: Int): Int {\n var count = 0\n for (i in 0 until nbrs.size - 1) {\n if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == '#') count++\n }\n return count\n}\n\nfun numTransitions(r: Int, c: Int): Int {\n var count = 0\n for (i in 0 until nbrs.size - 1) {\n if (grid[r + nbrs[i][1]][c + nbrs[i][0]] == ' ') {\n if (grid[r + nbrs[i + 1][1]][c + nbrs[i + 1][0]] == '#') count++\n }\n }\n return count\n}\n\nfun atLeastOneIsWhite(r: Int, c: Int, step: Int): Boolean {\n var count = 0;\n val group = nbrGroups[step]\n for (i in 0..1) {\n for (j in 0 until group[i].size) {\n val nbr = nbrs[group[i][j]]\n if (grid[r + nbr[1]][c + nbr[0]] == ' ') {\n count++\n break\n }\n }\n }\n return count > 1\n}\n\nfun main(args: Array) {\n thinImage()\n}"}