title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Non-transitive dice | Kotlin from Go | Let our dice select numbers on their faces with equal probability, i.e. fair dice.
Dice may have more or less than six faces. (The possibility of there being a
3D physical shape that has that many "faces" that allow them to be fair dice,
is ignored for this task - a die with 3 or 33 defined sides is defined by the
number of faces and the numbers on each face).
Throwing dice will randomly select a face on each die with equal probability.
To show which die of dice thrown multiple times is more likely to win over the
others:
# calculate all possible combinations of different faces from each die
# Count how many times each die wins a combination
# Each ''combination'' is equally likely so the die with more winning face combinations is statistically more likely to win against the other dice.
'''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.
'''
;Example 1:
If X is the three sided die with 1, 3, 6 on its faces and Y has 2, 3, 4 on its
faces then the equal possibility outcomes from throwing both, and the winners
is:
X Y Winner
= = ======
1 2 Y
1 3 Y
1 4 Y
3 2 X
3 3 -
3 4 Y
6 2 X
6 3 X
6 4 X
TOTAL WINS: X=4, Y=4
Both die will have the same statistical probability of winning, i.e.their comparison can be written as X = Y
;Transitivity:
In mathematics transitivity are rules like:
if a op b and b op c then a op c
If, for example, the op, (for operator), is the familiar less than, <, and it's applied to integers
we get the familiar if a < b and b < c then a < c
;Non-transitive dice
These are an ordered list of dice where the '>' operation between successive
dice pairs applies but a comparison between the first and last of the list
yields the opposite result, '<'.
''(Similarly '<' successive list comparisons with a final '>' between first and last is also non-transitive).''
Three dice S, T, U with appropriate face values could satisfy
S < T, T < U and yet S > U
To be non-transitive.
;Notes:
* 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).
* A die can have more than one instance of the same number on its faces, e.g. 2, 3, 3, 4
* '''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.
;Task:
;====
Find all the ordered lists of ''three'' non-transitive dice S, T, U of the form
S < T, T < U and yet S > U; where the dice are selected from all ''four-faced die''
, (unique w.r.t the notes), possible by having selections from the integers
''one to four'' on any dies face.
Solution can be found by generating all possble individual die then testing all
possible permutations, (permutations are ordered), of three dice for
non-transitivity.
;Optional stretch goal:
Find lists of '''four''' non-transitive dice selected from the same possible dice from the non-stretch goal.
Show the results here, on this page.
;References:
* The Most Powerful Dice - Numberphile Video.
* Nontransitive dice - Wikipedia.
| fun fourFaceCombos(): List<Array<Int>> {
val res = mutableListOf<Array<Int>>()
val found = mutableSetOf<Int>()
for (i in 1..4) {
for (j in 1..4) {
for (k in 1..4) {
for (l in 1..4) {
val c = arrayOf(i, j, k, l)
c.sort()
val key = 64 * (c[0] - 1) + 16 * (c[1] - 1) + 4 * (c[2] - 1) + (c[3] - 1)
if (!found.contains(key)) {
found.add(key)
res.add(c)
}
}
}
}
}
return res
}
fun cmp(x: Array<Int>, y: Array<Int>): Int {
var xw = 0
var yw = 0
for (i in 0 until 4) {
for (j in 0 until 4) {
if (x[i] > y[j]) {
xw++
} else if (y[j] > x[i]) {
yw++
}
}
}
if (xw < yw) {
return -1
}
if (xw > yw) {
return 1
}
return 0
}
fun findIntransitive3(cs: List<Array<Int>>): List<Array<Array<Int>>> {
val c = cs.size
val res = mutableListOf<Array<Array<Int>>>()
for (i in 0 until c) {
for (j in 0 until c) {
if (cmp(cs[i], cs[j]) == -1) {
for (k in 0 until c) {
if (cmp(cs[j], cs[k]) == -1 && cmp(cs[k], cs[i]) == -1) {
res.add(arrayOf(cs[i], cs[j], cs[k]))
}
}
}
}
}
return res
}
fun findIntransitive4(cs: List<Array<Int>>): List<Array<Array<Int>>> {
val c = cs.size
val res = mutableListOf<Array<Array<Int>>>()
for (i in 0 until c) {
for (j in 0 until c) {
if (cmp(cs[i], cs[j]) == -1) {
for (k in 0 until c) {
if (cmp(cs[j], cs[k]) == -1) {
for (l in 0 until c) {
if (cmp(cs[k], cs[l]) == -1 && cmp(cs[l], cs[i]) == -1) {
res.add(arrayOf(cs[i], cs[j], cs[k], cs[l]))
}
}
}
}
}
}
}
return res
}
fun main() {
val combos = fourFaceCombos()
println("Number of eligible 4-faced dice: ${combos.size}")
println()
val it3 = findIntransitive3(combos)
println("${it3.size} ordered lists of 3 non-transitive dice found, namely:")
for (a in it3) {
println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") })
}
println()
val it4 = findIntransitive4(combos)
println("${it4.size} ordered lists of 4 non-transitive dice found, namely:")
for (a in it4) {
println(a.joinToString(", ", "[", "]") { it.joinToString(", ", "[", "]") })
}
} |
Nonoblock | Kotlin from Java | Nonogram puzzle.
;Given:
* The number of cells in a row.
* The size of each, (space separated), connected block of cells to fit in the row, in left-to right order.
;Task:
* show all possible positions.
* show the number of positions of the blocks for the following cases within the row.
* show all output on this page.
* use a "neat" diagram of the block positions.
;Enumerate the following configurations:
# '''5''' cells and '''[2, 1]''' blocks
# '''5''' cells and '''[]''' blocks (no blocks)
# '''10''' cells and '''[8]''' blocks
# '''15''' cells and '''[2, 3, 2, 3]''' blocks
# '''5''' cells and '''[2, 3]''' blocks (should give some indication of this not being possible)
;Example:
Given 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:
|_|_|_|_|_| # 5 cells and [2, 1] blocks
And would expand to the following 3 possible rows of block positions:
|A|A|_|B|_|
|A|A|_|_|B|
|_|A|A|_|B|
Note how the sets of blocks are always separated by a space.
Note also that it is not necessary for each block to have a separate letter.
Output approximating
This:
|#|#|_|#|_|
|#|#|_|_|#|
|_|#|#|_|#|
This would also work:
##.#.
##..#
.##.#
;An algorithm:
* 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).
* 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.
* 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.
(This is the algorithm used in the [[Nonoblock#Python]] solution).
;Reference:
* The blog post Nonogram puzzle solver (part 1) Inspired this task and donated its [[Nonoblock#Python]] solution.
| // version 1.2.0
fun printBlock(data: String, len: Int) {
val a = data.toCharArray()
val sumChars = a.map { it.toInt() - 48 }.sum()
println("\nblocks ${a.asList()}, cells $len")
if (len - sumChars <= 0) {
println("No solution")
return
}
val prep = a.map { "1".repeat(it.toInt() - 48) }
for (r in genSequence(prep, len - sumChars + 1)) println(r.substring(1))
}
fun genSequence(ones: List<String>, numZeros: Int): List<String> {
if (ones.isEmpty()) return listOf("0".repeat(numZeros))
val result = mutableListOf<String>()
for (x in 1 until numZeros - ones.size + 2) {
val skipOne = ones.drop(1)
for (tail in genSequence(skipOne, numZeros - x)) {
result.add("0".repeat(x) + ones[0] + tail)
}
}
return result
}
fun main(args: Array<String>) {
printBlock("21", 5)
printBlock("", 5)
printBlock("8", 10)
printBlock("2323", 15)
printBlock("23", 5)
} |
Nonogram solver | Kotlin from Java | nonogram is a puzzle that provides
numeric clues used to fill in a grid of cells,
establishing for each cell whether it is filled or not.
The puzzle solution is typically a picture of some kind.
Each row and column of a rectangular grid is annotated with the lengths
of its distinct runs of occupied cells.
Using only these lengths you should find one valid configuration
of empty and occupied cells, or show a failure message.
;Example
Problem: Solution:
. . . . . . . . 3 . # # # . . . . 3
. . . . . . . . 2 1 # # . # . . . . 2 1
. . . . . . . . 3 2 . # # # . . # # 3 2
. . . . . . . . 2 2 . . # # . . # # 2 2
. . . . . . . . 6 . . # # # # # # 6
. . . . . . . . 1 5 # . # # # # # . 1 5
. . . . . . . . 6 # # # # # # . . 6
. . . . . . . . 1 . . . . # . . . 1
. . . . . . . . 2 . . . # # . . . 2
1 3 1 7 5 3 4 3 1 3 1 7 5 3 4 3
2 1 5 1 2 1 5 1
The problem above could be represented by two lists of lists:
x = [[3], [2,1], [3,2], [2,2], [6], [1,5], [6], [1], [2]]
y = [[1,2], [3,1], [1,5], [7,1], [5], [3], [4], [3]]
A more compact representation of the same problem uses strings,
where the letters represent the numbers, A=1, B=2, etc:
x = "C BA CB BB F AE F A B"
y = "AB CA AE GA E C D C"
;Task
For this task, try to solve the 4 problems below, read from a "nonogram_problems.txt" file that has this content
(the blank lines are separators):
C BA CB BB F AE F A B
AB CA AE GA E C D C
F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC
D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA
CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC
BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF AAAAD BDG CEF CBDB BBB FC
E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G
E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM
'''Extra credit''': generate nonograms with unique solutions, of desired height and width.
This 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).
; Related tasks
* [[Nonoblock]].
;See also
* Arc Consistency Algorithm
* http://www.haskell.org/haskellwiki/99_questions/Solutions/98 (Haskell)
* http://twanvl.nl/blog/haskell/Nonograms (Haskell)
* http://picolisp.com/5000/!wiki?99p98 (PicoLisp)
| // version 1.2.0
import java.util.BitSet
typealias BitSets = List<MutableList<BitSet>>
val rx = Regex("""\s""")
fun newPuzzle(data: List<String>) {
val rowData = data[0].split(rx)
val colData = data[1].split(rx)
val rows = getCandidates(rowData, colData.size)
val cols = getCandidates(colData, rowData.size)
do {
val numChanged = reduceMutual(cols, rows)
if (numChanged == -1) {
println("No solution")
return
}
}
while (numChanged > 0)
for (row in rows) {
for (i in 0 until cols.size) {
print(if (row[0][i]) "# " else ". ")
}
println()
}
println()
}
// collect all possible solutions for the given clues
fun getCandidates(data: List<String>, len: Int): BitSets {
val result = mutableListOf<MutableList<BitSet>>()
for (s in data) {
val lst = mutableListOf<BitSet>()
val a = s.toCharArray()
val sumChars = a.sumBy { it - 'A' + 1 }
val prep = a.map { "1".repeat(it - 'A' + 1) }
for (r in genSequence(prep, len - sumChars + 1)) {
val bits = r.substring(1).toCharArray()
val bitset = BitSet(bits.size)
for (i in 0 until bits.size) bitset[i] = bits[i] == '1'
lst.add(bitset)
}
result.add(lst)
}
return result
}
fun genSequence(ones: List<String>, numZeros: Int): List<String> {
if (ones.isEmpty()) return listOf("0".repeat(numZeros))
val result = mutableListOf<String>()
for (x in 1 until numZeros - ones.size + 2) {
val skipOne = ones.drop(1)
for (tail in genSequence(skipOne, numZeros - x)) {
result.add("0".repeat(x) + ones[0] + tail)
}
}
return result
}
/* If all the candidates for a row have a value in common for a certain cell,
then it's the only possible outcome, and all the candidates from the
corresponding column need to have that value for that cell too. The ones
that don't, are removed. The same for all columns. It goes back and forth,
until no more candidates can be removed or a list is empty (failure).
*/
fun reduceMutual(cols: BitSets, rows: BitSets): Int {
val countRemoved1 = reduce(cols, rows)
if (countRemoved1 == -1) return -1
val countRemoved2 = reduce(rows, cols)
if (countRemoved2 == -1) return -1
return countRemoved1 + countRemoved2
}
fun reduce(a: BitSets, b: BitSets): Int {
var countRemoved = 0
for (i in 0 until a.size) {
val commonOn = BitSet()
commonOn[0] = b.size
val commonOff = BitSet()
// determine which values all candidates of a[i] have in common
for (candidate in a[i]) {
commonOn.and(candidate)
commonOff.or(candidate)
}
// remove from b[j] all candidates that don't share the forced values
for (j in 0 until b.size) {
val fi = i
val fj = j
if (b[j].removeIf { cnd ->
(commonOn[fj] && !cnd[fi]) ||
(!commonOff[fj] && cnd[fi]) }) countRemoved++
if (b[j].isEmpty()) return -1
}
}
return countRemoved
}
val p1 = listOf("C BA CB BB F AE F A B", "AB CA AE GA E C D C")
val p2 = listOf(
"F CAC ACAC CN AAA AABB EBB EAA ECCC HCCC",
"D D AE CD AE A DA BBB CC AAB BAA AAB DA AAB AAA BAB AAA CD BBA DA"
)
val p3 = listOf(
"CA BDA ACC BD CCAC CBBAC BBBBB BAABAA ABAD AABB BBH " +
"BBBD ABBAAA CCEA AACAAB BCACC ACBH DCH ADBE ADBB DBE ECE DAA DB CC",
"BC CAC CBAB BDD CDBDE BEBDF ADCDFA DCCFB DBCFC ABDBA BBF AAF BADB DBF " +
"AAAAD BDG CEF CBDB BBB FC"
)
val p4 = listOf(
"E BCB BEA BH BEK AABAF ABAC BAA BFB OD JH BADCF Q Q R AN AAN EI H G",
"E CB BAB AAA AAA AC BB ACC ACCA AGB AIA AJ AJ " +
"ACE AH BAF CAG DAG FAH FJ GJ ADK ABK BL CM"
)
fun main(args: Array<String>) {
for (puzzleData in listOf(p1, p2, p3, p4)) {
newPuzzle(puzzleData)
}
} |
Numeric error propagation | Kotlin from Java | If '''f''', '''a''', and '''b''' are values with uncertainties sf, sa, and sb, and '''c''' is a constant;
then if '''f''' is derived from '''a''', '''b''', and '''c''' in the following ways,
then sf can be calculated as follows:
:;Addition/Subtraction
:* If f = a +- c, or f = c +- a then '''sf = sa'''
:* If f = a +- b then '''sf2 = sa2 + sb2'''
:;Multiplication/Division
:* If f = ca or f = ac then '''sf = |csa|'''
:* If f = ab or f = a / b then '''sf2 = f2( (sa / a)2 + (sb / b)2)'''
:;Exponentiation
:* If f = ac then '''sf = |fc(sa / a)|'''
Caution:
::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.
;Task details:
# 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.
# 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
# Print and display both '''d''' and its error.
;References:
* A Guide to Error Propagation B. Keeney, 2005.
* Propagation of uncertainty Wikipedia.
;Related task:
* [[Quaternion type]]
| import java.lang.Math.*
data class Approx(val ν: Double, val σ: Double = 0.0) {
constructor(a: Approx) : this(a.ν, a.σ)
constructor(n: Number) : this(n.toDouble(), 0.0)
override fun toString() = "$ν ±$σ"
operator infix fun plus(a: Approx) = Approx(ν + a.ν, sqrt(σ * σ + a.σ * a.σ))
operator infix fun plus(d: Double) = Approx(ν + d, σ)
operator infix fun minus(a: Approx) = Approx(ν - a.ν, sqrt(σ * σ + a.σ * a.σ))
operator infix fun minus(d: Double) = Approx(ν - d, σ)
operator infix fun times(a: Approx): Approx {
val v = ν * a.ν
return Approx(v, sqrt(v * v * σ * σ / (ν * ν) + a.σ * a.σ / (a.ν * a.ν)))
}
operator infix fun times(d: Double) = Approx(ν * d, abs(d * σ))
operator infix fun div(a: Approx): Approx {
val v = ν / a.ν
return Approx(v, sqrt(v * v * σ * σ / (ν * ν) + a.σ * a.σ / (a.ν * a.ν)))
}
operator infix fun div(d: Double) = Approx(ν / d, abs(d * σ))
fun pow(d: Double): Approx {
val v = pow(ν, d)
return Approx(v, abs(v * d * σ / ν))
}
}
fun main(args: Array<String>) {
val x1 = Approx(100.0, 1.1)
val y1 = Approx(50.0, 1.2)
val x2 = Approx(200.0, 2.2)
val y2 = Approx(100.0, 2.3)
println(((x1 - x2).pow(2.0) + (y1 - y2).pow(2.0)).pow(0.5))
} |
Odd word problem | Kotlin from C | Write a program that solves the odd word problem with the restrictions given below.
;Description:
You are promised an input stream consisting of English letters and punctuations.
It is guaranteed that:
* the words (sequence of consecutive letters) are delimited by one and only one punctuation,
* the stream will begin with a word,
* the words will be at least one letter long, and
* a full stop (a period, [.]) appears after, and only after, the last word.
;Example:
A stream with six words:
:: what,is,the;meaning,of:life.
The task is to reverse the letters in every other word while leaving punctuations intact, producing:
:: what,si,the;gninaem,of:efil.
while observing the following restrictions:
# 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;
# You '''are not''' to explicitly save characters in a collection data structure, such as arrays, strings, hash tables, etc, for later reversal;
# You '''are''' allowed to use recursions, closures, continuations, threads, co-routines, etc., even if their use implies the storage of multiple characters.
;Test cases:
Work on both the "life" example given above, and also the text:
:: we,are;not,in,kansas;any,more.
| // version 1.1.3
typealias Func = () -> Unit
fun doChar(odd: Boolean, f: Func?): Boolean {
val c = System.`in`.read()
if (c == -1) return false // end of stream reached
val ch = c.toChar()
fun writeOut() {
print(ch)
if (f != null) f()
}
if (!odd) print(ch)
if (ch.isLetter()) return doChar(odd, ::writeOut)
if (odd) {
if (f != null) f()
print(ch)
}
return ch != '.'
}
fun main(args: Array<String>) {
repeat(2) {
var b = true
while (doChar(!b, null)) b = !b
System.`in`.read() // remove '\n' from buffer
println("\n")
}
} |
Old Russian measure of length | Kotlin from FreeBASIC | Write a program to perform a conversion of the old Russian measures of length to the metric system (and vice versa).
It is an example of a linear transformation of several variables.
The program should accept a single value in a selected unit of measurement, and convert and return it to the other units:
''vershoks'', ''arshins'', ''sazhens'', ''versts'', ''meters'', ''centimeters'' and ''kilometers''.
;Also see:
:* Old Russian measure of length
| // version 1.0.6
/* clears console on Windows 10 */
fun cls() = ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor()
fun main(args: Array<String>) {
val units = listOf("tochka", "liniya", "dyuim", "vershok", "piad", "fut",
"arshin", "sazhen", "versta", "milia",
"centimeter", "meter", "kilometer")
val convs = arrayOf(0.0254f, 0.254f, 2.54f, 4.445f, 17.78f, 30.48f,
71.12f, 213.36f, 10668.0f, 74676.0f,
1.0f, 100.0f, 10000.0f)
var unit: Int
var value: Float
var yn : String
do {
cls()
println()
for (i in 0 until units.size) println("${"%2d".format(i + 1)} ${units[i]}")
println()
do {
print("Please choose a unit 1 to 13 : ")
unit = try { readLine()!!.toInt() } catch (e: NumberFormatException) { 0 }
}
while (unit !in 1..13)
unit--
do {
print("Now enter a value in that unit : ")
value = try { readLine()!!.toFloat() } catch (e: NumberFormatException) { -1.0f }
}
while (value < 0.0f)
println("\nThe equivalent in the remaining units is:\n")
for (i in 0 until units.size) {
if (i == unit) continue
println(" ${units[i].padEnd(10)} : ${value * convs[unit] / convs[i]}")
}
println()
do {
print("Do another one y/n : ")
yn = readLine()!!.toLowerCase()
}
while (yn != "y" && yn != "n")
}
while (yn == "y")
} |
Old lady swallowed a fly | Kotlin | 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.
This song has multiple versions with slightly different lyrics, so all these programs might not emit identical output.
| // version 1.1.3
val animals = listOf("fly", "spider", "bird", "cat","dog", "goat", "cow", "horse")
val phrases = listOf(
"",
"That wriggled and jiggled and tickled inside her",
"How absurd to swallow a bird",
"Fancy that to swallow a cat",
"What a hog, to swallow a dog",
"She just opened her throat and swallowed a goat",
"I don't know how she swallowed a cow",
"\n ...She's dead of course"
)
fun sing() {
for (i in 0..7) {
println("There was an old lady who swallowed a ${animals[i]};")
if (i > 0) println("${phrases[i]}!")
if (i == 7) return
println()
if (i > 0) {
for (j in i downTo 1) {
print(" She swallowed the ${animals[j]} to catch the ${animals[j - 1]}")
println(if (j < 3) ";" else ",")
if (j == 2) println(" ${phrases[1]}!")
}
}
println(" I don't know why she swallowed a fly - Perhaps she'll die!\n")
}
}
fun main(args: Array<String>) {
sing()
} |
One-time pad | Kotlin | One-time pad, for encrypting and decrypting messages.
To keep it simple, we will be using letters only.
;Sub-Tasks:
* '''Generate''' the data for a One-time pad (user needs to specify a filename and length)
: The important part is to get "true random" numbers, e.g. from /dev/random
* '''encryption / decryption''' ( basically the same operation, much like [[Rot-13]] )
: For this step, much of [[Vigenere cipher]] could be reused,with the key to be read from the file containing the One-time pad.
* optional: '''management''' of One-time pads: list, mark as used, delete, etc.
: Somehow, the users needs to keep track which pad to use for which partner.
To support the management of pad-files:
* Such files have a file-extension ".1tp"
* Lines starting with "#" may contain arbitary meta-data (i.e. comments)
* Lines starting with "-" count as "used"
* Whitespace within the otp-data is ignored
For example, here is the data from Wikipedia:
# Example data - Wikipedia - 2014-11-13
-ZDXWWW EJKAWO FECIFE WSNZIP PXPKIY URMZHI JZTLBC YLGDYJ
-HTSVTV RRYYEG EXNCGA GGQVRF FHZCIB EWLGGR BZXQDQ DGGIAK
YHJYEQ TDLCQT HZBSIZ IRZDYS RBYJFZ AIRCWI UCVXTW YKPQMK
CKHVEX VXYVCS WOGAAZ OUVVON GCNEVR LMBLYB SBDCDC PCGVJX
QXAUIP PXZQIJ JIUWYH COVWMJ UZOJHL DWHPER UBSRUJ HGAAPR
CRWVHI FRNTQW AJVWRT ACAKRD OZKIIB VIQGBK IJCWHF GTTSSE
EXFIPJ KICASQ IOUQTP ZSGXGH YTYCTI BAZSTN JKMFXI RERYWE
;See also
* one time pad encryption in Python
* snapfractalpop - One-Time-Pad Command-Line-Utility (C).
* Crypt-OTP-2.00 on CPAN (Perl)
| // version 1.2.31
import java.io.File
import java.security.SecureRandom
const val CHARS_PER_LINE = 48
const val CHUNK_SIZE = 6
const val COLS = 8
const val DEMO = true // would normally be set to false
enum class FileType { OTP, ENC, DEC }
fun Char.isAlpha() = this in 'A'..'Z'
fun String.toAlpha() = this.filter { it.isAlpha() }
fun String.isOtpRelated() = endsWith(".1tp") || endsWith(".1tp_cpy") ||
endsWith(".1tp_enc") || endsWith(".1tp_dec")
fun makePad(nLines: Int): String {
val nChars = nLines * CHARS_PER_LINE
val sr = SecureRandom()
val sb = StringBuilder(nChars)
/* generate random upper case letters */
for (i in 0 until nChars) sb.append((sr.nextInt(26) + 65).toChar())
return sb.toString().inChunks(nLines, FileType.OTP)
}
fun vigenere(text: String, key: String, encrypt: Boolean = true): String {
val sb = StringBuilder(text.length)
for ((i, c) in text.withIndex()) {
val ci = if (encrypt)
(c.toInt() + key[i].toInt() - 130) % 26
else
(c.toInt() - key[i].toInt() + 26) % 26
sb.append((ci + 65).toChar())
}
val temp = sb.length % CHARS_PER_LINE
if (temp > 0) { // pad with random characters so each line is a full one
val sr = SecureRandom()
for (i in temp until CHARS_PER_LINE) sb.append((sr.nextInt(26) + 65).toChar())
}
val ft = if (encrypt) FileType.ENC else FileType.DEC
return sb.toString().inChunks(sb.length / CHARS_PER_LINE, ft)
}
fun String.inChunks(nLines: Int, ft: FileType): String {
val chunks = this.chunked(CHUNK_SIZE)
val sb = StringBuilder(this.length + nLines * (COLS + 1))
for (i in 0 until nLines) {
val j = i * COLS
sb.append(" ${chunks.subList(j, j + COLS).joinToString(" ")}\n")
}
val s = " file\n" + sb.toString()
return when (ft) {
FileType.OTP -> "# OTP" + s
FileType.ENC -> "# Encrypted" + s
FileType.DEC -> "# Decrypted" + s
}
}
fun menu(): Int {
println("""
|
|1. Create one time pad file.
|
|2. Delete one time pad file.
|
|3. List one time pad files.
|
|4. Encrypt plain text.
|
|5. Decrypt cipher text.
|
|6. Quit program.
|
""".trimMargin())
var choice: Int?
do {
print("Your choice (1 to 6) : ")
choice = readLine()!!.toIntOrNull()
}
while (choice == null || choice !in 1..6)
return choice
}
fun main(args: Array<String>) {
mainLoop@ while (true) {
val choice = menu()
println()
when (choice) {
1 -> { // Create OTP
println("Note that encrypted lines always contain 48 characters.\n")
print("OTP file name to create (without extension) : ")
val fileName = readLine()!! + ".1tp"
var nLines: Int?
do {
print("Number of lines in OTP (max 1000) : ")
nLines = readLine()!!.toIntOrNull()
}
while (nLines == null || nLines !in 1..1000)
val key = makePad(nLines)
File(fileName).writeText(key)
println("\n'$fileName' has been created in the current directory.")
if (DEMO) {
// a copy of the OTP file would normally be on a different machine
val fileName2 = fileName + "_cpy" // copy for decryption
File(fileName2).writeText(key)
println("'$fileName2' has been created in the current directory.")
println("\nThe contents of these files are :\n")
println(key)
}
}
2 -> { // Delete OTP
println("Note that this will also delete ALL associated files.\n")
print("OTP file name to delete (without extension) : ")
val toDelete1 = readLine()!! + ".1tp"
val toDelete2 = toDelete1 + "_cpy"
val toDelete3 = toDelete1 + "_enc"
val toDelete4 = toDelete1 + "_dec"
val allToDelete = listOf(toDelete1, toDelete2, toDelete3, toDelete4)
var deleted = 0
println()
for (name in allToDelete) {
val f = File(name)
if (f.exists()) {
f.delete()
deleted++
println("'$name' has been deleted from the current directory.")
}
}
if (deleted == 0) println("There are no files to delete.")
}
3 -> { // List OTPs
println("The OTP (and related) files in the current directory are:\n")
val otpFiles = File(".").listFiles().filter {
it.isFile() && it.name.isOtpRelated()
}.map { it.name }.toMutableList()
otpFiles.sort()
println(otpFiles.joinToString("\n"))
}
4 -> { // Encrypt
print("OTP file name to use (without extension) : ")
val keyFile = readLine()!! + ".1tp"
val kf = File(keyFile)
if (kf.exists()) {
val lines = File(keyFile).readLines().toMutableList()
var first = lines.size
for (i in 0 until lines.size) {
if (lines[i].startsWith(" ")) {
first = i
break
}
}
if (first == lines.size) {
println("\nThat file has no unused lines.")
continue@mainLoop
}
val lines2 = lines.drop(first) // get rid of comments and used lines
println("Text to encrypt :-\n")
val text = readLine()!!.toUpperCase().toAlpha()
val len = text.length
var nLines = len / CHARS_PER_LINE
if (len % CHARS_PER_LINE > 0) nLines++
if (lines2.size >= nLines) {
val key = lines2.take(nLines).joinToString("").toAlpha()
val encrypted = vigenere(text, key)
val encFile = keyFile + "_enc"
File(encFile).writeText(encrypted)
println("\n'$encFile' has been created in the current directory.")
for (i in first until first + nLines) {
lines[i] = "-" + lines[i].drop(1)
}
File(keyFile).writeText(lines.joinToString("\n"))
if (DEMO) {
println("\nThe contents of the encrypted file are :\n")
println(encrypted)
}
}
else println("Not enough lines left in that file to do encryption")
}
else println("\nThat file does not exist.")
}
5 -> { // Decrypt
print("OTP file name to use (without extension) : ")
val keyFile = readLine()!! + ".1tp_cpy"
val kf = File(keyFile)
if (kf.exists()) {
val keyLines = File(keyFile).readLines().toMutableList()
var first = keyLines.size
for (i in 0 until keyLines.size) {
if (keyLines[i].startsWith(" ")) {
first = i
break
}
}
if (first == keyLines.size) {
println("\nThat file has no unused lines.")
continue@mainLoop
}
val keyLines2 = keyLines.drop(first) // get rid of comments and used lines
val encFile = keyFile.dropLast(3) + "enc"
val ef = File(encFile)
if (ef.exists()) {
val encLines = File(encFile).readLines().drop(1) // exclude comment line
val nLines = encLines.size
if (keyLines2.size >= nLines) {
val encrypted = encLines.joinToString("").toAlpha()
val key = keyLines2.take(nLines).joinToString("").toAlpha()
val decrypted = vigenere(encrypted, key, false)
val decFile = keyFile.dropLast(3) + "dec"
File(decFile).writeText(decrypted)
println("\n'$decFile' has been created in the current directory.")
for (i in first until first + nLines) {
keyLines[i] = "-" + keyLines[i].drop(1)
}
File(keyFile).writeText(keyLines.joinToString("\n"))
if (DEMO) {
println("\nThe contents of the decrypted file are :\n")
println(decrypted)
}
}
else println("Not enough lines left in that file to do decryption")
}
else println("\n'$encFile' is missing.")
}
else println("\nThat file does not exist.")
}
else -> return // Quit
}
}
} |
One of n lines in a file | Kotlin | A method of choosing a line randomly from a file:
::* Without reading the file more than once
::* When substantial parts of the file cannot be held in memory
::* Without knowing how many lines are in the file
Is to:
::* keep the first line of the file as a possible choice, then
::* 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.
::* 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.
::* ...
::* 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
::* Return the computed possible choice when no further lines exist in the file.
;Task:
# 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.
# 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.
# Print and show how many times each of the 10 lines is chosen as a rough measure of how well the algorithm works.
Note: You may choose a smaller number of repetitions if necessary, but mention this up-front.
Note: This is a specific version of a Reservoir Sampling algorithm: https://en.wikipedia.org/wiki/Reservoir_sampling
| // version 1.1.51
import java.util.Random
val r = Random()
fun oneOfN(n: Int): Int {
var choice = 1
for (i in 2..n) {
if (r.nextDouble() < 1.0 / i) choice = i
}
return choice
}
fun main(args: Array<String>) {
val n = 10
val freqs = IntArray(n)
val reps = 1_000_000
repeat(reps) {
val num = oneOfN(n)
freqs[num - 1]++
}
for (i in 1..n) println("Line ${"%-2d".format(i)} = ${freqs[i - 1]}")
} |
OpenWebNet password | Kotlin from Python | 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
'''Note:''' Factory default password is '12345'. Changing it is highly recommended !
conversation goes as follows
- *#*1##
- *99*0##
- *#603356072##
at 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
- *#25280520##
- *#*1##
| // version 1.1.51
fun ownCalcPass(password: Long, nonce: String): Long {
val m1 = 0xFFFF_FFFFL
val m8 = 0xFFFF_FFF8L
val m16 = 0xFFFF_FFF0L
val m128 = 0xFFFF_FF80L
val m16777216 = 0xFF00_0000L
var flag = true
var num1 = 0L
var num2 = 0L
for (c in nonce) {
num2 = num2 and m1
when (c) {
'1' -> {
if (flag) num2 = password
flag = false
num1 = num2 and m128
num1 = num1 ushr 7
num2 = num2 shl 25
num1 = num1 + num2
}
'2' -> {
if (flag) num2 = password
flag = false
num1 = num2 and m16
num1 = num1 ushr 4
num2 = num2 shl 28
num1 = num1 + num2
}
'3' -> {
if (flag) num2 = password
flag = false
num1 = num2 and m8
num1 = num1 ushr 3
num2 = num2 shl 29
num1 = num1 + num2
}
'4' -> {
if (flag) num2 = password
flag = false
num1 = num2 shl 1
num2 = num2 ushr 31
num1 = num1 + num2
}
'5' -> {
if (flag) num2 = password
flag = false
num1 = num2 shl 5
num2 = num2 ushr 27
num1 = num1 + num2
}
'6' -> {
if (flag) num2 = password
flag = false
num1 = num2 shl 12
num2 = num2 ushr 20
num1 = num1 + num2
}
'7' -> {
if (flag) num2 = password
flag = false
num1 = num2 and 0xFF00L
num1 = num1 + ((num2 and 0xFFL) shl 24)
num1 = num1 + ((num2 and 0xFF0000L) ushr 16)
num2 = (num2 and m16777216) ushr 8
num1 = num1 + num2
}
'8' -> {
if (flag) num2 = password
flag = false
num1 = num2 and 0xFFFFL
num1 = num1 shl 16
num1 = num1 + (num2 ushr 24)
num2 = num2 and 0xFF0000L
num2 = num2 ushr 8
num1 = num1 + num2
}
'9' -> {
if (flag) num2 = password
flag = false
num1 = num2.inv()
}
else -> num1 = num2
}
num2 = num1
}
return num1 and m1
}
fun ownTestCalcPass(passwd: String, nonce: String, expected: Long) {
val res = ownCalcPass(passwd.toLong(), nonce)
val m = "$passwd $nonce $res $expected"
println(if (res == expected) "PASS $m" else "FAIL $m")
}
fun main(args: Array<String>) {
ownTestCalcPass("12345", "603356072", 25280520)
ownTestCalcPass("12345", "410501656", 119537670)
} |
Operator precedence | Kotlin | Operators in C and C++}}
;Task:
Provide 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.
Operators 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.
State whether arguments are passed by value or by reference.
| This is well-documented [https://kotlinlang.org/docs/reference/grammar.html on the Kotlin language website].
|
Pancake numbers | Kotlin from Go | 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.
The task is to determine p(n) for n = 1 to 9, and for each show an example requiring p(n) flips.
[[Sorting_algorithms/Pancake_sort]] actually performs the sort some giving the number of flips used. How do these compare with p(n)?
Few people know p(20), generously I shall award an extra credit for anyone doing more than p(16).
;References
# Bill Gates and the pancake problem
# A058986
| fun pancake(n: Int): Int {
var gap = 2
var sum = 2
var adj = -1
while (sum < n) {
adj++
gap = gap * 2 - 1
sum += gap
}
return n + adj
}
fun main() {
(1 .. 20).map {"p(%2d) = %2d".format(it, pancake(it))}
val lines = results.chunked(5).map { it.joinToString(" ") }
lines.forEach { println(it) }
} |
Pangram checker | Kotlin | A pangram is a sentence that contains all the letters of the English alphabet at least once.
For example: ''The quick brown fox jumps over the lazy dog''.
;Task:
Write a function or method to check a sentence to see if it is a pangram (or not) and show its use.
;Related tasks:
:* determine if a string has all the same characters
:* determine if a string has all unique characters
| // version 1.0.6
fun isPangram(s: String): Boolean {
if (s.length < 26) return false
val t = s.toLowerCase()
for (c in 'a' .. 'z')
if (c !in t) return false
return true
}
fun main(args: Array<String>) {
val candidates = arrayOf(
"The quick brown fox jumps over the lazy dog",
"New job: fix Mr. Gluck's hazy TV, PDQ!",
"A very bad quack might jinx zippy fowls",
"A very mad quack might jinx zippy fowls" // no 'b' now!
)
for (candidate in candidates)
println("'$candidate' is ${if (isPangram(candidate)) "a" else "not a"} pangram")
} |
Paraffins | Kotlin from Java | This organic chemistry task is essentially to implement a tree enumeration algorithm.
;Task:
Enumerate, without repetitions and in order of increasing size, all possible paraffin molecules (also known as alkanes).
Paraffins 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.
In 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
But for all '''n''' >= 4 there are several distinct molecules ("isomers") with the same formula but different structures.
The number of isomers rises rather rapidly when '''n''' increases.
In 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.
;Example:
With '''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:
:::* a straight chain: (CH3)(CH2)(CH2)(CH3)
:::* a branched chain: (CH3)(CH(CH3))(CH3)
Due to bond rotations, it doesn't matter which direction the branch points in.
The 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.
The input is the number '''n''' of carbon atoms of a molecule (for instance '''17''').
The output is how many different different paraffins there are with '''n''' carbon atoms (for instance 24,894 if '''n''' = 17).
The sequence of those results is visible in the OEIS entry:
::: A00602: number of n-node unrooted quartic trees; number of n-carbon alkanes C(n)H(2n+2) ignoring stereoisomers.
The sequence is (the index starts from zero, and represents the number of carbon atoms):
1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159, 355, 802, 1858, 4347, 10359,
24894, 60523, 148284, 366319, 910726, 2278658, 5731580, 14490245,
36797588, 93839412, 240215803, 617105614, 1590507121, 4111846763,
10660307791, 27711253769, ...
;Extra credit:
Show the paraffins in some way.
A flat 1D representation, with arrays or lists is enough, for instance:
*Main> all_paraffins 1
[CCP H H H H]
*Main> all_paraffins 2
[BCP (C H H H) (C H H H)]
*Main> all_paraffins 3
[CCP H H (C H H H) (C H H H)]
*Main> all_paraffins 4
[BCP (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 5
[CCP H H (C H H (C H H H)) (C H H (C H H H)),
CCP H (C H H H) (C H H H) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H H)]
*Main> all_paraffins 6
[BCP (C H H (C H H (C H H H))) (C H H (C H H (C H H H))),
BCP (C H H (C H H (C H H H))) (C H (C H H H) (C H H H)),
BCP (C H (C H H H) (C H H H)) (C H (C H H H) (C H H H)),
CCP H (C H H H) (C H H (C H H H)) (C H H (C H H H)),
CCP (C H H H) (C H H H) (C H H H) (C H H (C H H H))]
Showing a basic 2D ASCII-art representation of the paraffins is better; for instance (molecule names aren't necessary):
methane ethane propane isobutane
H H H H H H H H H
| | | | | | | | |
H - C - H H - C - C - H H - C - C - C - H H - C - C - C - H
| | | | | | | | |
H H H H H H H | H
|
H - C - H
|
H
;Links:
* A paper that explains the problem and its solution in a functional language:
http://www.cs.wright.edu/~tkprasad/courses/cs776/paraffins-turner.pdf
* A Haskell implementation:
https://github.com/ghc/nofib/blob/master/imaginary/paraffins/Main.hs
* A Scheme implementation:
http://www.ccs.neu.edu/home/will/Twobit/src/paraffins.scm
* A Fortress implementation: (this site has been closed)
http://java.net/projects/projectfortress/sources/sources/content/ProjectFortress/demos/turnersParaffins0.fss?rev=3005
| // version 1.1.4-3
import java.math.BigInteger
const val MAX_N = 250
const val BRANCHES = 4
val rooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val unrooted = Array(MAX_N + 1) { if (it < 2) BigInteger.ONE else BigInteger.ZERO }
val c = Array(BRANCHES) { BigInteger.ZERO }
fun tree(br: Int, n: Int, l: Int, s: Int, cnt: BigInteger) {
var sum = s
for (b in (br + 1)..BRANCHES) {
sum += n
if (sum > MAX_N || (l * 2 >= sum && b >= BRANCHES)) return
var tmp = rooted[n]
if (b == br + 1) {
c[br] = tmp * cnt
}
else {
val diff = (b - br).toLong()
c[br] *= tmp + BigInteger.valueOf(diff - 1L)
c[br] /= BigInteger.valueOf(diff)
}
if (l * 2 < sum) unrooted[sum] += c[br]
if (b < BRANCHES) rooted[sum] += c[br]
for (m in n - 1 downTo 1) tree(b, m, l, sum, c[br])
}
}
fun bicenter(s: Int) {
if ((s and 1) == 0) {
var tmp = rooted[s / 2]
tmp *= tmp + BigInteger.ONE
unrooted[s] += tmp.shiftRight(1)
}
}
fun main(args: Array<String>) {
for (n in 1..MAX_N) {
tree(0, n, n, 1, BigInteger.ONE)
bicenter(n)
println("$n: ${unrooted[n]}")
}
} |
Parse an IP Address | Kotlin | The purpose of this task is to demonstrate parsing of text-format IP addresses, using IPv4 and IPv6.
Taking the following as inputs:
::: {| border="5" cellspacing="0" cellpadding=2
|-
|127.0.0.1
|The "localhost" IPv4 address
|-
|127.0.0.1:80
|The "localhost" IPv4 address, with a specified port (80)
|-
|::1
|The "localhost" IPv6 address
|-
|[::1]:80
|The "localhost" IPv6 address, with a specified port (80)
|-
|2605:2700:0:3::4713:93e3
|Rosetta Code's primary server's public IPv6 address
|-
|[2605:2700:0:3::4713:93e3]:80
|Rosetta Code's primary server's public IPv6 address, with a specified port (80)
|}
;Task:
Emit each described IP address as a hexadecimal integer representing the address, the address space, and the port number specified, if any.
In 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.
;Example:
'''127.0.0.1''' has the address number '''7F000001''' (2130706433 decimal)
in the ipv4 address space.
'''::ffff:127.0.0.1''' represents the same address in the ipv6 address space where it has the
address number '''FFFF7F000001''' (281472812449793 decimal).
'''::1''' has address number '''1''' and serves the same purpose in the ipv6 address
space that '''127.0.0.1''' serves in the ipv4 address space.
| // version 1.1.3
import java.math.BigInteger
enum class AddressSpace { IPv4, IPv6, Invalid }
data class IPAddressComponents(
val address: BigInteger,
val addressSpace: AddressSpace,
val port: Int // -1 denotes 'not specified'
)
val INVALID = IPAddressComponents(BigInteger.ZERO, AddressSpace.Invalid, 0)
fun ipAddressParse(ipAddress: String): IPAddressComponents {
var addressSpace = AddressSpace.IPv4
var ipa = ipAddress.toLowerCase()
var port = -1
var trans = false
if (ipa.startsWith("::ffff:") && '.' in ipa) {
addressSpace = AddressSpace.IPv6
trans = true
ipa = ipa.drop(7)
}
else if (ipa.startsWith("[::ffff:") && '.' in ipa) {
addressSpace = AddressSpace.IPv6
trans = true
ipa = ipa.drop(8).replace("]", "")
}
val octets = ipa.split('.').reversed().toTypedArray()
var address = BigInteger.ZERO
if (octets.size == 4) {
val split = octets[0].split(':')
if (split.size == 2) {
val temp = split[1].toIntOrNull()
if (temp == null || temp !in 0..65535) return INVALID
port = temp
octets[0] = split[0]
}
for (i in 0..3) {
val num = octets[i].toLongOrNull()
if (num == null || num !in 0..255) return INVALID
val bigNum = BigInteger.valueOf(num)
address = address.or(bigNum.shiftLeft(i * 8))
}
if (trans) address += BigInteger("ffff00000000", 16)
}
else if (octets.size == 1) {
addressSpace = AddressSpace.IPv6
if (ipa[0] == '[') {
ipa = ipa.drop(1)
val split = ipa.split("]:")
if (split.size != 2) return INVALID
val temp = split[1].toIntOrNull()
if (temp == null || temp !in 0..65535) return INVALID
port = temp
ipa = ipa.dropLast(2 + split[1].length)
}
val hextets = ipa.split(':').reversed().toMutableList()
val len = hextets.size
if (ipa.startsWith("::"))
hextets[len - 1] = "0"
else if (ipa.endsWith("::"))
hextets[0] = "0"
if (ipa == "::") hextets[1] = "0"
if (len > 8 || (len == 8 && hextets.any { it == "" }) || hextets.count { it == "" } > 1)
return INVALID
if (len < 8) {
var insertions = 8 - len
for (i in 0..7) {
if (hextets[i] == "") {
hextets[i] = "0"
while (insertions-- > 0) hextets.add(i, "0")
break
}
}
}
for (j in 0..7) {
val num = hextets[j].toLongOrNull(16)
if (num == null || num !in 0x0..0xFFFF) return INVALID
val bigNum = BigInteger.valueOf(num)
address = address.or(bigNum.shiftLeft(j * 16))
}
}
else return INVALID
return IPAddressComponents(address, addressSpace, port)
}
fun main(args: Array<String>) {
val ipas = listOf(
"127.0.0.1",
"127.0.0.1:80",
"::1",
"[::1]:80",
"2605:2700:0:3::4713:93e3",
"[2605:2700:0:3::4713:93e3]:80",
"::ffff:192.168.173.22",
"[::ffff:192.168.173.22]:80",
"1::",
"::",
"256.0.0.0",
"::ffff:127.0.0.0.1"
)
for (ipa in ipas) {
val (address, addressSpace, port) = ipAddressParse(ipa)
println("IP address : $ipa")
println("Address : ${"%X".format(address)}")
println("Address Space : $addressSpace")
println("Port : ${if (port == -1) "not specified" else port.toString()}")
println()
}
} |
Parsing/RPN calculator algorithm | Kotlin | 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''.
* Assume an input of a correct, space separated, string of tokens of an RPN expression
* Test with the RPN expression generated from the [[Parsing/Shunting-yard algorithm]] task:
3 4 2 * 1 5 - 2 3 ^ ^ / +
* Print or display the output here
;Notes:
* '''^''' means exponentiation in the expression above.
* '''/''' means division.
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* Several solutions to [[24 game/Solve]] make use of RPN evaluators (although tracing how they work is not a part of that task).
* [[Parsing/RPN to infix conversion]].
* [[Arithmetic evaluation]].
| // version 1.1.2
fun rpnCalculate(expr: String) {
if (expr.isEmpty()) throw IllegalArgumentException("Expresssion cannot be empty")
println("For expression = $expr\n")
println("Token Action Stack")
val tokens = expr.split(' ').filter { it != "" }
val stack = mutableListOf<Double>()
for (token in tokens) {
val d = token.toDoubleOrNull()
if (d != null) {
stack.add(d)
println(" $d Push num onto top of stack $stack")
}
else if ((token.length > 1) || (token !in "+-*/^")) {
throw IllegalArgumentException("$token is not a valid token")
}
else if (stack.size < 2) {
throw IllegalArgumentException("Stack contains too few operands")
}
else {
val d1 = stack.removeAt(stack.lastIndex)
val d2 = stack.removeAt(stack.lastIndex)
stack.add(when (token) {
"+" -> d2 + d1
"-" -> d2 - d1
"*" -> d2 * d1
"/" -> d2 / d1
else -> Math.pow(d2, d1)
})
println(" $token Apply op to top of stack $stack")
}
}
println("\nThe final value is ${stack[0]}")
}
fun main(args: Array<String>) {
val expr = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
rpnCalculate(expr)
} |
Parsing/RPN to infix conversion | Kotlin from Java | Create a program that takes an infix notation.
* Assume an input of a correct, space separated, string of tokens
* Generate a space separated output string representing the same expression in infix notation
* Show how the major datastructure of your algorithm changes with each new token parsed.
* Test with the following input RPN strings then print and display the output here.
:::::{| class="wikitable"
! RPN input !! sample output
|- || align="center"
| 3 4 2 * 1 5 - 2 3 ^ ^ / +|| 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
|- || align="center"
| 1 2 + 3 4 + ^ 5 6 + ^|| ( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )
|}
* Operator precedence and operator associativity is given in this table:
::::::::{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;See also:
* [[Parsing/Shunting-yard algorithm]] for a method of generating an RPN from an infix expression.
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* Postfix to infix from the RubyQuiz site.
| // version 1.2.0
import java.util.Stack
class Expression(var ex: String, val op: String = "", val prec: Int = 3) {
constructor(e1: String, e2: String, o: String) :
this("$e1 $o $e2", o, OPS.indexOf(o) / 2)
override fun toString() = ex
companion object {
const val OPS = "-+/*^"
}
}
fun postfixToInfix(postfix: String): String {
val expr = Stack<Expression>()
val rx = Regex("""\s+""")
for (token in postfix.split(rx)) {
val c = token[0]
val idx = Expression.OPS.indexOf(c)
if (idx != -1 && token.length == 1) {
val r = expr.pop()
val l = expr.pop()
val opPrec = idx / 2
if (l.prec < opPrec || (l.prec == opPrec && c == '^')) {
l.ex = "(${l.ex})"
}
if (r.prec < opPrec || (r.prec == opPrec && c != '^')) {
r.ex = "(${r.ex})"
}
expr.push(Expression(l.ex, r.ex, token))
}
else {
expr.push(Expression(token))
}
println("$token -> $expr")
}
return expr.peek().ex
}
fun main(args: Array<String>) {
val es = listOf(
"3 4 2 * 1 5 - 2 3 ^ ^ / +",
"1 2 + 3 4 + ^ 5 6 + ^"
)
for (e in es) {
println("Postfix : $e")
println("Infix : ${postfixToInfix(e)}\n")
}
} |
Parsing/Shunting-yard algorithm | Kotlin from Java | 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
as each individual token is processed.
* Assume an input of a correct, space separated, string of tokens representing an infix expression
* Generate a space separated output string representing the RPN
* Test with the input string:
:::: 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3
* print and display the output here.
* Operator precedence is given in this table:
:{| class="wikitable"
! operator !! associativity !! operation
|- || align="center"
| ^ || 4 || right || exponentiation
|- || align="center"
| * || 3 || left || multiplication
|- || align="center"
| / || 3 || left || division
|- || align="center"
| + || 2 || left || addition
|- || align="center"
| - || 2 || left || subtraction
|}
;Extra credit
Add extra text explaining the actions and an optional comment for the action on receipt of each token.
;Note
The handling of functions and arguments is not required.
;See also:
* [[Parsing/RPN calculator algorithm]] for a method of calculating a final value from this output RPN expression.
* [[Parsing/RPN to infix conversion]].
| // version 1.2.0
import java.util.Stack
/* To find out the precedence, we take the index of the
token in the OPS string and divide by 2 (rounding down).
This will give us: 0, 0, 1, 1, 2 */
const val OPS = "-+/*^"
fun infixToPostfix(infix: String): String {
val sb = StringBuilder()
val s = Stack<Int>()
val rx = Regex("""\s""")
for (token in infix.split(rx)) {
if (token.isEmpty()) continue
val c = token[0]
val idx = OPS.indexOf(c)
// check for operator
if (idx != - 1) {
if (s.isEmpty()) {
s.push(idx)
}
else {
while (!s.isEmpty()) {
val prec2 = s.peek() / 2
val prec1 = idx / 2
if (prec2 > prec1 || (prec2 == prec1 && c != '^')) {
sb.append(OPS[s.pop()]).append(' ')
}
else break
}
s.push(idx)
}
}
else if (c == '(') {
s.push(-2) // -2 stands for '('
}
else if (c == ')') {
// until '(' on stack, pop operators.
while (s.peek() != -2) sb.append(OPS[s.pop()]).append(' ')
s.pop()
}
else {
sb.append(token).append(' ')
}
}
while (!s.isEmpty()) sb.append(OPS[s.pop()]).append(' ')
return sb.toString()
}
fun main(args: Array<String>) {
val es = listOf(
"3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3",
"( ( 1 + 2 ) ^ ( 3 + 4 ) ) ^ ( 5 + 6 )"
)
for (e in es) {
println("Infix : $e")
println("Postfix : ${infixToPostfix(e)}\n")
}
} |
Pascal's triangle/Puzzle | Kotlin from C | This puzzle involves a Pascals Triangle, also known as a Pyramid of Numbers.
[ 151]
[ ][ ]
[40][ ][ ]
[ ][ ][ ][ ]
[ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
Of the three missing numbers at the base of the pyramid,
the middle one is the sum of the other two (that is, Y = X + Z).
;Task:
Write a program to find a solution to this puzzle.
| // version 1.1.3
data class Solution(val x: Int, val y: Int, val z: Int)
fun Double.isIntegral(tolerance: Double = 0.0) =
(this - Math.floor(this)) <= tolerance || (Math.ceil(this) - this) <= tolerance
fun pascal(a: Int, b: Int, mid: Int, top: Int): Solution {
val yd = (top - 4 * (a + b)) / 7.0
if (!yd.isIntegral(0.0001)) return Solution(0, 0, 0)
val y = yd.toInt()
val x = mid - 2 * a - y
return Solution(x, y, y - x)
}
fun main(args: Array<String>) {
val (x, y, z) = pascal(11, 4, 40, 151)
if (x != 0)
println("Solution is: x = $x, y = $y, z = $z")
else
println("There is no solutuon")
} |
Pascal matrix generation | Kotlin | A pascal matrix is a two-dimensional square matrix holding numbers from binomial coefficients and which can be shown as nCr.
Shown below are truncated 5-by-5 matrices M[i, j] for i,j in range 0..4.
A Pascal upper-triangular matrix that is populated with jCi:
[[1, 1, 1, 1, 1],
[0, 1, 2, 3, 4],
[0, 0, 1, 3, 6],
[0, 0, 0, 1, 4],
[0, 0, 0, 0, 1]]
A Pascal lower-triangular matrix that is populated with iCj (the transpose of the upper-triangular matrix):
[[1, 0, 0, 0, 0],
[1, 1, 0, 0, 0],
[1, 2, 1, 0, 0],
[1, 3, 3, 1, 0],
[1, 4, 6, 4, 1]]
A Pascal symmetric matrix that is populated with i+jCi:
[[1, 1, 1, 1, 1],
[1, 2, 3, 4, 5],
[1, 3, 6, 10, 15],
[1, 4, 10, 20, 35],
[1, 5, 15, 35, 70]]
;Task:
Write functions capable of generating each of the three forms of n-by-n matrices.
Use those functions to display upper, lower, and symmetric Pascal 5-by-5 matrices on this page.
The 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).
;Note:
The [[Cholesky decomposition]] of a Pascal symmetric matrix is the Pascal lower-triangle matrix of the same size.
| // version 1.1.3
fun binomial(n: Int, k: Int): Int {
if (n < k) return 0
if (n == 0 || k == 0) return 1
val num = (k + 1..n).fold(1) { acc, i -> acc * i }
val den = (2..n - k).fold(1) { acc, i -> acc * i }
return num / den
}
fun pascalUpperTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(j, i) } }
fun pascalLowerTriangular(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i, j) } }
fun pascalSymmetric(n: Int) = List(n) { i -> IntArray(n) { j -> binomial(i + j, i) } }
fun printMatrix(title: String, m: List<IntArray>) {
val n = m.size
println(title)
print("[")
for (i in 0 until n) {
if (i > 0) print(" ")
print(m[i].contentToString())
if (i < n - 1) println(",") else println("]\n")
}
}
fun main(args: Array<String>) {
printMatrix("Pascal upper-triangular matrix", pascalUpperTriangular(5))
printMatrix("Pascal lower-triangular matrix", pascalLowerTriangular(5))
printMatrix("Pascal symmetric matrix", pascalSymmetric(5))
} |
Password generator | Kotlin | Create a password generation program which will generate passwords containing random ASCII characters from the following groups:
lower-case letters: a --> z
upper-case letters: A --> Z
digits: 0 --> 9
other printable characters: !"#$%&'()*+,-./:;<=>?@[]^_{|}~
(the above character list excludes white-space, backslash and grave)
The generated password(s) must include ''at least one'' (of each of the four groups):
lower-case letter,
upper-case letter,
digit (numeral), and
one "other" character.
The user must be able to specify the password length and the number of passwords to generate.
The passwords should be displayed or written to a file, one per line.
The randomness should be from a system source or library.
The program should implement a help option or button which should describe the program and options when invoked.
You may also allow the user to specify a seed value, and give the option of excluding visually similar characters.
For example: Il1 O0 5S 2Z where the characters are:
::::* capital eye, lowercase ell, the digit one
::::* capital oh, the digit zero
::::* the digit five, capital ess
::::* the digit two, capital zee
| // version 1.1.4-3
import java.util.Random
import java.io.File
val r = Random()
val rr = Random() // use a separate generator for shuffles
val ls = System.getProperty("line.separator")
var lower = "abcdefghijklmnopqrstuvwxyz"
var upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var digit = "0123456789"
var other = """!"#$%&'()*+,-./:;<=>?@[]^_{|}~"""
val exclChars = arrayOf(
"'I', 'l' and '1'",
"'O' and '0' ",
"'5' and 'S' ",
"'2' and 'Z' "
)
fun String.shuffle(): String {
val sb = StringBuilder(this)
var n = sb.length
while (n > 1) {
val k = rr.nextInt(n--)
val t = sb[n]
sb[n] = sb[k]
sb[k] = t
}
return sb.toString()
}
fun generatePasswords(pwdLen: Int, pwdNum: Int, toConsole: Boolean, toFile: Boolean) {
val sb = StringBuilder()
val ll = lower.length
val ul = upper.length
val dl = digit.length
val ol = other.length
val tl = ll + ul + dl + ol
var fw = if (toFile) File("pwds.txt").writer() else null
if (toConsole) println("\nThe generated passwords are:")
for (i in 0 until pwdNum) {
sb.setLength(0)
sb.append(lower[r.nextInt(ll)])
sb.append(upper[r.nextInt(ul)])
sb.append(digit[r.nextInt(dl)])
sb.append(other[r.nextInt(ol)])
for (j in 0 until pwdLen - 4) {
val k = r.nextInt(tl)
sb.append(when (k) {
in 0 until ll -> lower[k]
in ll until ll + ul -> upper[k - ll]
in ll + ul until tl - ol -> digit[k - ll - ul]
else -> other[tl - 1 - k]
})
}
var pwd = sb.toString()
repeat(5) { pwd = pwd.shuffle() } // shuffle 5 times say
if (toConsole) println(" ${"%2d".format(i + 1)}: $pwd")
if (toFile) {
fw!!.write(pwd)
if (i < pwdNum - 1) fw.write(ls)
}
}
if (toFile) {
println("\nThe generated passwords have been written to the file pwds.txt")
fw!!.close()
}
}
fun printHelp() {
println("""
|This program generates up to 99 passwords of between 5 and 20 characters in
|length.
|
|You will be prompted for the values of all parameters when the program is run
|- there are no command line options to memorize.
|
|The passwords can either be written to the console or to a file (pwds.txt),
|or both.
|
|The passwords must contain at least one each of the following character types:
| lower-case letters : a -> z
| upper-case letters : A -> Z
| digits : 0 -> 9
| other characters : !"#$%&'()*+,-./:;<=>?@[]^_{|}~
|
|Optionally, a seed can be set for the random generator
|(any non-zero Long integer) otherwise the default seed will be used.
|Even if the same seed is set, the passwords won't necessarily be exactly
|the same on each run as additional random shuffles are always performed.
|
|You can also specify that various sets of visually similar characters
|will be excluded (or not) from the passwords, namely: Il1 O0 5S 2Z
|
|Finally, the only command line options permitted are -h and -help which
|will display this page and then exit.
|
|Any other command line parameters will simply be ignored and the program
|will be run normally.
|
""".trimMargin())
}
fun main(args: Array<String>) {
if (args.size == 1 && (args[0] == "-h" || args[0] == "-help")) {
printHelp()
return
}
println("Please enter the following and press return after each one")
var pwdLen: Int?
do {
print(" Password length (5 to 20) : ")
pwdLen = readLine()!!.toIntOrNull() ?: 0
}
while (pwdLen !in 5..20)
var pwdNum: Int?
do {
print(" Number to generate (1 to 99) : ")
pwdNum = readLine()!!.toIntOrNull() ?: 0
}
while (pwdNum !in 1..99)
var seed: Long?
do {
print(" Seed value (0 to use default) : ")
seed = readLine()!!.toLongOrNull()
}
while (seed == null)
if (seed != 0L) r.setSeed(seed)
println(" Exclude the following visually similar characters")
for (i in 0..3) {
var yn: String
do {
print(" ${exclChars[i]} y/n : ")
yn = readLine()!!.toLowerCase()
}
while (yn != "y" && yn != "n")
if (yn == "y") {
when (i) {
0 -> {
upper = upper.replace("I", "")
lower = lower.replace("l", "")
digit = digit.replace("1", "")
}
1 -> {
upper = upper.replace("O", "")
digit = digit.replace("0", "")
}
2 -> {
upper = upper.replace("S", "")
digit = digit.replace("5", "")
}
3 -> {
upper = upper.replace("Z", "")
digit = digit.replace("2", "")
}
}
}
}
var toConsole: Boolean?
do {
print(" Write to console y/n : ")
val t = readLine()!!
toConsole = if (t == "y") true else if (t == "n") false else null
}
while (toConsole == null)
var toFile: Boolean? = true
if (toConsole) {
do {
print(" Write to file y/n : ")
val t = readLine()!!
toFile = if (t == "y") true else if (t == "n") false else null
}
while (toFile == null)
}
generatePasswords(pwdLen!!, pwdNum!!, toConsole, toFile!!)
} |
Pathological floating point problems | Kotlin | Most programmers are familiar with the inexactness of floating point calculations in a binary processor.
The classic example being:
0.1 + 0.2 = 0.30000000000000004
In many situations the amount of error in such calculations is very small and can be overlooked or eliminated with rounding.
There are pathological problems however, where seemingly simple, straight-forward calculations are extremely sensitive to even tiny amounts of imprecision.
This task's purpose is to show how your language deals with such classes of problems.
'''A sequence that seems to converge to a wrong limit.'''
Consider the sequence:
:::::: v1 = 2
:::::: v2 = -4
:::::: vn = 111 - 1130 / vn-1 + 3000 / (vn-1 * vn-2)
As '''n''' grows larger, the series should converge to '''6''' but small amounts of error will cause it to approach '''100'''.
;Task 1:
Display the values of the sequence where n = 3, 4, 5, 6, 7, 8, 20, 30, 50 & 100 to at least '''16''' decimal places.
n = 3 18.5
n = 4 9.378378
n = 5 7.801153
n = 6 7.154414
n = 7 6.806785
n = 8 6.5926328
n = 20 6.0435521101892689
n = 30 6.006786093031205758530554
n = 50 6.0001758466271871889456140207471954695237
n = 100 6.000000019319477929104086803403585715024350675436952458072592750856521767230266
;Task 2:
'''The Chaotic Bank Society''' is offering a new investment account to their customers.
You first deposit $e - 1 where e is 2.7182818... the base of natural logarithms.
After each year, your account balance will be multiplied by the number of years that have passed, and $1 in service charges will be removed.
So ...
::* after 1 year, your balance will be multiplied by 1 and $1 will be removed for service charges.
::* after 2 years your balance will be doubled and $1 removed.
::* after 3 years your balance will be tripled and $1 removed.
::* ...
::* after 10 years, multiplied by 10 and $1 removed, and so on.
What will your balance be after 25 years?
Starting balance: $e-1
Balance = (Balance * year) - 1 for 25 years
Balance after 25 years: $0.0399387296732302
;Task 3, extra credit:
'''Siegfried Rump's example.''' Consider the following function, designed by Siegfried Rump in 1988.
:::::: f(a,b) = 333.75b6 + a2( 11a2b2 - b6 - 121b4 - 2 ) + 5.5b8 + a/(2b)
:::::: compute f(a,b) where a=77617.0 and b=33096.0
:::::: f(77617.0, 33096.0) = -0.827396059946821
Demonstrate how to solve at least one of the first two problems, or both, and the third if you're feeling particularly jaunty.
;See also;
* Floating-Point Arithmetic Section 1.3.2 Difficult problems.
| // version 1.0.6
import java.math.*
const val LIMIT = 100
val con480 = MathContext(480)
val bigTwo = BigDecimal(2)
val bigE = BigDecimal("2.71828182845904523536028747135266249775724709369995") // precise enough!
fun main(args: Array<String>) {
// v(n) sequence task
val c1 = BigDecimal(111)
val c2 = BigDecimal(1130)
val c3 = BigDecimal(3000)
var v1 = bigTwo
var v2 = BigDecimal(-4)
var v3: BigDecimal
for (i in 3 .. LIMIT) {
v3 = c1 - c2.divide(v2, con480) + c3.divide(v2 * v1, con480)
println("${"%3d".format(i)} : ${"%19.16f".format(v3)}")
v1 = v2
v2 = v3
}
// Chaotic Building Society task
var balance = bigE - BigDecimal.ONE
for (year in 1..25) balance = balance.multiply(BigDecimal(year), con480) - BigDecimal.ONE
println("\nBalance after 25 years is ${"%18.16f".format(balance)}")
// Siegfried Rump task
val a = BigDecimal(77617)
val b = BigDecimal(33096)
val c4 = BigDecimal("333.75")
val c5 = BigDecimal(11)
val c6 = BigDecimal(121)
val c7 = BigDecimal("5.5")
var f = c4 * b.pow(6, con480) + c7 * b.pow(8, con480) + a.divide(bigTwo * b, con480)
val c8 = c5 * a.pow(2, con480) * b.pow(2, con480) - b.pow(6, con480) - c6 * b.pow(4, con480) - bigTwo
f += c8 * a.pow(2, con480)
println("\nf(77617.0, 33096.0) is ${"%18.16f".format(f)}")
} |
Peaceful chess queen armies | Kotlin from D | 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.
\
|
/
=
=
=
=
/
|
\
/
|
\
|
The 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''.
;Task:
# 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).
# Create a routine to generate at least one solution to placing m equal numbers of black and white queens on an n square board.
# Display here results for the m=4, n=5 case.
;References:
* Peaceably Coexisting Armies of Queens (Pdf) by Robert A. Bosch. Optima, the Mathematical Programming Socity newsletter, issue 62.
* A250000 OEIS
| import kotlin.math.abs
enum class Piece {
Empty,
Black,
White,
}
typealias Position = Pair<Int, Int>
fun place(m: Int, n: Int, pBlackQueens: MutableList<Position>, pWhiteQueens: MutableList<Position>): Boolean {
if (m == 0) {
return true
}
var placingBlack = true
for (i in 0 until n) {
inner@
for (j in 0 until n) {
val pos = Position(i, j)
for (queen in pBlackQueens) {
if (queen == pos || !placingBlack && isAttacking(queen, pos)) {
continue@inner
}
}
for (queen in pWhiteQueens) {
if (queen == pos || placingBlack && isAttacking(queen, pos)) {
continue@inner
}
}
placingBlack = if (placingBlack) {
pBlackQueens.add(pos)
false
} else {
pWhiteQueens.add(pos)
if (place(m - 1, n, pBlackQueens, pWhiteQueens)) {
return true
}
pBlackQueens.removeAt(pBlackQueens.lastIndex)
pWhiteQueens.removeAt(pWhiteQueens.lastIndex)
true
}
}
}
if (!placingBlack) {
pBlackQueens.removeAt(pBlackQueens.lastIndex)
}
return false
}
fun isAttacking(queen: Position, pos: Position): Boolean {
return queen.first == pos.first
|| queen.second == pos.second
|| abs(queen.first - pos.first) == abs(queen.second - pos.second)
}
fun printBoard(n: Int, blackQueens: List<Position>, whiteQueens: List<Position>) {
val board = MutableList(n * n) { Piece.Empty }
for (queen in blackQueens) {
board[queen.first * n + queen.second] = Piece.Black
}
for (queen in whiteQueens) {
board[queen.first * n + queen.second] = Piece.White
}
for ((i, b) in board.withIndex()) {
if (i != 0 && i % n == 0) {
println()
}
if (b == Piece.Black) {
print("B ")
} else if (b == Piece.White) {
print("W ")
} else {
val j = i / n
val k = i - j * n
if (j % 2 == k % 2) {
print("• ")
} else {
print("◦ ")
}
}
}
println('\n')
}
fun main() {
val nms = listOf(
Pair(2, 1), Pair(3, 1), Pair(3, 2), Pair(4, 1), Pair(4, 2), Pair(4, 3),
Pair(5, 1), Pair(5, 2), Pair(5, 3), Pair(5, 4), Pair(5, 5),
Pair(6, 1), Pair(6, 2), Pair(6, 3), Pair(6, 4), Pair(6, 5), Pair(6, 6),
Pair(7, 1), Pair(7, 2), Pair(7, 3), Pair(7, 4), Pair(7, 5), Pair(7, 6), Pair(7, 7)
)
for ((n, m) in nms) {
println("$m black and $m white queens on a $n x $n board:")
val blackQueens = mutableListOf<Position>()
val whiteQueens = mutableListOf<Position>()
if (place(m, n, blackQueens, whiteQueens)) {
printBoard(n, blackQueens, whiteQueens)
} else {
println("No solution exists.\n")
}
}
} |
Pentagram | Kotlin from Java | 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.
;Task:
Draw (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.
;See also
* Angle sum of a pentagram
| // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
class Pentagram : JPanel() {
init {
preferredSize = Dimension(640, 640)
background = Color.white
}
private fun drawPentagram(g: Graphics2D, len: Int, x: Int, y: Int,
fill: Color, stroke: Color) {
var x2 = x.toDouble()
var y2 = y.toDouble()
var angle = 0.0
val p = Path2D.Float()
p.moveTo(x2, y2)
for (i in 0..4) {
x2 += Math.cos(angle) * len
y2 += Math.sin(-angle) * len
p.lineTo(x2, y2)
angle -= Math.toRadians(144.0)
}
p.closePath()
with(g) {
color = fill
fill(p)
color = stroke
draw(p)
}
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
g.stroke = BasicStroke(5.0f, BasicStroke.CAP_ROUND, 0)
drawPentagram(g, 500, 70, 250, Color(0x6495ED), Color.darkGray)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Pentagram"
isResizable = false
add(Pentagram(), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
Pentomino tiling | Kotlin from Java | A pentomino is a polyomino that consists of 5 squares. There are 12 pentomino shapes,
if you don't count rotations and reflections. Most pentominoes can form their own mirror image through
rotation, but some of them have to be flipped over.
I
I L N Y
FF I L NN PP TTT V W X YY ZZ
FF I L N PP T U U V WW XXX Y Z
F I LL N P T UUU VVV WW X Y ZZ
A Pentomino tiling is an example of an exact cover problem and can take on many forms.
A traditional tiling presents an 8 by 8 grid, where 4 cells are left uncovered. The other cells are covered
by the 12 pentomino shapes, without overlaps, with every shape only used once.
The 4 uncovered cells should be chosen at random. Note that not all configurations are solvable.
;Task
Create an 8 by 8 tiling and print the result.
;Example
F I I I I I L N
F F F L L L L N
W F - X Z Z N N
W W X X X Z N V
T W W X - Z Z V
T T T P P V V V
T Y - P P U U U
Y Y Y Y P U - U
;Related tasks
* Free polyominoes enumeration
| // Version 1.1.4-3
import java.util.Random
val F = arrayOf(
intArrayOf(1, -1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 2, 0),
intArrayOf(1, 0, 1, 1, 1, 2, 2, 1), intArrayOf(1, 0, 1, 1, 2, -1, 2, 0),
intArrayOf(1, -2, 1, -1, 1, 0, 2, -1), intArrayOf(0, 1, 1, 1, 1, 2, 2, 1),
intArrayOf(1, -1, 1, 0, 1, 1, 2, -1), intArrayOf(1, -1, 1, 0, 2, 0, 2, 1)
)
val I = arrayOf(
intArrayOf(0, 1, 0, 2, 0, 3, 0, 4), intArrayOf(1, 0, 2, 0, 3, 0, 4, 0)
)
val L = arrayOf(
intArrayOf(1, 0, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, 0, 3, -1, 3, 0),
intArrayOf(0, 1, 0, 2, 0, 3, 1, 3), intArrayOf(0, 1, 1, 0, 2, 0, 3, 0),
intArrayOf(0, 1, 1, 1, 2, 1, 3, 1), intArrayOf(0, 1, 0, 2, 0, 3, 1, 0),
intArrayOf(1, 0, 2, 0, 3, 0, 3, 1), intArrayOf(1, -3, 1, -2, 1, -1, 1, 0)
)
val N = arrayOf(
intArrayOf(0, 1, 1, -2, 1, -1, 1, 0), intArrayOf(1, 0, 1, 1, 2, 1, 3, 1),
intArrayOf(0, 1, 0, 2, 1, -1, 1, 0), intArrayOf(1, 0, 2, 0, 2, 1, 3, 1),
intArrayOf(0, 1, 1, 1, 1, 2, 1, 3), intArrayOf(1, 0, 2, -1, 2, 0, 3, -1),
intArrayOf(0, 1, 0, 2, 1, 2, 1, 3), intArrayOf(1, -1, 1, 0, 2, -1, 3, -1)
)
val P = arrayOf(
intArrayOf(0, 1, 1, 0, 1, 1, 2, 1), intArrayOf(0, 1, 0, 2, 1, 0, 1, 1),
intArrayOf(1, 0, 1, 1, 2, 0, 2, 1), intArrayOf(0, 1, 1, -1, 1, 0, 1, 1),
intArrayOf(0, 1, 1, 0, 1, 1, 1, 2), intArrayOf(1, -1, 1, 0, 2, -1, 2, 0),
intArrayOf(0, 1, 0, 2, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 1, 1, 2, 0)
)
val T = arrayOf(
intArrayOf(0, 1, 0, 2, 1, 1, 2, 1), intArrayOf(1, -2, 1, -1, 1, 0, 2, 0),
intArrayOf(1, 0, 2, -1, 2, 0, 2, 1), intArrayOf(1, 0, 1, 1, 1, 2, 2, 0)
)
val U = arrayOf(
intArrayOf(0, 1, 0, 2, 1, 0, 1, 2), intArrayOf(0, 1, 1, 1, 2, 0, 2, 1),
intArrayOf(0, 2, 1, 0, 1, 1, 1, 2), intArrayOf(0, 1, 1, 0, 2, 0, 2, 1)
)
val V = arrayOf(
intArrayOf(1, 0, 2, 0, 2, 1, 2, 2), intArrayOf(0, 1, 0, 2, 1, 0, 2, 0),
intArrayOf(1, 0, 2, -2, 2, -1, 2, 0), intArrayOf(0, 1, 0, 2, 1, 2, 2, 2)
)
val W = arrayOf(
intArrayOf(1, 0, 1, 1, 2, 1, 2, 2), intArrayOf(1, -1, 1, 0, 2, -2, 2, -1),
intArrayOf(0, 1, 1, 1, 1, 2, 2, 2), intArrayOf(0, 1, 1, -1, 1, 0, 2, -1)
)
val X = arrayOf(intArrayOf(1, -1, 1, 0, 1, 1, 2, 0))
val Y = arrayOf(
intArrayOf(1, -2, 1, -1, 1, 0, 1, 1), intArrayOf(1, -1, 1, 0, 2, 0, 3, 0),
intArrayOf(0, 1, 0, 2, 0, 3, 1, 1), intArrayOf(1, 0, 2, 0, 2, 1, 3, 0),
intArrayOf(0, 1, 0, 2, 0, 3, 1, 2), intArrayOf(1, 0, 1, 1, 2, 0, 3, 0),
intArrayOf(1, -1, 1, 0, 1, 1, 1, 2), intArrayOf(1, 0, 2, -1, 2, 0, 3, 0)
)
val Z = arrayOf(
intArrayOf(0, 1, 1, 0, 2, -1, 2, 0), intArrayOf(1, 0, 1, 1, 1, 2, 2, 2),
intArrayOf(0, 1, 1, 1, 2, 1, 2, 2), intArrayOf(1, -2, 1, -1, 1, 0, 2, -2)
)
val shapes = arrayOf(F, I, L, N, P, T, U, V, W, X, Y, Z)
val rand = Random()
val symbols = "FILNPTUVWXYZ-".toCharArray()
val nRows = 8
val nCols = 8
val blank = 12
val grid = Array(nRows) { IntArray(nCols) }
val placed = BooleanArray(symbols.size - 1)
fun tryPlaceOrientation(o: IntArray, r: Int, c: Int, shapeIndex: Int): Boolean {
for (i in 0 until o.size step 2) {
val x = c + o[i + 1]
val y = r + o[i]
if (x !in (0 until nCols) || y !in (0 until nRows) || grid[y][x] != - 1) return false
}
grid[r][c] = shapeIndex
for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = shapeIndex
return true
}
fun removeOrientation(o: IntArray, r: Int, c: Int) {
grid[r][c] = -1
for (i in 0 until o.size step 2) grid[r + o[i]][c + o[i + 1]] = -1
}
fun solve(pos: Int, numPlaced: Int): Boolean {
if (numPlaced == shapes.size) return true
val row = pos / nCols
val col = pos % nCols
if (grid[row][col] != -1) return solve(pos + 1, numPlaced)
for (i in 0 until shapes.size) {
if (!placed[i]) {
for (orientation in shapes[i]) {
if (!tryPlaceOrientation(orientation, row, col, i)) continue
placed[i] = true
if (solve(pos + 1, numPlaced + 1)) return true
removeOrientation(orientation, row, col)
placed[i] = false
}
}
}
return false
}
fun shuffleShapes() {
var n = shapes.size
while (n > 1) {
val r = rand.nextInt(n--)
val tmp = shapes[r]
shapes[r] = shapes[n]
shapes[n] = tmp
val tmpSymbol= symbols[r]
symbols[r] = symbols[n]
symbols[n] = tmpSymbol
}
}
fun printResult() {
for (r in grid) {
for (i in r) print("${symbols[i]} ")
println()
}
}
fun main(args: Array<String>) {
shuffleShapes()
for (r in 0 until nRows) grid[r].fill(-1)
for (i in 0..3) {
var randRow: Int
var randCol: Int
do {
randRow = rand.nextInt(nRows)
randCol = rand.nextInt(nCols)
}
while (grid[randRow][randCol] == blank)
grid[randRow][randCol] = blank
}
if (solve(0, 0)) printResult()
else println("No solution")
} |
Perfect shuffle | Kotlin | 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:
::: 7 8 9 J Q K-7 8 9 J Q K-7 J 8 Q 9 K
When 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:
::::: {| style="border-spacing:0.5em 0;border-collapse:separate;margin:0 1em;text-align:right"
|-
| ''original:'' ||
1
2
3
4
5
6
7
8
|-
| ''after 1st shuffle:'' ||
1
5
2
6
3
7
4
8
|-
| ''after 2nd shuffle:'' ||
1
3
5
7
2
4
6
8
|-
| ''after 3rd shuffle:'' ||
1
2
3
4
5
6
7
8
|}
'''''The Task'''''
# Write a function that can perform a perfect shuffle on an even-sized list of values.
# 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.
#* 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.
#* Print out the resulting shuffle counts, to demonstrate that your program passes the test-cases.
'''''Test Cases'''''
::::: {| class="wikitable"
|-
! input ''(deck size)'' !! output ''(number of shuffles required)''
|-
| 8 || 3
|-
| 24 || 11
|-
| 52 || 8
|-
| 100 || 30
|-
| 1020 || 1018
|-
| 1024 || 10
|-
| 10000 || 300
|}
| // version 1.1.2
fun areSame(a: IntArray, b: IntArray): Boolean {
for (i in 0 until a.size) if (a[i] != b[i]) return false
return true
}
fun perfectShuffle(a: IntArray): IntArray {
var b = IntArray(a.size)
val hSize = a.size / 2
for (i in 0 until hSize) b[i * 2] = a[i]
var j = 1
for (i in hSize until a.size) {
b[j] = a[i]
j += 2
}
return b
}
fun countShuffles(a: IntArray): Int {
require(a.size >= 2 && a.size % 2 == 0)
var b = a
var count = 0
while (true) {
val c = perfectShuffle(b)
count++
if (areSame(a, c)) return count
b = c
}
}
fun main(args: Array<String>) {
println("Deck size Num shuffles")
println("--------- ------------")
val sizes = intArrayOf(8, 24, 52, 100, 1020, 1024, 10000)
for (size in sizes) {
val a = IntArray(size) { it }
val count = countShuffles(a)
println("${"%-9d".format(size)} $count")
}
} |
Perfect totient numbers | Kotlin from Go | Generate and show here, the first twenty Perfect totient numbers.
;Related task:
::* [[Totient function]]
;Also see:
::* the OEIS entry for perfect totient numbers.
::* mrob list of the first 54
| // Version 1.3.21
fun totient(n: Int): Int {
var tot = n
var nn = n
var i = 2
while (i * i <= nn) {
if (nn % i == 0) {
while (nn % i == 0) nn /= i
tot -= tot / i
}
if (i == 2) i = 1
i += 2
}
if (nn > 1) tot -= tot / nn
return tot
}
fun main() {
val perfect = mutableListOf<Int>()
var n = 1
while (perfect.size < 20) {
var tot = n
var sum = 0
while (tot != 1) {
tot = totient(tot)
sum += tot
}
if (sum == n) perfect.add(n)
n += 2
}
println("The first 20 perfect totient numbers are:")
println(perfect)
} |
Perlin noise | Kotlin from Java | The '''computer graphics, most notably to procedurally generate textures or heightmaps.
The 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.
Either 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.
''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.''
| // version 1.1.3
object Perlin {
private val permutation = intArrayOf(
151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225,
140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148,
247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32,
57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175,
74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122,
60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54,
65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169,
200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212,
207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213,
119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9,
129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104,
218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241,
81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157,
184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93,
222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180
)
private val p = IntArray(512) {
if (it < 256) permutation[it] else permutation[it - 256]
}
fun noise(x: Double, y: Double, z: Double): Double {
// Find unit cube that contains point
val xi = Math.floor(x).toInt() and 255
val yi = Math.floor(y).toInt() and 255
val zi = Math.floor(z).toInt() and 255
// Find relative x, y, z of point in cube
val xx = x - Math.floor(x)
val yy = y - Math.floor(y)
val zz = z - Math.floor(z)
// Compute fade curves for each of xx, yy, zz
val u = fade(xx)
val v = fade(yy)
val w = fade(zz)
// Hash co-ordinates of the 8 cube corners
// and add blended results from 8 corners of cube
val a = p[xi] + yi
val aa = p[a] + zi
val ab = p[a + 1] + zi
val b = p[xi + 1] + yi
val ba = p[b] + zi
val bb = p[b + 1] + zi
return lerp(w, lerp(v, lerp(u, grad(p[aa], xx, yy, zz),
grad(p[ba], xx - 1, yy, zz)),
lerp(u, grad(p[ab], xx, yy - 1, zz),
grad(p[bb], xx - 1, yy - 1, zz))),
lerp(v, lerp(u, grad(p[aa + 1], xx, yy, zz - 1),
grad(p[ba + 1], xx - 1, yy, zz - 1)),
lerp(u, grad(p[ab + 1], xx, yy - 1, zz - 1),
grad(p[bb + 1], xx - 1, yy - 1, zz - 1))))
}
private fun fade(t: Double) = t * t * t * (t * (t * 6 - 15) + 10)
private fun lerp(t: Double, a: Double, b: Double) = a + t * (b - a)
private fun grad(hash: Int, x: Double, y: Double, z: Double): Double {
// Convert low 4 bits of hash code into 12 gradient directions
val h = hash and 15
val u = if (h < 8) x else y
val v = if (h < 4) y else if (h == 12 || h == 14) x else z
return (if ((h and 1) == 0) u else -u) +
(if ((h and 2) == 0) v else -v)
}
}
fun main(args: Array<String>) {
println(Perlin.noise(3.14, 42.0, 7.0))
} |
Permutations/Derangements | Kotlin | A derangement is a permutation of the order of distinct items in which ''no item appears in its original place''.
For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1).
The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''.
There are various ways to calculate !''n''.
;Task:
# Create a named function/method/subroutine/... to generate derangements of the integers ''0..n-1'', (or ''1..n'' if you prefer).
# Generate ''and show'' all the derangements of 4 integers using the above routine.
# Create a function that calculates the subfactorial of ''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.
;Optional stretch goal:
* Calculate !''20''
;Related tasks:
* [[Anagrams/Deranged anagrams]]
* [[Best shuffle]]
* [[Left_factorials]]
| // version 1.1.2
fun <T> permute(input: List<T>): List<List<T>> {
if (input.size == 1) return listOf(input)
val perms = mutableListOf<List<T>>()
val toInsert = input[0]
for (perm in permute(input.drop(1))) {
for (i in 0..perm.size) {
val newPerm = perm.toMutableList()
newPerm.add(i, toInsert)
perms.add(newPerm)
}
}
return perms
}
fun derange(input: List<Int>): List<List<Int>> {
if (input.isEmpty()) return listOf(input)
return permute(input).filter { permutation ->
permutation.filterIndexed { i, index -> i == index }.none()
}
}
fun subFactorial(n: Int): Long =
when (n) {
0 -> 1
1 -> 0
else -> (n - 1) * (subFactorial(n - 1) + subFactorial(n - 2))
}
fun main(args: Array<String>) {
val input = listOf(0, 1, 2, 3)
val derangements = derange(input)
println("There are ${derangements.size} derangements of $input, namely:\n")
derangements.forEach(::println)
println("\nN Counted Calculated")
println("- ------- ----------")
for (n in 0..9) {
val list = List(n) { it }
val counted = derange(list).size
println("%d %-9d %-9d".format(n, counted, subFactorial(n)))
}
println("\n!20 = ${subFactorial(20)}")
} |
Permutations/Rank of a permutation | Kotlin from C | A particular ranking of a permutation associates an integer with a particular ordering of all the permutations of a set of distinct items.
For our purposes the ranking will assign integers 0 .. (n! - 1) to an ordering of all the permutations of the integers 0 .. (n - 1).
For example, the permutations of the digits zero to 3 arranged lexicographically have the following rank:
PERMUTATION RANK
(0, 1, 2, 3) -> 0
(0, 1, 3, 2) -> 1
(0, 2, 1, 3) -> 2
(0, 2, 3, 1) -> 3
(0, 3, 1, 2) -> 4
(0, 3, 2, 1) -> 5
(1, 0, 2, 3) -> 6
(1, 0, 3, 2) -> 7
(1, 2, 0, 3) -> 8
(1, 2, 3, 0) -> 9
(1, 3, 0, 2) -> 10
(1, 3, 2, 0) -> 11
(2, 0, 1, 3) -> 12
(2, 0, 3, 1) -> 13
(2, 1, 0, 3) -> 14
(2, 1, 3, 0) -> 15
(2, 3, 0, 1) -> 16
(2, 3, 1, 0) -> 17
(3, 0, 1, 2) -> 18
(3, 0, 2, 1) -> 19
(3, 1, 0, 2) -> 20
(3, 1, 2, 0) -> 21
(3, 2, 0, 1) -> 22
(3, 2, 1, 0) -> 23
Algorithms 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).
One 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.
A question on the Stack Overflow site asked how to generate one million random and indivudual permutations of 144 items.
;Task:
# Create a function to generate a permutation from a rank.
# Create the inverse function that given the permutation generates its rank.
# Show that for n=3 the two functions are indeed inverses of each other.
# Compute and show here 4 random, individual, samples of permutations of 12 objects.
;Stretch goal:
* State how reasonable it would be to use your program to address the limits of the Stack Overflow question.
;References:
# Ranking and Unranking Permutations in Linear Time by Myrvold & Ruskey. (Also available via Google here).
# Ranks on the DevData site.
# Another answer on Stack Overflow to a different question that explains its algorithm in detail.
;Related tasks:
#[[Factorial_base_numbers_indexing_permutations_of_a_collection]]
| // version 1.1.2
import java.util.Random
fun IntArray.swap(i: Int, j: Int) {
val temp = this[i]
this[i] = this[j]
this[j] = temp
}
tailrec fun mrUnrank1(rank: Int, n: Int, vec: IntArray) {
if (n < 1) return
val q = rank / n
val r = rank % n
vec.swap(r, n - 1)
mrUnrank1(q, n - 1, vec)
}
fun mrRank1(n: Int, vec: IntArray, inv: IntArray): Int {
if (n < 2) return 0
val s = vec[n - 1]
vec.swap(n - 1, inv[n - 1])
inv.swap(s, n - 1)
return s + n * mrRank1(n - 1, vec, inv)
}
fun getPermutation(rank: Int, n: Int, vec: IntArray) {
for (i in 0 until n) vec[i] = i
mrUnrank1(rank, n, vec)
}
fun getRank(n: Int, vec: IntArray): Int {
val v = IntArray(n)
val inv = IntArray(n)
for (i in 0 until n) {
v[i] = vec[i]
inv[vec[i]] = i
}
return mrRank1(n, v, inv)
}
fun main(args: Array<String>) {
var tv = IntArray(3)
for (r in 0..5) {
getPermutation(r, 3, tv)
System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(3, tv))
}
println()
tv = IntArray(4)
for (r in 0..23) {
getPermutation(r, 4, tv)
System.out.printf("%2d -> %s -> %d\n", r, tv.contentToString(), getRank(4, tv))
}
println()
tv = IntArray(12)
val a = IntArray(4)
val rand = Random()
val fact12 = (2..12).fold(1) { acc, i -> acc * i }
for (i in 0..3) a[i] = rand.nextInt(fact12)
for (r in a) {
getPermutation(r, 12, tv)
System.out.printf("%9d -> %s -> %d\n", r, tv.contentToString(), getRank(12, tv))
}
} |
Permutations by swapping | Kotlin | Generate permutations of n items in which successive permutations differ from each other by the swapping of any two items.
Also 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.
Show the permutations and signs of three items, in order of generation ''here''.
Such data are of use in generating the determinant of a square matrix and any functions created should bear this in mind.
Note: The Steinhaus-Johnson-Trotter algorithm generates successive permutations where ''adjacent'' items are swapped, but from this discussion adjacency is not a requirement.
;References:
* Steinhaus-Johnson-Trotter algorithm
* Johnson-Trotter Algorithm Listing All Permutations
* Heap's algorithm
* Tintinnalogia
;Related tasks:
* [[Matrix arithmetic]
* [[Gray code]]
| // version 1.1.2
fun johnsonTrotter(n: Int): Pair<List<IntArray>, List<Int>> {
val p = IntArray(n) { it } // permutation
val q = IntArray(n) { it } // inverse permutation
val d = IntArray(n) { -1 } // direction = 1 or -1
var sign = 1
val perms = mutableListOf<IntArray>()
val signs = mutableListOf<Int>()
fun permute(k: Int) {
if (k >= n) {
perms.add(p.copyOf())
signs.add(sign)
sign *= -1
return
}
permute(k + 1)
for (i in 0 until k) {
val z = p[q[k] + d[k]]
p[q[k]] = z
p[q[k] + d[k]] = k
q[z] = q[k]
q[k] += d[k]
permute(k + 1)
}
d[k] *= -1
}
permute(0)
return perms to signs
}
fun printPermsAndSigns(perms: List<IntArray>, signs: List<Int>) {
for ((i, perm) in perms.withIndex()) {
println("${perm.contentToString()} -> sign = ${signs[i]}")
}
}
fun main(args: Array<String>) {
val (perms, signs) = johnsonTrotter(3)
printPermsAndSigns(perms, signs)
println()
val (perms2, signs2) = johnsonTrotter(4)
printPermsAndSigns(perms2, signs2)
} |
Phrase reversals | Kotlin | Given a string of space separated words containing the following phrase:
rosetta code phrase reversal
:# Reverse the characters of the string.
:# Reverse the characters of each individual word in the string, maintaining original word order within the string.
:# Reverse the order of each word of the string, maintaining the order of characters in each word.
Show your output here.
| // version 1.0.6
fun reverseEachWord(s: String) = s.split(" ").map { it.reversed() }.joinToString(" ")
fun main(args: Array<String>) {
val original = "rosetta code phrase reversal"
val reversed = original.reversed()
println("Original string => $original")
println("Reversed string => $reversed")
println("Reversed words => ${reverseEachWord(original)}")
println("Reversed order => ${reverseEachWord(reversed)}")
} |
Pig the dice game | Kotlin | The game of Pig is a multiplayer game played with a single six-sided die. The
object of the game is to reach '''100''' points or more.
Play is taken in turns. On each person's turn that person has the option of either:
:# '''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.
:# '''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.
;Task:
Create a program to score for, and simulate dice throws for, a two-person game.
;Related task:
* [[Pig the dice game/Player]]
| // version 1.1.2
fun main(Args: Array<String>) {
print("Player 1 - Enter your name : ")
val name1 = readLine()!!.trim().let { if (it == "") "PLAYER 1" else it.toUpperCase() }
print("Player 2 - Enter your name : ")
val name2 = readLine()!!.trim().let { if (it == "") "PLAYER 2" else it.toUpperCase() }
val names = listOf(name1, name2)
val r = java.util.Random()
val totals = intArrayOf(0, 0)
var player = 0
while (true) {
println("\n${names[player]}")
println(" Your total score is currently ${totals[player]}")
var score = 0
while (true) {
print(" Roll or Hold r/h : ")
val rh = readLine()!![0].toLowerCase()
if (rh == 'h') {
totals[player] += score
println(" Your total score is now ${totals[player]}")
if (totals[player] >= 100) {
println(" So, ${names[player]}, YOU'VE WON!")
return
}
player = if (player == 0) 1 else 0
break
}
if (rh != 'r') {
println(" Must be 'r'or 'h', try again")
continue
}
val dice = 1 + r.nextInt(6)
println(" You have thrown a $dice")
if (dice == 1) {
println(" Sorry, your score for this round is now 0")
println(" Your total score remains at ${totals[player]}")
player = if (player == 0) 1 else 0
break
}
score += dice
println(" Your score for the round is now $score")
}
}
} |
Plasma effect | Kotlin from Java | 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.
;Task
Create a plasma effect.
;See also
* Computer Graphics Tutorial (lodev.org)
* Plasma (bidouille.org)
| // version 1.1.2
import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.*
class PlasmaEffect : JPanel() {
private val plasma: Array<FloatArray>
private var hueShift = 0.0f
private val img: BufferedImage
init {
val dim = Dimension(640, 640)
preferredSize = dim
background = Color.white
img = BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB)
plasma = createPlasma(dim.height, dim.width)
// animate about 24 fps and shift hue value with every frame
Timer(42) {
hueShift = (hueShift + 0.02f) % 1
repaint()
}.start()
}
private fun createPlasma(w: Int, h: Int): Array<FloatArray> {
val buffer = Array(h) { FloatArray(w) }
for (y in 0 until h)
for (x in 0 until w) {
var value = Math.sin(x / 16.0)
value += Math.sin(y / 8.0)
value += Math.sin((x + y) / 16.0)
value += Math.sin(Math.sqrt((x * x + y * y).toDouble()) / 8.0)
value += 4.0 // shift range from -4 .. 4 to 0 .. 8
value /= 8.0 // bring range down to 0 .. 1
if (value < 0.0 || value > 1.0) throw RuntimeException("Hue value out of bounds")
buffer[y][x] = value.toFloat()
}
return buffer
}
private fun drawPlasma(g: Graphics2D) {
val h = plasma.size
val w = plasma[0].size
for (y in 0 until h)
for (x in 0 until w) {
val hue = hueShift + plasma[y][x] % 1
img.setRGB(x, y, Color.HSBtoRGB(hue, 1.0f, 1.0f))
}
g.drawImage(img, 0, 0, null)
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawPlasma(g);
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Plasma Effect"
f.isResizable = false
f.add(PlasmaEffect(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = true
}
} |
Playfair cipher | Kotlin from FreeBASIC | Implement a Playfair cipher for encryption and decryption.
The user must be able to choose '''J''' = '''I''' or no '''Q''' in the alphabet.
The output of the encrypted and decrypted message must be in capitalized digraphs, separated by spaces.
;Output example:
HI DE TH EG OL DI NT HE TR EX ES TU MP
| // version 1.0.5-2
enum class PlayfairOption {
NO_Q,
I_EQUALS_J
}
class Playfair(keyword: String, val pfo: PlayfairOption) {
private val table: Array<CharArray> = Array(5, { CharArray(5) }) // 5 x 5 char array
init {
// build table
val used = BooleanArray(26) // all elements false
if (pfo == PlayfairOption.NO_Q)
used[16] = true // Q used
else
used[9] = true // J used
val alphabet = keyword.toUpperCase() + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var i = 0
var j = 0
var c: Char
var d: Int
for (k in 0 until alphabet.length) {
c = alphabet[k]
if (c !in 'A'..'Z') continue
d = c.toInt() - 65
if (!used[d]) {
table[i][j] = c
used[d] = true
if (++j == 5) {
if (++i == 5) break // table has been filled
j = 0
}
}
}
}
private fun getCleanText(plainText: String): String {
val plainText2 = plainText.toUpperCase() // ensure everything is upper case
// get rid of any non-letters and insert X between duplicate letters
var cleanText = ""
var prevChar = '\u0000' // safe to assume null character won't be present in plainText
var nextChar: Char
for (i in 0 until plainText2.length) {
nextChar = plainText2[i]
// It appears that Q should be omitted altogether if NO_Q option is specified - we assume so anyway
if (nextChar !in 'A'..'Z' || (nextChar == 'Q' && pfo == PlayfairOption.NO_Q)) continue
// If I_EQUALS_J option specified, replace J with I
if (nextChar == 'J' && pfo == PlayfairOption.I_EQUALS_J) nextChar = 'I'
if (nextChar != prevChar)
cleanText += nextChar
else
cleanText += "X" + nextChar
prevChar = nextChar
}
val len = cleanText.length
if (len % 2 == 1) { // dangling letter at end so add another letter to complete digram
if (cleanText[len - 1] != 'X')
cleanText += 'X'
else
cleanText += 'Z'
}
return cleanText
}
private fun findChar(c: Char): Pair<Int, Int> {
for (i in 0..4)
for (j in 0..4)
if (table[i][j] == c) return Pair(i, j)
return Pair(-1, -1)
}
fun encode(plainText: String): String {
val cleanText = getCleanText(plainText)
var cipherText = ""
val length = cleanText.length
for (i in 0 until length step 2) {
val (row1, col1) = findChar(cleanText[i])
val (row2, col2) = findChar(cleanText[i + 1])
cipherText += when {
row1 == row2 -> table[row1][(col1 + 1) % 5].toString() + table[row2][(col2 + 1) % 5]
col1 == col2 -> table[(row1 + 1) % 5][col1].toString() + table[(row2 + 1) % 5][col2]
else -> table[row1][col2].toString() + table[row2][col1]
}
if (i < length - 1) cipherText += " "
}
return cipherText
}
fun decode(cipherText: String): String {
var decodedText = ""
val length = cipherText.length
for (i in 0 until length step 3) { // cipherText will include spaces so we need to skip them
val (row1, col1) = findChar(cipherText[i])
val (row2, col2) = findChar(cipherText[i + 1])
decodedText += when {
row1 == row2 -> table[row1][if (col1 > 0) col1 - 1 else 4].toString() + table[row2][if (col2 > 0) col2 - 1 else 4]
col1 == col2 -> table[if (row1 > 0) row1- 1 else 4][col1].toString() + table[if (row2 > 0) row2 - 1 else 4][col2]
else -> table[row1][col2].toString() + table[row2][col1]
}
if (i < length - 1) decodedText += " "
}
return decodedText
}
fun printTable() {
println("The table to be used is :\n")
for (i in 0..4) {
for (j in 0..4) print(table[i][j] + " ")
println()
}
}
}
fun main(args: Array<String>) {
print("Enter Playfair keyword : ")
val keyword: String = readLine()!!
var ignoreQ: String
do {
print("Ignore Q when buiding table y/n : ")
ignoreQ = readLine()!!.toLowerCase()
}
while (ignoreQ != "y" && ignoreQ != "n")
val pfo = if (ignoreQ == "y") PlayfairOption.NO_Q else PlayfairOption.I_EQUALS_J
val playfair = Playfair(keyword, pfo)
playfair.printTable()
print("\nEnter plain text : ")
val plainText: String = readLine()!!
val encodedText = playfair.encode(plainText)
println("\nEncoded text is : $encodedText")
val decodedText = playfair.decode(encodedText)
println("Decoded text is : $decodedText")
} |
Plot coordinate pairs | Kotlin from Groovy | Plot a function represented as x, y numerical arrays.
Post the resulting image for the following input arrays (taken from Python's Example section on ''Time a function''):
x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};
This task is intended as a subtask for [[Measure relative performance of sorting algorithms implementations]].
| // Version 1.2.31
import org.jfree.chart.ChartFactory
import org.jfree.chart.ChartPanel
import org.jfree.data.xy.XYSeries
import org.jfree.data.xy.XYSeriesCollection
import org.jfree.chart.plot.PlotOrientation
import javax.swing.JFrame
import javax.swing.SwingUtilities
import java.awt.BorderLayout
fun main(args: Array<String>) {
val x = intArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
val y = doubleArrayOf(
2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0
)
val series = XYSeries("plots")
(0 until x.size).forEach { series.add(x[it], y[it]) }
val labels = arrayOf("Plot Demo", "X", "Y")
val data = XYSeriesCollection(series)
val options = booleanArrayOf(false, true, false)
val orient = PlotOrientation.VERTICAL
val chart = ChartFactory.createXYLineChart(
labels[0], labels[1], labels[2], data, orient, options[0], options[1], options[2]
)
val chartPanel = ChartPanel(chart)
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(chartPanel, BorderLayout.CENTER)
title = "Plot coordinate pairs"
isResizable = false
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
Poker hand analyser | Kotlin | Create a program to parse a single five card poker hand and rank it according to this list of poker hands.
A poker hand is specified as a space separated list of five playing cards.
Each input card has two characters indicating face and suit.
;Example:
::::'''2d''' (two of diamonds).
Faces are: '''a''', '''2''', '''3''', '''4''', '''5''', '''6''', '''7''', '''8''', '''9''', '''10''', '''j''', '''q''', '''k'''
Suits are: '''h''' (hearts), '''d''' (diamonds), '''c''' (clubs), and '''s''' (spades), or
alternatively, the unicode card-suit characters:
Duplicate cards are illegal.
The program should analyze a single hand and produce one of the following outputs:
straight-flush
four-of-a-kind
full-house
flush
straight
three-of-a-kind
two-pair
one-pair
high-card
invalid
;Examples:
2 2 2 k q: three-of-a-kind
2 5 7 8 9: high-card
a 2 3 4 5: straight
2 3 2 3 3: full-house
2 7 2 3 3: two-pair
2 7 7 7 7: four-of-a-kind
10 j q k a: straight-flush
4 4 k 5 10: one-pair
q 10 7 6 q: invalid
The programs output for the above examples should be displayed here on this page.
;Extra credit:
# use the playing card characters introduced with Unicode 6.0 (U+1F0A1 - U+1F0DE).
# allow two jokers
::* use the symbol '''joker'''
::* duplicates would be allowed (for jokers only)
::* five-of-a-kind would then be the highest hand
;More extra credit examples:
joker 2 2 k q: three-of-a-kind
joker 5 7 8 9: straight
joker 2 3 4 5: straight
joker 3 2 3 3: four-of-a-kind
joker 7 2 3 3: three-of-a-kind
joker 7 7 7 7: five-of-a-kind
joker j q k A: straight-flush
joker 4 k 5 10: one-pair
joker k 7 6 4: flush
joker 2 joker 4 5: straight
joker Q joker A 10: straight
joker Q joker A 10: straight-flush
joker 2 2 joker q: four-of-a-kind
;Related tasks:
* [[Playing cards]]
* [[Card shuffles]]
* [[Deal cards_for_FreeCell]]
* [[War Card_Game]]
* [[Go Fish]]
| // version 1.1.2
class Card(val face: Int, val suit: Char)
const val FACES = "23456789tjqka"
const val SUITS = "shdc"
fun isStraight(cards: List<Card>): Boolean {
val sorted = cards.sortedBy { it.face }
if (sorted[0].face + 4 == sorted[4].face) return true
if (sorted[4].face == 14 && sorted[0].face == 2 && sorted[3].face == 5) return true
return false
}
fun isFlush(cards: List<Card>): Boolean {
val suit = cards[0].suit
if (cards.drop(1).all { it.suit == suit }) return true
return false
}
fun analyzeHand(hand: String): String {
val h = hand.toLowerCase()
val split = h.split(' ').filterNot { it == "" }.distinct()
if (split.size != 5) return "invalid"
val cards = mutableListOf<Card>()
for (s in split) {
if (s.length != 2) return "invalid"
val fIndex = FACES.indexOf(s[0])
if (fIndex == -1) return "invalid"
val sIndex = SUITS.indexOf(s[1])
if (sIndex == -1) return "invalid"
cards.add(Card(fIndex + 2, s[1]))
}
val groups = cards.groupBy { it.face }
when (groups.size) {
2 -> {
if (groups.any { it.value.size == 4 }) return "four-of-a-kind"
return "full-house"
}
3 -> {
if (groups.any { it.value.size == 3 }) return "three-of-a-kind"
return "two-pair"
}
4 -> return "one-pair"
else -> {
val flush = isFlush(cards)
val straight = isStraight(cards)
when {
flush && straight -> return "straight-flush"
flush -> return "flush"
straight -> return "straight"
else -> return "high-card"
}
}
}
}
fun main(args: Array<String>) {
val hands = arrayOf(
"2h 2d 2c kc qd",
"2h 5h 7d 8c 9s",
"ah 2d 3c 4c 5d",
"2h 3h 2d 3c 3d",
"2h 7h 2d 3c 3d",
"2h 7h 7d 7c 7s",
"th jh qh kh ah",
"4h 4s ks 5d ts",
"qc tc 7c 6c 4c",
"ah ah 7c 6c 4c"
)
for (hand in hands) {
println("$hand: ${analyzeHand(hand)}")
}
} |
Polyspiral | Kotlin from Java | 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.
;Task
Animate 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.
If animation is not practical in your programming environment, you may show a single frame instead.
;Pseudo code
set incr to 0.0
// animation loop
WHILE true
incr = (incr + 0.05) MOD 360
x = width / 2
y = height / 2
length = 5
angle = incr
// spiral loop
FOR 1 TO 150
drawline
change direction by angle
length = length + 3
angle = (angle + incr) MOD 360
ENDFOR
| // version 1.1.0
import java.awt.*
import java.awt.event.ActionEvent
import javax.swing.*
class PolySpiral() : JPanel() {
private var inc = 0.0
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(40) {
inc = (inc + 0.05) % 360.0
repaint()
}.start()
}
private fun drawSpiral(g: Graphics2D, length: Int, angleIncrement: Double) {
var x1 = width / 2.0
var y1 = height / 2.0
var len = length
var angle = angleIncrement
for (i in 0 until 150) {
g.setColor(Color.getHSBColor(i / 150f, 1.0f, 1.0f))
val x2 = x1 + Math.cos(angle) * len
val y2 = y1 - Math.sin(angle) * len
g.drawLine(x1.toInt(), y1.toInt(), x2.toInt(), y2.toInt())
x1 = x2
y1 = y2
len += 3
angle = (angle + angleIncrement) % (Math.PI * 2.0)
}
}
override protected fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
drawSpiral(g, 5, Math.toRadians(inc))
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "PolySpiral"
f.setResizable(true)
f.add(PolySpiral(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.setVisible(true)
}
} |
Population count | Kotlin | The ''population count'' is the number of '''1'''s (ones) in the binary representation of a non-negative integer.
''Population count'' is also known as:
::::* ''pop count''
::::* ''popcount''
::::* ''sideways sum''
::::* ''bit summation''
::::* ''Hamming weight''
For example, '''5''' (which is '''101''' in binary) has a population count of '''2'''.
''Evil numbers'' are non-negative integers that have an ''even'' population count.
''Odious numbers'' are positive integers that have an ''odd'' population count.
;Task:
* write a function (or routine) to return the population count of a non-negative integer.
* all computation of the lists below should start with '''0''' (zero indexed).
:* display the ''pop count'' of the 1st thirty powers of '''3''' ('''30''', '''31''', '''32''', '''33''', '''34''', '''329''').
:* display the 1st thirty ''evil'' numbers.
:* display the 1st thirty ''odious'' numbers.
* 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.
;See also
* The On-Line Encyclopedia of Integer Sequences: A000120 population count.
* The On-Line Encyclopedia of Integer Sequences: A000069 odious numbers.
* The On-Line Encyclopedia of Integer Sequences: A001969 evil numbers.
| // version 1.0.6
fun popCount(n: Long) = when {
n < 0L -> throw IllegalArgumentException("n must be non-negative")
else -> java.lang.Long.bitCount(n)
}
fun main(args: Array<String>) {
println("The population count of the first 30 powers of 3 are:")
var pow3 = 1L
for (i in 1..30) {
print("${popCount(pow3)} ")
pow3 *= 3L
}
println("\n")
println("The first thirty evil numbers are:")
var count = 0
var i = 0
while (true) {
val pc = popCount(i.toLong())
if (pc % 2 == 0) {
print("$i ")
if (++count == 30) break
}
i++
}
println("\n")
println("The first thirty odious numbers are:")
count = 0
i = 1
while (true) {
val pc = popCount(i.toLong())
if (pc % 2 == 1) {
print("$i ")
if (++count == 30) break
}
i++
}
println()
} |
Pragmatic directives | Kotlin | 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).
;Task:
List 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.
| // version 1.0.6
@Suppress("UNUSED_VARIABLE")
fun main(args: Array<String>) {
val s = "To be suppressed"
} |
Priority queue | Kotlin from Java | 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.
;Task:
Create a priority queue. The queue must support at least two operations:
:# Insertion. An element is added to the queue with a priority (a numeric value).
:# Top item removal. Deletes the element or one of the elements with the current top priority and return it.
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
To test your implementation, insert a number of elements into the queue, each with some random priority.
Then dequeue them sequentially; now the elements should be sorted by priority.
You can use the following task/priority items as input data:
'''Priority''' '''Task'''
---------- ----------------
3 Clear drains
4 Feed cat
5 Make tea
1 Solve RC tasks
2 Tax return
The 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.
You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
| import java.util.PriorityQueue
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
override fun compareTo(other: Task) = when {
priority < other.priority -> -1
priority > other.priority -> 1
else -> 0
}
}
private infix fun String.priority(priority: Int) = Task(priority, this)
fun main(args: Array<String>) {
val q = PriorityQueue(listOf("Clear drains" priority 3,
"Feed cat" priority 4,
"Make tea" priority 5,
"Solve RC tasks" priority 1,
"Tax return" priority 2))
while (q.any()) println(q.remove())
} |
Pseudo-random numbers/Combined recursive generator MRG32k3a | Kotlin from C++ | MRG32k3a Combined recursive generator (pseudo-code):
/* Constants */
/* First generator */
a1 = [0, 1403580, -810728]
m1 = 2**32 - 209
/* Second Generator */
a2 = [527612, 0, -1370589]
m2 = 2**32 - 22853
d = m1 + 1
class MRG32k3a
x1 = [0, 0, 0] /* list of three last values of gen #1 */
x2 = [0, 0, 0] /* list of three last values of gen #2 */
method seed(u64 seed_state)
assert seed_state in range >0 and < d
x1 = [seed_state, 0, 0]
x2 = [seed_state, 0, 0]
end method
method next_int()
x1i = (a1[0]*x1[0] + a1[1]*x1[1] + a1[2]*x1[2]) mod m1
x2i = (a2[0]*x2[0] + a2[1]*x2[1] + a2[2]*x2[2]) mod m2
x1 = [x1i, x1[0], x1[1]] /* Keep last three */
x2 = [x2i, x2[0], x2[1]] /* Keep last three */
z = (x1i - x2i) % m1
answer = (z + 1)
return answer
end method
method next_float():
return float next_int() / d
end method
end class
:MRG32k3a Use:
random_gen = instance MRG32k3a
random_gen.seed(1234567)
print(random_gen.next_int()) /* 1459213977 */
print(random_gen.next_int()) /* 2827710106 */
print(random_gen.next_int()) /* 4245671317 */
print(random_gen.next_int()) /* 3877608661 */
print(random_gen.next_int()) /* 2595287583 */
;Task
* Generate a class/set of functions that generates pseudo-random
numbers as shown above.
* Show that the first five integers generated with the seed `1234567`
are as shown above
* Show that for an initial seed of '987654321' the counts of 100_000
repetitions of
floor(random_gen.next_float() * 5)
Is as follows:
0: 20002, 1: 20060, 2: 19948, 3: 20059, 4: 19931
* Show your output here, on this page.
| import kotlin.math.floor
fun mod(x: Long, y: Long): Long {
val m = x % y
return if (m < 0) {
if (y < 0) {
m - y
} else {
m + y
}
} else m
}
class RNG {
// first generator
private val a1 = arrayOf(0L, 1403580L, -810728L)
private val m1 = (1L shl 32) - 209
private var x1 = arrayOf(0L, 0L, 0L)
// second generator
private val a2 = arrayOf(527612L, 0L, -1370589L)
private val m2 = (1L shl 32) - 22853
private var x2 = arrayOf(0L, 0L, 0L)
private val d = m1 + 1
fun seed(state: Long) {
x1 = arrayOf(state, 0, 0)
x2 = arrayOf(state, 0, 0)
}
fun nextInt(): Long {
val x1i = mod(a1[0] * x1[0] + a1[1] * x1[1] + a1[2] * x1[2], m1)
val x2i = mod(a2[0] * x2[0] + a2[1] * x2[1] + a2[2] * x2[2], m2)
val z = mod(x1i - x2i, m1)
// keep last three values of the first generator
x1 = arrayOf(x1i, x1[0], x1[1])
// keep last three values of the second generator
x2 = arrayOf(x2i, x2[0], x2[1])
return z + 1
}
fun nextFloat(): Double {
return nextInt().toDouble() / d
}
}
fun main() {
val rng = RNG()
rng.seed(1234567)
println(rng.nextInt())
println(rng.nextInt())
println(rng.nextInt())
println(rng.nextInt())
println(rng.nextInt())
println()
val counts = IntArray(5)
rng.seed(987654321)
for (i in 0 until 100_000) {
val v = floor((rng.nextFloat() * 5.0)).toInt()
counts[v]++
}
for (iv in counts.withIndex()) {
println("${iv.index}: ${iv.value}")
}
} |
Pseudo-random numbers/PCG32 | Kotlin from C++ | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
:'''|''' Bitwise or operator
::https://en.wikipedia.org/wiki/Bitwise_operation#OR
::Bitwise comparison gives 1 if any of corresponding bits are 1
:::E.g Binary 00110101 '''|''' Binary 00110011 == Binary 00110111
;PCG32 Generator (pseudo-code):
PCG32 has two unsigned 64-bit integers of internal state:
# '''state''': All 2**64 values may be attained.
# '''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).
Values of sequence allow 2**63 ''different'' sequences of random numbers from the same state.
The algorithm is given 2 U64 inputs called seed_state, and seed_sequence. The algorithm proceeds in accordance with the following pseudocode:-
const N<-U64 6364136223846793005
const inc<-U64 (seed_sequence << 1) | 1
state<-U64 ((inc+seed_state)*N+inc
do forever
xs<-U32 (((state>>18)^state)>>27)
rot<-INT (state>>59)
OUTPUT U32 (xs>>rot)|(xs<<((-rot)&31))
state<-state*N+inc
end do
Note that this an anamorphism - dual to catamorphism, and encoded in some languages as a general higher-order `unfold` function, dual to `fold` or `reduce`.
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers using the above.
* Show that the first five integers generated with the seed 42, 54
are: 2707161783 2068313097 3122475824 2211639955 3215226955
* Show that for an initial seed of 987654321, 1 the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20049, 1: 20022, 2: 20115, 3: 19809, 4: 20005
* Show your output here, on this page.
| import kotlin.math.floor
class PCG32 {
private var state = 0x853c49e6748fea9buL
private var inc = 0xda3e39cb94b95bdbuL
fun nextInt(): UInt {
val old = state
state = old * N + inc
val shifted = old.shr(18).xor(old).shr(27).toUInt()
val rot = old.shr(59)
return (shifted shr rot.toInt()) or shifted.shl((rot.inv() + 1u).and(31u).toInt())
}
fun nextFloat(): Double {
return nextInt().toDouble() / (1L shl 32)
}
fun seed(seedState: ULong, seedSequence: ULong) {
state = 0u
inc = (seedSequence shl 1).or(1uL)
nextInt()
state += seedState
nextInt()
}
companion object {
private const val N = 6364136223846793005uL
}
}
fun main() {
val r = PCG32()
r.seed(42u, 54u)
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println(r.nextInt())
println()
val counts = Array(5) { 0 }
r.seed(987654321u, 1u)
for (i in 0 until 100000) {
val j = floor(r.nextFloat() * 5.0).toInt()
counts[j] += 1
}
println("The counts for 100,000 repetitions are:")
for (iv in counts.withIndex()) {
println(" %d : %d".format(iv.index, iv.value))
}
} |
Pseudo-random numbers/Xorshift star | Kotlin from Java | Some definitions to help in the explanation:
:Floor operation
::https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
::Greatest integer less than or equal to a real number.
:Bitwise Logical shift operators (c-inspired)
::https://en.wikipedia.org/wiki/Bitwise_operation#Bit_shifts
::Binary bits of value shifted left or right, with zero bits shifted in where appropriate.
::Examples are shown for 8 bit binary numbers; most significant bit to the left.
:: '''<<''' Logical shift left by given number of bits.
:::E.g Binary 00110101 '''<<''' 2 == Binary 11010100
:: '''>>''' Logical shift right by given number of bits.
:::E.g Binary 00110101 '''>>''' 2 == Binary 00001101
:'''^''' Bitwise exclusive-or operator
::https://en.wikipedia.org/wiki/Exclusive_or
::Bitwise comparison for if bits differ
:::E.g Binary 00110101 '''^''' Binary 00110011 == Binary 00000110
;Xorshift_star Generator (pseudo-code):
/* Let u64 denote an unsigned 64 bit integer type. */
/* Let u32 denote an unsigned 32 bit integer type. */
class Xorshift_star
u64 state /* Must be seeded to non-zero initial value */
u64 const = HEX '2545F4914F6CDD1D'
method seed(u64 num):
state = num
end method
method next_int():
u64 x = state
x = x ^ (x >> 12)
x = x ^ (x << 25)
x = x ^ (x >> 27)
state = x
u32 answer = ((x * const) >> 32)
return answer
end method
method next_float():
return float next_int() / (1 << 32)
end method
end class
:;Xorshift use:
random_gen = instance Xorshift_star
random_gen.seed(1234567)
print(random_gen.next_int()) /* 3540625527 */
print(random_gen.next_int()) /* 2750739987 */
print(random_gen.next_int()) /* 4037983143 */
print(random_gen.next_int()) /* 1993361440 */
print(random_gen.next_int()) /* 3809424708 */
;Task:
* Generate a class/set of functions that generates pseudo-random
numbers as shown above.
* Show that the first five integers genrated with the seed 1234567
are as shown above
* Show that for an initial seed of 987654321, the counts of 100_000 repetitions of
floor(random_gen.next_float() * 5)
:Is as follows:
0: 20103, 1: 19922, 2: 19937, 3: 20031, 4: 20007
* Show your output here, on this page.
| import kotlin.math.floor
class XorShiftStar {
private var state = 0L
fun seed(num: Long) {
state = num
}
fun nextInt(): Int {
var x = state
x = x xor (x ushr 12)
x = x xor (x shl 25)
x = x xor (x ushr 27)
state = x
return (x * MAGIC shr 32).toInt()
}
fun nextFloat(): Float {
return nextInt().toUInt().toFloat() / (1L shl 32)
}
companion object {
private const val MAGIC = 0x2545F4914F6CDD1D
}
}
fun main() {
val rng = XorShiftStar()
rng.seed(1234567)
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println(rng.nextInt().toUInt())
println()
rng.seed(987654321)
val counts = arrayOf(0, 0, 0, 0, 0)
for (i in 1..100000) {
val j = floor(rng.nextFloat() * 5.0).toInt()
counts[j]++
}
for (iv in counts.withIndex()) {
println("${iv.index}: ${iv.value}")
}
} |
Pythagoras tree | Kotlin from Java | 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.
;Task
Construct a Pythagoras tree of order 7 using only vectors (no rotation or trigonometric functions).
;Related tasks
* Fractal tree
| // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import javax.swing.*
class PythagorasTree : JPanel() {
val depthLimit = 7
val hue = 0.15f
init {
preferredSize = Dimension(640, 640)
background = Color.white
}
private fun drawTree(g: Graphics2D, x1: Float, y1: Float,
x2: Float, y2: Float, depth: Int) {
if (depth == depthLimit) return
val dx = x2 - x1
val dy = y1 - y2
val x3 = x2 - dy
val y3 = y2 - dx
val x4 = x1 - dy
val y4 = y1 - dx
val x5 = x4 + 0.5f * (dx - dy)
val y5 = y4 - 0.5f * (dx + dy)
val square = Path2D.Float()
with (square) {
moveTo(x1, y1)
lineTo(x2, y2)
lineTo(x3, y3)
lineTo(x4, y4)
closePath()
}
g.color = Color.getHSBColor(hue + depth * 0.02f, 1.0f, 1.0f)
g.fill(square)
g.color = Color.lightGray
g.draw(square)
val triangle = Path2D.Float()
with (triangle) {
moveTo(x3, y3)
lineTo(x4, y4)
lineTo(x5, y5)
closePath()
}
g.color = Color.getHSBColor(hue + depth * 0.035f, 1.0f, 1.0f)
g.fill(triangle)
g.color = Color.lightGray
g.draw(triangle)
drawTree(g, x4, y4, x5, y5, depth + 1)
drawTree(g, x5, y5, x3, y3, depth + 1)
}
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
drawTree(g as Graphics2D, 275.0f, 500.0f, 375.0f, 500.0f, 0)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with (f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Pythagoras Tree"
isResizable = false
add(PythagorasTree(), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null);
setVisible(true)
}
}
} |
Pythagorean quadruples | Kotlin | One form of '''Pythagorean quadruples''' is (for positive integers '''a''', '''b''', '''c''', and '''d'''):
:::::::: a2 + b2 + c2 = d2
An example:
:::::::: 22 + 32 + 62 = 72
::::: which is:
:::::::: 4 + 9 + 36 = 49
;Task:
For positive integers up '''2,200''' (inclusive), for all values of '''a''',
'''b''', '''c''', and '''d''',
find (and show here) those values of '''d''' that ''can't'' be represented.
Show the values of '''d''' on one line of output (optionally with a title).
;Related tasks:
* [[Euler's sum of powers conjecture]].
* [[Pythagorean triples]].
;Reference:
:* the Wikipedia article: Pythagorean quadruple.
| // version 1.1.3
const val MAX = 2200
const val MAX2 = MAX * MAX - 1
fun main(args: Array<String>) {
val found = BooleanArray(MAX + 1) // all false by default
val p2 = IntArray(MAX + 1) { it * it } // pre-compute squares
// compute all possible positive values of d * d - c * c and map them back to d
val dc = mutableMapOf<Int, MutableList<Int>>()
for (d in 1..MAX) {
for (c in 1 until d) {
val diff = p2[d] - p2[c]
val v = dc[diff]
if (v == null)
dc.put(diff, mutableListOf(d))
else if (d !in v)
v.add(d)
}
}
for (a in 1..MAX) {
for (b in 1..a) {
if ((a and 1) != 0 && (b and 1) != 0) continue
val sum = p2[a] + p2[b]
if (sum > MAX2) continue
val v = dc[sum]
if (v != null) v.forEach { found[it] = true }
}
}
println("The values of d <= $MAX which can't be represented:")
for (i in 1..MAX) if (!found[i]) print("$i ")
println()
} |
Pythagorean triples | Kotlin from Go | A Pythagorean triple is defined as three positive integers (a, b, c) where a < b < c, and a^2+b^2=c^2.
They 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.
Because 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).
Each triple forms the length of the sides of a right triangle, whose perimeter is P=a+b+c.
;Task:
The 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.
;Extra credit:
Deal with large values. Can your program handle a maximum perimeter of 1,000,000? What about 10,000,000? 100,000,000?
Note: 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.
;Related tasks:
* [[Euler's sum of powers conjecture]]
* [[List comprehensions]]
* [[Pythagorean quadruples]]
| // version 1.1.2
var total = 0L
var prim = 0L
var maxPeri = 0L
fun newTri(s0: Long, s1: Long, s2: Long) {
val p = s0 + s1 + s2
if (p <= maxPeri) {
prim++
total += maxPeri / p
newTri( s0 - 2 * s1 + 2 * s2, 2 * s0 - s1 + 2 * s2, 2 * s0 - 2 * s1 + 3 * s2)
newTri( s0 + 2 * s1 + 2 * s2, 2 * s0 + s1 + 2 * s2, 2 * s0 + 2 * s1 + 3 * s2)
newTri(-s0 + 2 * s1 + 2 * s2, -2 * s0 + s1 + 2 * s2, -2 * s0 + 2 * s1 + 3 * s2)
}
}
fun main(args: Array<String>) {
maxPeri = 100
while (maxPeri <= 10_000_000_000L) {
prim = 0
total = 0
newTri(3, 4, 5)
println("Up to $maxPeri: $total triples, $prim primatives")
maxPeri *= 10
}
} |
Quaternion type | Kotlin | complex numbers.
A complex number has a real and complex part, sometimes written as a + bi,
where a and b stand for real numbers, and i stands for the square root of minus 1.
An example of a complex number might be -3 + 2i,
where the real part, a is '''-3.0''' and the complex part, b is '''+2.0'''.
A quaternion has one real part and ''three'' imaginary parts, i, j, and k.
A quaternion might be written as a + bi + cj + dk.
In the quaternion numbering system:
:::* ii = jj = kk = ijk = -1, or more simply,
:::* ii = jj = kk = ijk = -1.
The order of multiplication is important, as, in general, for two quaternions:
:::: q1 and q2: q1q2 q2q1.
An example of a quaternion might be 1 +2i +3j +4k
There is a list form of notation where just the numbers are shown and the imaginary multipliers i, j, and k are assumed by position.
So the example above would be written as (1, 2, 3, 4)
;Task:
Given the three quaternions and their components:
q = (1, 2, 3, 4) = (a, b, c, d)
q1 = (2, 3, 4, 5) = (a1, b1, c1, d1)
q2 = (3, 4, 5, 6) = (a2, b2, c2, d2)
And a wholly real number r = 7.
Create functions (or classes) to perform simple maths with quaternions including computing:
# The norm of a quaternion: = \sqrt{a^2 + b^2 + c^2 + d^2}
# The negative of a quaternion: = (-a, -b, -c, -d)
# The conjugate of a quaternion: = ( a, -b, -c, -d)
# Addition of a real number r and a quaternion q: r + q = q + r = (a+r, b, c, d)
# Addition of two quaternions: q1 + q2 = (a1+a2, b1+b2, c1+c2, d1+d2)
# Multiplication of a real number and a quaternion: qr = rq = (ar, br, cr, dr)
# 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 )
# Show that, for the two quaternions q1 and q2: q1q2 q2q1
If a language has built-in support for quaternions, then use it.
;C.f.:
* [[Vector products]]
* 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.
| // version 1.1.2
data class Quaternion(val a: Double, val b: Double, val c: Double, val d: Double) {
operator fun plus(other: Quaternion): Quaternion {
return Quaternion (this.a + other.a, this.b + other.b,
this.c + other.c, this.d + other.d)
}
operator fun plus(r: Double) = Quaternion(a + r, b, c, d)
operator fun times(other: Quaternion): Quaternion {
return Quaternion(
this.a * other.a - this.b * other.b - this.c * other.c - this.d * other.d,
this.a * other.b + this.b * other.a + this.c * other.d - this.d * other.c,
this.a * other.c - this.b * other.d + this.c * other.a + this.d * other.b,
this.a * other.d + this.b * other.c - this.c * other.b + this.d * other.a
)
}
operator fun times(r: Double) = Quaternion(a * r, b * r, c * r, d * r)
operator fun unaryMinus() = Quaternion(-a, -b, -c, -d)
fun conj() = Quaternion(a, -b, -c, -d)
fun norm() = Math.sqrt(a * a + b * b + c * c + d * d)
override fun toString() = "($a, $b, $c, $d)"
}
// extension functions for Double type
operator fun Double.plus(q: Quaternion) = q + this
operator fun Double.times(q: Quaternion) = q * this
fun main(args: Array<String>) {
val q = Quaternion(1.0, 2.0, 3.0, 4.0)
val q1 = Quaternion(2.0, 3.0, 4.0, 5.0)
val q2 = Quaternion(3.0, 4.0, 5.0, 6.0)
val r = 7.0
println("q = $q")
println("q1 = $q1")
println("q2 = $q2")
println("r = $r\n")
println("norm(q) = ${"%f".format(q.norm())}")
println("-q = ${-q}")
println("conj(q) = ${q.conj()}\n")
println("r + q = ${r + q}")
println("q + r = ${q + r}")
println("q1 + q2 = ${q1 + q2}\n")
println("r * q = ${r * q}")
println("q * r = ${q * r}")
val q3 = q1 * q2
val q4 = q2 * q1
println("q1 * q2 = $q3")
println("q2 * q1 = $q4\n")
println("q1 * q2 != q2 * q1 = ${q3 != q4}")
} |
Quine | Kotlin | A quine is a self-referential program that can,
without any external access, output its own source.
A '''quine''' (named after Willard Van Orman Quine) is also known as:
::* ''self-reproducing automata'' (1972)
::* ''self-replicating program'' or ''self-replicating computer program''
::* ''self-reproducing program'' or ''self-reproducing computer program''
::* ''self-copying program'' or ''self-copying computer program''
It is named after the philosopher and logician
who studied self-reference and quoting in natural language,
as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation."
"Source" has one of two meanings. It can refer to the text-based program source.
For 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.
The 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.
;Task:
Write 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.
There are several difficulties that one runs into when writing a quine, mostly dealing with quoting:
* 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.
** 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.
** 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.
* 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.
** 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.
** Some languages allow you to have a string literal that spans multiple lines, which embeds the newlines into the string without escaping.
** 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.
'''Next to the Quines presented here, many other versions can be found on the Quine page.'''
;Related task:
:* print itself.
| // version 1.1.2
const val F = """// version 1.1.2
const val F = %c%c%c%s%c%c%c
fun main(args: Array<String>) {
System.out.printf(F, 34, 34, 34, F, 34, 34, 34)
}
"""
fun main(args: Array<String>) {
System.out.printf(F, 34, 34, 34, F, 34, 34, 34)
} |
RPG attributes generator | Kotlin | '''RPG''' = Role Playing Game.
You're running a tabletop RPG, and your players are creating characters.
Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma.
One 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.
Some players like to assign values to their attributes in the order they're rolled.
To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied:
* The total of all character attributes must be at least 75.
* At least two of the attributes must be at least 15.
However, this can require a lot of manual dice rolling. A programatic solution would be much faster.
;Task:
Write a program that:
# Generates 4 random, whole values between 1 and 6.
# Saves the sum of the 3 largest values.
# Generates a total of 6 values this way.
# Displays the total, and all 6 values once finished.
* The order in which each value was generated must be preserved.
* The total of all 6 values must be at least 75.
* At least 2 of the values must be 15 or more.
| import kotlin.random.Random
fun main() {
while (true) {
val values = List(6) {
val rolls = generateSequence { 1 + Random.nextInt(6) }.take(4)
rolls.sorted().take(3).sum()
}
val vsum = values.sum()
val vcount = values.count { it >= 15 }
if (vsum < 75 || vcount < 2) continue
println("The 6 random numbers generated are: $values")
println("Their sum is $vsum and $vcount of them are >= 15")
break
}
} |
Ramer-Douglas-Peucker line simplification | Kotlin from C++ | The '''Ramer-Douglas-Peucker''' algorithm is a line simplification algorithm for reducing the number of points used to define its shape.
;Task:
Using the '''Ramer-Douglas-Peucker''' algorithm, simplify the 2D line defined by the points:
(0,0) (1,0.1) (2,-0.1) (3,5) (4,6) (5,7) (6,8.1) (7,9) (8,9) (9,9)
The error threshold to be used is: '''1.0'''.
Display the remaining points here.
;Reference:
:* the Wikipedia article: Ramer-Douglas-Peucker algorithm.
| // version 1.1.0
typealias Point = Pair<Double, Double>
fun perpendicularDistance(pt: Point, lineStart: Point, lineEnd: Point): Double {
var dx = lineEnd.first - lineStart.first
var dy = lineEnd.second - lineStart.second
// Normalize
val mag = Math.hypot(dx, dy)
if (mag > 0.0) { dx /= mag; dy /= mag }
val pvx = pt.first - lineStart.first
val pvy = pt.second - lineStart.second
// Get dot product (project pv onto normalized direction)
val pvdot = dx * pvx + dy * pvy
// Scale line direction vector and substract it from pv
val ax = pvx - pvdot * dx
val ay = pvy - pvdot * dy
return Math.hypot(ax, ay)
}
fun RamerDouglasPeucker(pointList: List<Point>, epsilon: Double, out: MutableList<Point>) {
if (pointList.size < 2) throw IllegalArgumentException("Not enough points to simplify")
// Find the point with the maximum distance from line between start and end
var dmax = 0.0
var index = 0
val end = pointList.size - 1
for (i in 1 until end) {
val d = perpendicularDistance(pointList[i], pointList[0], pointList[end])
if (d > dmax) { index = i; dmax = d }
}
// If max distance is greater than epsilon, recursively simplify
if (dmax > epsilon) {
val recResults1 = mutableListOf<Point>()
val recResults2 = mutableListOf<Point>()
val firstLine = pointList.take(index + 1)
val lastLine = pointList.drop(index)
RamerDouglasPeucker(firstLine, epsilon, recResults1)
RamerDouglasPeucker(lastLine, epsilon, recResults2)
// build the result list
out.addAll(recResults1.take(recResults1.size - 1))
out.addAll(recResults2)
if (out.size < 2) throw RuntimeException("Problem assembling output")
}
else {
// Just return start and end points
out.clear()
out.add(pointList.first())
out.add(pointList.last())
}
}
fun main(args: Array<String>) {
val pointList = listOf(
Point(0.0, 0.0),
Point(1.0, 0.1),
Point(2.0, -0.1),
Point(3.0, 5.0),
Point(4.0, 6.0),
Point(5.0, 7.0),
Point(6.0, 8.1),
Point(7.0, 9.0),
Point(8.0, 9.0),
Point(9.0, 9.0)
)
val pointListOut = mutableListOf<Point>()
RamerDouglasPeucker(pointList, 1.0, pointListOut)
println("Points remaining after simplification:")
for (p in pointListOut) println(p)
} |
Random Latin squares | Kotlin from Go | 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.
For 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.
;Example n=4 randomised Latin square:
0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
;Task:
# Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
# Use the function to generate ''and show here'', two randomly generated squares of size 5.
;Note:
Strict ''uniformity'' in the random generation is a hard problem and '''not''' a requirement of the task.
;Related tasks:
* [[Latin Squares in reduced form/Randomizing using Jacobson and Matthews' Technique]]
* [[Latin Squares in reduced form]]
;Reference:
* Wikipedia: Latin square
* OEIS: A002860
| typealias matrix = MutableList<MutableList<Int>>
fun printSquare(latin: matrix) {
for (row in latin) {
println(row)
}
println()
}
fun latinSquare(n: Int) {
if (n <= 0) {
println("[]")
return
}
val latin = MutableList(n) { MutableList(n) { it } }
// first row
latin[0].shuffle()
// middle row(s)
for (i in 1 until n - 1) {
var shuffled = false
shuffling@
while (!shuffled) {
latin[i].shuffle()
for (k in 0 until i) {
for (j in 0 until n) {
if (latin[k][j] == latin[i][j]) {
continue@shuffling
}
}
}
shuffled = true
}
}
// last row
for (j in 0 until n) {
val used = MutableList(n) { false }
for (i in 0 until n - 1) {
used[latin[i][j]] = true
}
for (k in 0 until n) {
if (!used[k]) {
latin[n - 1][j] = k
break
}
}
}
printSquare(latin)
}
fun main() {
latinSquare(5)
latinSquare(5)
latinSquare(10) // for good measure
} |
Random number generator (device) | Kotlin | If your system has a means to generate random numbers involving not only a software algorithm (like the /dev/urandom devices in Unix), then:
show how to obtain a random 32-bit number from that mechanism.
;Related task
* [[Random_number_generator_(included)]]
| // version 1.1.2
import java.security.SecureRandom
fun main(args: Array<String>) {
val rng = SecureRandom()
val rn1 = rng.nextInt()
val rn2 = rng.nextInt()
val newSeed = rn1.toLong() * rn2
rng.setSeed(newSeed) // reseed using the previous 2 random numbers
println(rng.nextInt()) // get random 32-bit number and print it
} |
Random number generator (included) | Kotlin | The task is to:
: 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.
: If possible, give a link to a wider explanation of the algorithm used.
Note: 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.
The 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.
Note that neither LCGs nor GFSRs should be used for the most demanding applications (cryptography) without additional steps.
| 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
|
Range consolidation | Kotlin | Define a range of numbers '''R''', with bounds '''b0''' and '''b1''' covering all numbers ''between and including both bounds''.
That range can be shown as:
::::::::: '''[b0, b1]'''
:::::::: or equally as:
::::::::: '''[b1, b0]'''
Given two ranges, the act of consolidation between them compares the two ranges:
* If one range covers all of the other then the result is that encompassing range.
* If the ranges touch or intersect then the result is ''one'' new single range covering the overlapping ranges.
* Otherwise the act of consolidation is to return the two non-touching ranges.
Given '''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.
If '''N < 2''' then range consolidation has no strict meaning and the input can be returned.
;Example 1:
: Given the two ranges '''[1, 2.5]''' and '''[3, 4.2]''' then
: there is no common region between the ranges and the result is the same as the input.
;Example 2:
: Given the two ranges '''[1, 2.5]''' and '''[1.8, 4.7]''' then
: there is : an overlap '''[2.5, 1.8]''' between the ranges and
: the result is the single range '''[1, 4.7]'''.
: Note that order of bounds in a range is not (yet) stated.
;Example 3:
: Given the two ranges '''[6.1, 7.2]''' and '''[7.2, 8.3]''' then
: they touch at '''7.2''' and
: the result is the single range '''[6.1, 8.3]'''.
;Example 4:
: Given the three ranges '''[1, 2]''' and '''[4, 8]''' and '''[2, 5]'''
: then there is no intersection of the ranges '''[1, 2]''' and '''[4, 8]'''
: but the ranges '''[1, 2]''' and '''[2, 5]''' overlap and
: consolidate to produce the range '''[1, 5]'''.
: This range, in turn, overlaps the other range '''[4, 8]''', and
: so consolidates to the final output of the single range '''[1, 8]'''.
;Task:
Let a normalized range display show the smaller bound to the left; and show the
range with the smaller lower bound to the left of other ranges when showing multiple ranges.
Output the ''normalized'' result of applying consolidation to these five sets of ranges:
[1.1, 2.2]
[6.1, 7.2], [7.2, 8.3]
[4, 3], [2, 1]
[4, 3], [2, 1], [-1, -2], [3.9, 10]
[1, 3], [-6, -1], [-4, -5], [8, 2], [-6, -6]
Show all output here.
;See also:
* [[Set consolidation]]
* [[Set of real numbers]]
| fun <T> consolidate(ranges: Iterable<ClosedRange<T>>): List<ClosedRange<T>> where T : Comparable<T>
{
return ranges
.sortedWith(compareBy({ it.start }, { it.endInclusive }))
.asReversed()
.fold(mutableListOf<ClosedRange<T>>()) {
consolidatedRanges, range ->
if (consolidatedRanges.isEmpty())
{
consolidatedRanges.add(range)
}
// Keep in mind the reverse-sorting applied above:
// If the end of the current-range is higher, than it must start at a lower value,
else if (range.endInclusive >= consolidatedRanges[0].endInclusive)
{
consolidatedRanges[0] = range
}
else if (range.endInclusive >= consolidatedRanges[0].start)
{
consolidatedRanges[0] = range.start .. consolidatedRanges[0].endInclusive
}
else
{
consolidatedRanges.add(0, range)
}
return@fold consolidatedRanges
}
.toList()
}
// What a bummer! Kotlin's range syntax (a..b) doesn't meet the task requirements when b < b,
// and on the other hand, the syntax for constructing lists, arrays and pairs isn't close enough
// to the range notation. Instead then, here's a *very* naive parser. Don't take it seriously.
val rangeRegex = Regex("""\[(.+),(.+)\]""")
fun parseDoubleRange(rangeStr: String): ClosedFloatingPointRange<Double> {
val parts = rangeRegex
.matchEntire(rangeStr)
?.groupValues
?.drop(1)
?.map { it.toDouble() }
?.sorted()
if (parts == null) throw IllegalArgumentException("Unable to parse range $rangeStr")
return parts[0] .. parts[1]
}
fun serializeRange(range: ClosedRange<*>) = "[${range.start}, ${range.endInclusive}]"
// See above. In practice you'd probably use consolidate directly
fun consolidateDoubleRanges(rangeStrings: Iterable<String>): List<String>
{
return consolidate(rangeStrings.asSequence().map(::parseDoubleRange).toList()).map(::serializeRange)
}
fun main() {
val inputRanges = listOf(
listOf("[1.1, 2.2]"),
listOf("[6.1, 7.2]", "[7.2, 8.3]"),
listOf("[4, 3]", "[2, 1]"),
listOf("[4, 3]", "[2, 1]", "[-1, -2]", "[3.9, 10]"),
listOf("[1, 3]", "[-6, -1]", "[-4, -5]", "[8, 2]", "[-6, -6]")
)
inputRanges.associateBy(Any::toString, ::consolidateDoubleRanges).forEach({ println("${it.key} => ${it.value}") })
} |
Range expansion | Kotlin | {{:Range extraction/Format}}
;Task:
Expand the range description:
-6,-3--1,3-5,7-11,14,15,17-20
Note that the second element above,
is the '''range from minus 3 to ''minus'' 1'''.
;Related task:
* [[Range extraction]]
| // version 1.0.6
fun expandRange(s: String): MutableList<Int> {
val list = mutableListOf<Int>()
val items = s.split(',')
var first: Int
var last: Int
for (item in items) {
val count = item.count { it == '-' }
if (count == 0 || (count == 1 && item[0] == '-'))
list.add(item.toInt())
else {
val items2 = item.split('-')
if (count == 1) {
first = items2[0].toInt()
last = items2[1].toInt()
}
else if (count == 2) {
first = items2[1].toInt() * -1
last = items2[2].toInt()
}
else {
first = items2[1].toInt() * -1
last = items2[3].toInt() * -1
}
for (i in first..last) list.add(i)
}
}
return list
}
fun main(args: Array<String>) {
val s = "-6,-3--1,3-5,7-11,14,15,17-20"
println(expandRange(s))
} |
Range extraction | Kotlin | {{:Range extraction/Format}}
;Task:
* Create a function that takes a list of integers in increasing order and returns a correctly formatted string in the range format.
* 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).
0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39
* Show the output of your program.
;Related task:
* [[Range expansion]]
| // version 1.0.6
fun extractRange(list: List<Int>): String {
if (list.isEmpty()) return ""
val sb = StringBuilder()
var first = list[0]
var prev = first
fun append(index: Int) {
if (first == prev) sb.append(prev)
else if (first == prev - 1) sb.append(first, ",", prev)
else sb.append(first, "-", prev)
if (index < list.size - 1) sb.append(",")
}
for (i in 1 until list.size) {
if (list[i] == prev + 1) prev++
else {
append(i)
first = list[i]
prev = first
}
}
append(list.size - 1)
return sb.toString()
}
fun main(args: Array<String>) {
val list1 = listOf(-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20)
println(extractRange(list1))
println()
val list2 = listOf(0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
37, 38, 39)
println(extractRange(list2))
} |
Rate counter | Kotlin from JavaScript | 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.
Of 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.
Multiple approaches are allowed (even preferable), so long as they can accomplish these goals:
* Run N seconds worth of jobs and/or Y jobs.
* Report at least three distinct times.
Be aware of the precision and accuracy limitations of your timing mechanisms, and document them if you can.
'''See also:''' [[System time]], [[Time a function]]
| // version 1.1.3
typealias Func<T> = (T) -> T
fun cube(n: Int) = n * n * n
fun <T> benchmark(n: Int, func: Func<T>, arg: T): LongArray {
val times = LongArray(n)
for (i in 0 until n) {
val m = System.nanoTime()
func(arg)
times[i] = System.nanoTime() - m
}
return times
}
fun main(args: Array<String>) {
println("\nTimings (nanoseconds) : ")
for (time in benchmark(10, ::cube, 5)) println(time)
} |
Read a specific line from a file | Kotlin | Some languages have special semantics for obtaining a known line number from a file.
;Task:
Demonstrate how to obtain the contents of a specific line within a file.
For 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).
If the file does not contain seven lines, or the seventh line is empty, or too big to be retrieved, output an appropriate message.
If no special semantics are available for obtaining the required line, it is permissible to read line by line.
Note that empty lines are considered and should still be counted.
Also note that for functional languages or languages without variables or storage, it is permissible to output the extracted data to standard output.
| // version 1.1.2
import java.io.File
fun main(args: Array<String>) {
/* The following code reads the whole file into memory
and so should not be used for large files
which should instead be read line by line until the
desired line is reached */
val lines = File("input.txt").readLines()
if (lines.size < 7)
println("There are only ${lines.size} lines in the file")
else {
val line7 = lines[6].trim()
if (line7.isEmpty())
println("The seventh line is empty")
else
println("The seventh line is : $line7")
}
}
/* Note that 'input.txt' contains the eight lines:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
*/ |
Recaman's sequence | Kotlin from Go | The '''Recaman's sequence''' generates Natural numbers.
Starting 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.
If the conditions ''don't'' hold then a(n) = a(n-1) + n.
;Task:
# Generate and show here the first 15 members of the sequence.
# Find and show here, the first duplicated number in the sequence.
# '''Optionally''': Find and show here, how many terms of the sequence are needed until all the integers 0..1000, inclusive, are generated.
;References:
* A005132, The On-Line Encyclopedia of Integer Sequences.
* The Slightly Spooky Recaman Sequence, Numberphile video.
* Recaman's sequence, on Wikipedia.
| // Version 1.2.60
fun main(args: Array<String>) {
val a = mutableListOf(0)
val used = mutableSetOf(0)
val used1000 = mutableSetOf(0)
var foundDup = false
var n = 1
while (n <= 15 || !foundDup || used1000.size < 1001) {
var next = a[n - 1] - n
if (next < 1 || used.contains(next)) next += 2 * n
val alreadyUsed = used.contains(next)
a.add(next)
if (!alreadyUsed) {
used.add(next)
if (next in 0..1000) used1000.add(next)
}
if (n == 14) {
println("The first 15 terms of the Recaman's sequence are: $a")
}
if (!foundDup && alreadyUsed) {
println("The first duplicated term is a[$n] = $next")
foundDup = true
}
if (used1000.size == 1001) {
println("Terms up to a[$n] are needed to generate 0 to 1000")
}
n++
}
} |
Remove lines from a file | Kotlin | Remove a specific line or a number of lines from a file.
This should be implemented as a routine that takes three parameters (filename, starting line, and the number of lines to be removed).
For 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
Empty lines are considered and should still be counted, and if the specified line is empty, it should still be removed.
An appropriate message should appear if an attempt is made to remove lines beyond the end of the file.
| // version 1.1.2
import java.io.File
fun removeLines(fileName: String, startLine: Int, numLines: Int) {
require(!fileName.isEmpty() && startLine >= 1 && numLines >= 1)
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
var lines = f.readLines()
val size = lines.size
if (startLine > size) {
println("The starting line is beyond the length of the file")
return
}
var n = numLines
if (startLine + numLines - 1 > size) {
println("Attempting to remove some lines which are beyond the end of the file")
n = size - startLine + 1
}
lines = lines.take(startLine - 1) + lines.drop(startLine + n - 1)
val text = lines.joinToString(System.lineSeparator())
f.writeText(text)
}
fun printFile(fileName: String, message: String) {
require(!fileName.isEmpty())
val f = File(fileName)
if (!f.exists()) {
println("$fileName does not exist")
return
}
println("\nContents of $fileName $message:\n")
f.forEachLine { println(it) }
}
fun main(args: Array<String>) {
printFile("input.txt", "before removal")
removeLines("input.txt", 2, 3)
printFile("input.txt", "after removal of 3 lines starting from the second")
} |
Rep-string | Kotlin | 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''.
For 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.
Note 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.
;Task:
* 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).
* 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.
* Use the function to indicate the repeating substring if any, in the following:
1001110011
1110111011
0010010010
1010101010
1111111111
0100101101
0100100
101
11
00
1
* Show your output on this page.
| // version 1.0.6
fun repString(s: String): MutableList<String> {
val reps = mutableListOf<String>()
if (s.length < 2) return reps
for (c in s) if (c != '0' && c != '1') throw IllegalArgumentException("Not a binary string")
for (len in 1..s.length / 2) {
val t = s.take(len)
val n = s.length / len
val r = s.length % len
val u = t.repeat(n) + t.take(r)
if (u == s) reps.add(t)
}
return reps
}
fun main(args: Array<String>) {
val strings = listOf(
"1001110011",
"1110111011",
"0010010010",
"1010101010",
"1111111111",
"0100101101",
"0100100",
"101",
"11",
"00",
"1"
)
println("The (longest) rep-strings are:\n")
for (s in strings) {
val reps = repString(s)
val size = reps.size
println("${s.padStart(10)} -> ${if (size > 0) reps[size - 1] else "Not a rep-string"}")
}
} |
Repeat | Kotlin | Write a procedure which accepts as arguments another procedure and a positive integer.
The latter procedure is executed a number of times equal to the accepted integer.
| // version 1.0.6
fun repeat(n: Int, f: () -> Unit) {
for (i in 1..n) {
f()
println(i)
}
}
fun main(args: Array<String>) {
repeat(5) { print("Example ") }
} |
Resistor mesh | Kotlin from C | Given 10x10 grid nodes (as shown in the image) interconnected by 1O resistors as shown,
find the resistance between points '''A''' and '''B'''.
;See also:
* (humor, nerd sniping) xkcd.com cartoon (you can solve that for extra credits)
* An article on how to calculate this and an implementation in Mathematica
| // version 1.1.4-3
typealias List2D<T> = List<List<T>>
const val S = 10
class Node(var v: Double, var fixed: Int)
fun setBoundary(m: List2D<Node>) {
m[1][1].v = 1.0; m[1][1].fixed = 1
m[6][7].v = -1.0; m[6][7].fixed = -1
}
fun calcDiff(m: List2D<Node>, d: List2D<Node>, w: Int, h: Int): Double {
var total = 0.0
for (i in 0 until h) {
for (j in 0 until w) {
var v = 0.0
var n = 0
if (i > 0) { v += m[i - 1][j].v; n++ }
if (j > 0) { v += m[i][j - 1].v; n++ }
if (i + 1 < h) { v += m[i + 1][j].v; n++ }
if (j + 1 < w) { v += m[i][j + 1].v; n++ }
v = m[i][j].v - v / n
d[i][j].v = v
if (m[i][j].fixed == 0) total += v * v
}
}
return total
}
fun iter(m: List2D<Node>, w: Int, h: Int): Double {
val d = List(h) { List(w) { Node(0.0, 0) } }
val cur = DoubleArray(3)
var diff = 1e10
while (diff > 1e-24) {
setBoundary(m)
diff = calcDiff(m, d, w, h)
for (i in 0 until h) {
for (j in 0 until w) m[i][j].v -= d[i][j].v
}
}
for (i in 0 until h) {
for (j in 0 until w) {
var k = 0
if (i != 0) k++
if (j != 0) k++
if (i < h - 1) k++
if (j < w - 1) k++
cur[m[i][j].fixed + 1] += d[i][j].v * k
}
}
return (cur[2] - cur[0]) / 2.0
}
fun main(args: Array<String>) {
val mesh = List(S) { List(S) { Node(0.0, 0) } }
val r = 2.0 / iter(mesh, S, S)
println("R = $r")
} |
Reverse words in a string | Kotlin | 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.
;Example:
Hey you, Bub! would be shown reversed as: Bub! you, Hey
Tokens 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.
You may assume that there are no significant non-visible characters in the input. Multiple or superfluous spaces may be compressed into a single space.
Some strings have no tokens, so an empty string (or one just containing spaces) would be the result.
'''Display''' the strings in order (1st, 2nd, 3rd, ***), and one string per line.
(You can consider the ten strings as ten lines, and the tokens as words.)
;Input data
(ten lines within the box)
line
+----------------------------------------+
1 | ---------- Ice and Fire ------------ |
2 | | <--- a blank line here.
3 | fire, in end will world the say Some |
4 | ice. in say Some |
5 | desire of tasted I've what From |
6 | fire. favor who those with hold I |
7 | | <--- a blank line here.
8 | ... elided paragraph last ... |
9 | | <--- a blank line here.
10 | Frost Robert ----------------------- |
+----------------------------------------+
;Cf.
* [[Phrase reversals]]
| fun reversedWords(s: String) = s.split(" ").filter { it.isNotEmpty() }.reversed().joinToString(" ")
fun main() {
val s = "Hey you, Bub!"
println(reversedWords(s))
println()
val sl = listOf(
" ---------- Ice and Fire ------------ ",
" ",
" fire, in end will world the say Some ",
" ice. in say Some ",
" desire of tasted I've what From ",
" fire. favor who those with hold I ",
" ",
" ... elided paragraph last ... ",
" ",
" Frost Robert ----------------------- ",
)
sl.forEach { println(reversedWords(it)) }
} |
Roman numerals/Decode | Kotlin | Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer.
You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately,
starting with the leftmost decimal digit and skipping any '''0'''s (zeroes).
'''1990''' is rendered as '''MCMXC''' (1000 = M, 900 = CM, 90 = XC) and
'''2008''' is rendered as '''MMVIII''' (2000 = MM, 8 = VIII).
The Roman numeral for '''1666''', '''MDCLXVI''', uses each letter in descending order.
| // version 1.0.6
fun romanDecode(roman: String): Int {
if (roman.isEmpty()) return 0
var n = 0
var last = 'O'
for (c in roman) {
when (c) {
'I' -> n += 1
'V' -> if (last == 'I') n += 3 else n += 5
'X' -> if (last == 'I') n += 8 else n += 10
'L' -> if (last == 'X') n += 30 else n += 50
'C' -> if (last == 'X') n += 80 else n += 100
'D' -> if (last == 'C') n += 300 else n += 500
'M' -> if (last == 'C') n += 800 else n += 1000
}
last = c
}
return n
}
fun main(args: Array<String>) {
val romans = arrayOf("I", "III", "IV", "VIII", "XLIX", "CCII", "CDXXXIII", "MCMXC", "MMVIII", "MDCLXVI")
for (roman in romans) println("${roman.padEnd(10)} = ${romanDecode(roman)}")
} |
Roman numerals/Encode | Kotlin | 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.
In Roman numerals:
* 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC
* 2008 is written as 2000=MM, 8=VIII; or MMVIII
* 1666 uses each Roman symbol in descending order: MDCLXVI
| val romanNumerals = mapOf(
1000 to "M",
900 to "CM",
500 to "D",
400 to "CD",
100 to "C",
90 to "XC",
50 to "L",
40 to "XL",
10 to "X",
9 to "IX",
5 to "V",
4 to "IV",
1 to "I"
)
fun encode(number: Int): String? {
if (number > 5000 || number < 1) {
return null
}
var num = number
var result = ""
for ((multiple, numeral) in romanNumerals.entries) {
while (num >= multiple) {
num -= multiple
result += numeral
}
}
return result
}
fun main(args: Array<String>) {
println(encode(1990))
println(encode(1666))
println(encode(2008))
} |
Runge-Kutta method | Kotlin | Given the example Differential equation:
:y'(t) = t \times \sqrt {y(t)}
With initial condition:
:t_0 = 0 and y_0 = y(t_0) = y(0) = 1
This equation has an exact solution:
:y(t) = \tfrac{1}{16}(t^2 +4)^2
;Task
Demonstrate the commonly used explicit fourth-order Runge-Kutta method to solve the above differential equation.
* 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)
* 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.
;Method summary
Starting with a given y_n and t_n calculate:
:\delta y_1 = \delta t\times y'(t_n, y_n)\quad
:\delta y_2 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_1)
:\delta y_3 = \delta t\times y'(t_n + \tfrac{1}{2}\delta t , y_n + \tfrac{1}{2}\delta y_2)
:\delta y_4 = \delta t\times y'(t_n + \delta t , y_n + \delta y_3)\quad
then:
:y_{n+1} = y_n + \tfrac{1}{6} (\delta y_1 + 2\delta y_2 + 2\delta y_3 + \delta y_4)
:t_{n+1} = t_n + \delta t\quad
| // version 1.1.2
typealias Y = (Double) -> Double
typealias Yd = (Double, Double) -> Double
fun rungeKutta4(t0: Double, tz: Double, dt: Double, y: Y, yd: Yd) {
var tn = t0
var yn = y(tn)
val z = ((tz - t0) / dt).toInt()
for (i in 0..z) {
if (i % 10 == 0) {
val exact = y(tn)
val error = yn - exact
println("%4.1f %10f %10f %9f".format(tn, yn, exact, error))
}
if (i == z) break
val dy1 = dt * yd(tn, yn)
val dy2 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy1)
val dy3 = dt * yd(tn + 0.5 * dt, yn + 0.5 * dy2)
val dy4 = dt * yd(tn + dt, yn + dy3)
yn += (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0
tn += dt
}
}
fun main(args: Array<String>) {
println(" T RK4 Exact Error")
println("---- ---------- ---------- ---------")
val y = fun(t: Double): Double {
val x = t * t + 4.0
return x * x / 16.0
}
val yd = fun(t: Double, yt: Double) = t * Math.sqrt(yt)
rungeKutta4(0.0, 10.0, 0.1, y, yd)
} |
Runtime evaluation | Kotlin | Demonstrate a language's ability for programs to execute code written in the language provided at runtime.
Show 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.
You 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.
For a more constrained task giving a specific program fragment to evaluate, see [[Eval in environment]].
| Kotlin has a REPL which is started from the command line by running the compiler without any parameters.
Any valid Kotlin code can then be entered and immediately evaluated.
Below is a sample session.
$ kotlinc
Welcome to Kotlin version 1.2.31 (JRE 1.8.0_162-8u162-b12-0ubuntu0.16.04.2-b12)
Type :help for help, :quit for quit
>>> 20 + 22
42
>>> 5 * Math.sqrt(81.0)
45.0
>>> fun triple(x: Int) = x * 3
>>> triple(16)
48
>>> :quit
|
Runtime evaluation/In an environment | Kotlin from JavaScript | 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.
Do so in a way which:
* does not involve string manipulation of the input source code
* is plausibly extensible to a runtime-chosen set of bindings rather than just x
* does not make x a ''global'' variable
or note that these are impossible.
;See also:
* For more general examples and language-specific details, see [[Eval]].
* [[Dynamic variable names]] is a similar task.
| // Kotlin JS version 1.1.4-3
fun evalWithX(expr: String, a: Double, b: Double) {
var x = a
val atA = eval(expr)
x = b
val atB = eval(expr)
return atB - atA
}
fun main(args: Array<String>) {
println(evalWithX("Math.exp(x)", 0.0, 1.0))
} |
SHA-1 | Kotlin | '''SHA-1''' or '''SHA1''' is a one-way hash function;
it computes a 160-bit message digest.
SHA-1 often appears in security protocols; for example,
many HTTPS websites use RSA with SHA-1 to secure their connections.
BitTorrent uses SHA-1 to verify downloads.
Git and Mercurial use SHA-1 digests to identify commits.
A US government standard, FIPS 180-1, defines SHA-1.
Find 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.
{{alertbox|lightgray|'''Warning:''' SHA-1 has known weaknesses. Theoretical attacks may find a collision after 252 operations, or perhaps fewer.
This is much faster than a brute force attack of 280 operations. USgovernment deprecated SHA-1.
For production-grade cryptography, users may consider a stronger alternative, such as SHA-256 (from the SHA-2 family) or the upcoming SHA-3.}}
| // version 1.0.6
import java.security.MessageDigest
fun main(args: Array<String>) {
val text = "Rosetta Code"
val bytes = text.toByteArray()
val md = MessageDigest.getInstance("SHA-1")
val digest = md.digest(bytes)
for (byte in digest) print("%02x".format(byte))
println()
} |
Sailors, coconuts and a monkey problem | Kotlin | Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day.
That 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.
To 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.
In 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.)
;The task:
# Calculate the minimum possible size of the initial pile of coconuts collected during the first day.
# 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.)
# 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).
# Show your answers here.
;Extra credit (optional):
* Give some indication of the number of coconuts each sailor hides during the night.
;Note:
* 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.
* The tale is also told in a version where the monkey also gets a coconut in the morning. This is ''not'' that tale!
;C.f:
* Monkeys and Coconuts - Numberphile (Video) Analytical solution.
* 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).
| // version 1.1.2
fun main(args: Array<String>) {
var coconuts = 11
outer@ for (ns in 2..9) {
val hidden = IntArray(ns)
coconuts = (coconuts / ns) * ns + 1
while (true) {
var nc = coconuts
for (s in 1..ns) {
if (nc % ns == 1) {
hidden[s - 1] = nc / ns
nc -= hidden[s - 1] + 1
if (s == ns && nc % ns == 0) {
println("$ns sailors require a minimum of $coconuts coconuts")
for (t in 1..ns) println("\tSailor $t hides ${hidden[t - 1]}")
println("\tThe monkey gets $ns")
println("\tFinally, each sailor takes ${nc / ns}\n")
continue@outer
}
}
else break
}
coconuts += ns
}
}
} |
Self-describing numbers | Kotlin | {{task}}There are several so-called "self-describing" or "self-descriptive" integers.
An 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.
For example, '''2020''' is a four-digit self describing number:
* position 0 has value 2 and there are two 0s in the number;
* position 1 has value 0 and there are no 1s in the number;
* position 2 has value 2 and there are two 2s;
* position 3 has value 0 and there are zero 3s.
Self-describing numbers < 100.000.000 are: 1210, 2020, 21200, 3211000, 42101000.
;Task Description
# Write a function/routine/method/... that will check whether a given positive integer is self-describing.
# As an optional stretch goal - generate and display the set of self-describing numbers.
;Related tasks:
* [[Fours is the number of letters in the ...]]
* [[Look-and-say sequence]]
* [[Number names]]
* [[Self-referential sequence]]
* [[Spelling of ordinal numbers]]
| // version 1.0.6
fun selfDescribing(n: Int): Boolean {
if (n <= 0) return false
val ns = n.toString()
val count = IntArray(10)
var nn = n
while (nn > 0) {
count[nn % 10] += 1
nn /= 10
}
for (i in 0 until ns.length)
if( ns[i] - '0' != count[i]) return false
return true
}
fun main(args: Array<String>) {
println("The self-describing numbers less than 100 million are:")
for (i in 0..99999999) if (selfDescribing(i)) print("$i ")
println()
} |
Self numbers | Kotlin from Java | 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.
The task is:
Display the first 50 self numbers;
I believe that the 100000000th self number is 1022727208. You should either confirm or dispute my conjecture.
224036583-1 is a Mersenne prime, claimed to also be a self number. Extra credit to anyone proving it.
;See also:
;*OEIS: A003052 - Self numbers or Colombian numbers
;*Wikipedia: Self numbers
| private const val MC = 103 * 1000 * 10000 + 11 * 9 + 1
private val SV = BooleanArray(MC + 1)
private fun sieve() {
val dS = IntArray(10000)
run {
var a = 9
var i = 9999
while (a >= 0) {
for (b in 9 downTo 0) {
var c = 9
val s = a + b
while (c >= 0) {
var d = 9
val t = s + c
while (d >= 0) {
dS[i--] = t + d
d--
}
c--
}
}
a--
}
}
var a = 0
var n = 0
while (a < 103) {
var b = 0
val d = dS[a]
while (b < 1000) {
var c = 0
var s = d + dS[b] + n
while (c < 10000) {
SV[dS[c] + s++] = true
c++
}
b++
n += 10000
}
a++
}
}
fun main() {
sieve()
println("The first 50 self numbers are:")
run {
var i = 0
var count = 0
while (count <= 50) {
if (!SV[i]) {
count++
if (count <= 50) {
print("$i ")
} else {
println()
println()
println(" Index Self number")
}
}
i++
}
}
var i = 0
var limit = 1
var count = 0
while (i < MC) {
if (!SV[i]) {
if (++count == limit) {
println("%,12d %,13d".format(count, i))
limit *= 10
}
}
i++
}
} |
Semordnilap | Kotlin from D | A semordnilap is a word (or phrase) that spells a different word (or phrase) backward. "Semordnilap" is a word that itself is a semordnilap.
Example: ''lager'' and ''regal''
;Task
This task does not consider semordnilap phrases, only single words.
Using only words from this list, report the total number of unique semordnilap pairs, and print 5 examples.
Two matching semordnilaps, such as ''lager'' and ''regal'', should be counted as one unique pair.
(Note that the word "semordnilap" is not in the above dictionary.)
| // version 1.2.0
import java.io.File
fun main(args: Array<String>) {
val words = File("unixdict.txt").readLines().toSet()
val pairs = words.map { Pair(it, it.reversed()) }
.filter { it.first < it.second && it.second in words } // avoid dupes+palindromes, find matches
println("Found ${pairs.size} semordnilap pairs")
println(pairs.take(5))
} |
Sequence: nth number with exactly n divisors | Kotlin from Go | Calculate the sequence where each term an is the nth that has '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;See also
:*OEIS:A073916
;Related tasks
:*[[Sequence: smallest number greater than previous term with exactly n divisors]]
:*[[Sequence: smallest number with exactly n divisors]]
| // Version 1.3.21
import java.math.BigInteger
import kotlin.math.sqrt
const val MAX = 33
fun isPrime(n: Int) = BigInteger.valueOf(n.toLong()).isProbablePrime(10)
fun generateSmallPrimes(n: Int): List<Int> {
val primes = mutableListOf<Int>()
primes.add(2)
var i = 3
while (primes.size < n) {
if (isPrime(i)) {
primes.add(i)
}
i += 2
}
return primes
}
fun countDivisors(n: Int): Int {
var nn = n
var count = 1
while (nn % 2 == 0) {
nn = nn shr 1
count++
}
var d = 3
while (d * d <= nn) {
var q = nn / d
var r = nn % d
if (r == 0) {
var dc = 0
while (r == 0) {
dc += count
nn = q
q = nn / d
r = nn % d
}
count += dc
}
d += 2
}
if (nn != 1) count *= 2
return count
}
fun main() {
var primes = generateSmallPrimes(MAX)
println("The first $MAX terms in the sequence are:")
for (i in 1..MAX) {
if (isPrime(i)) {
var z = BigInteger.valueOf(primes[i - 1].toLong())
z = z.pow(i - 1)
System.out.printf("%2d : %d\n", i, z)
} else {
var count = 0
var j = 1
while (true) {
if (i % 2 == 1) {
val sq = sqrt(j.toDouble()).toInt()
if (sq * sq != j) {
j++
continue
}
}
if (countDivisors(j) == i) {
if (++count == i) {
System.out.printf("%2d : %d\n", i, j)
break
}
}
j++
}
}
}
} |
Sequence: smallest number greater than previous term with exactly n divisors | Kotlin from Go | Calculate the sequence where each term an is the '''smallest natural number''' greater than the previous term, that has exactly '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;See also
:* OEIS:A069654
;Related tasks
:* [[Sequence: smallest number with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]
| // Version 1.3.21
const val MAX = 15
fun countDivisors(n: Int): Int {
var count = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
count += if (i == n / i) 1 else 2
}
i++
}
return count
}
fun main() {
println("The first $MAX terms of the sequence are:")
var i = 1
var next = 1
while (next <= MAX) {
if (next == countDivisors(i)) {
print("$i ")
next++
}
i++
}
println()
} |
Sequence: smallest number with exactly n divisors | Kotlin from Go | Calculate the sequence where each term an is the '''smallest natural number''' that has exactly '''n''' divisors.
;Task
Show here, on this page, at least the first '''15''' terms of the sequence.
;Related tasks:
:* [[Sequence: smallest number greater than previous term with exactly n divisors]]
:* [[Sequence: nth number with exactly n divisors]]
;See also:
:* OEIS:A005179
| // Version 1.3.21
const val MAX = 15
fun countDivisors(n: Int): Int {
var count = 0
var i = 1
while (i * i <= n) {
if (n % i == 0) {
count += if (i == n / i) 1 else 2
}
i++
}
return count
}
fun main() {
var seq = IntArray(MAX)
println("The first $MAX terms of the sequence are:")
var i = 1
var n = 0
while (n < MAX) {
var k = countDivisors(i)
if (k <= MAX && seq[k - 1] == 0) {
seq[k - 1] = i
n++
}
i++
}
println(seq.asList())
} |
Set consolidation | Kotlin | 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:
* The two input sets if no common item exists between the two input sets of items.
* The single set that is the union of the two input sets if they share a common item.
Given 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.
If N<2 then consolidation has no strict meaning and the input can be returned.
;'''Example 1:'''
: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.
;'''Example 2:'''
: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).
;'''Example 3:'''
: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}
;'''Example 4:'''
:The consolidation of the five sets:
::{H,I,K}, {A,B}, {C,D}, {D,B}, and {F,G,H}
:Is the two sets:
::{A, C, B, D}, and {G, F, I, H, K}
'''See also'''
* Connected component (graph theory)
* [[Range consolidation]]
| // version 1.0.6
fun<T : Comparable<T>> consolidateSets(sets: Array<Set<T>>): Set<Set<T>> {
val size = sets.size
val consolidated = BooleanArray(size) // all false by default
var i = 0
while (i < size - 1) {
if (!consolidated[i]) {
while (true) {
var intersects = 0
for (j in (i + 1) until size) {
if (consolidated[j]) continue
if (sets[i].intersect(sets[j]).isNotEmpty()) {
sets[i] = sets[i].union(sets[j])
consolidated[j] = true
intersects++
}
}
if (intersects == 0) break
}
}
i++
}
return (0 until size).filter { !consolidated[it] }.map { sets[it].toSortedSet() }.toSet()
}
fun main(args: Array<String>) {
val unconsolidatedSets = arrayOf(
arrayOf(setOf('A', 'B'), setOf('C', 'D')),
arrayOf(setOf('A', 'B'), setOf('B', 'D')),
arrayOf(setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B')),
arrayOf(setOf('H', 'I', 'K'), setOf('A', 'B'), setOf('C', 'D'), setOf('D', 'B'), setOf('F', 'G', 'H'))
)
for (sets in unconsolidatedSets) println(consolidateSets(sets))
} |
Set of real numbers | Kotlin | 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:
* [''a'', ''b'']: {''x'' | ''a'' <= ''x'' and ''x'' <= ''b'' }
* (''a'', ''b''): {''x'' | ''a'' < ''x'' and ''x'' < ''b'' }
* [''a'', ''b''): {''x'' | ''a'' <= ''x'' and ''x'' < ''b'' }
* (''a'', ''b'']: {''x'' | ''a'' < ''x'' and ''x'' <= ''b'' }
Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty.
'''Task'''
* Devise a way to represent any set of real numbers, for the definition of 'any' in the implementation notes below.
* Provide methods for these common set operations (''x'' is a real number; ''A'' and ''B'' are sets):
:* ''x'' ''A'': determine if ''x'' is an element of ''A''
:: example: 1 is in [1, 2), while 2, 3, ... are not.
:* ''A'' ''B'': union of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' or ''x'' ''B''}
:: example: [0, 2) (1, 3) = [0, 3); [0, 1) (2, 3] = well, [0, 1) (2, 3]
:* ''A'' ''B'': intersection of ''A'' and ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) (1, 3) = (1, 2); [0, 1) (2, 3] = empty set
:* ''A'' - ''B'': difference between ''A'' and ''B'', also written as ''A'' \ ''B'', i.e. {''x'' | ''x'' ''A'' and ''x'' ''B''}
:: example: [0, 2) - (1, 3) = [0, 1]
* Test your implementation by checking if numbers 0, 1, and 2 are in any of the following sets:
:* (0, 1] [0, 2)
:* [0, 2) (1, 2]
:* [0, 3) - (0, 1)
:* [0, 3) - [0, 1]
'''Implementation notes'''
* '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.
* Infinities should be handled gracefully; indeterminate numbers (NaN) can be ignored.
* 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).
'''Optional work'''
* Create a function to determine if a given set is empty (contains no element).
* 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
|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.
| // version 1.1.4-3
typealias RealPredicate = (Double) -> Boolean
enum class RangeType { CLOSED, BOTH_OPEN, LEFT_OPEN, RIGHT_OPEN }
class RealSet(val low: Double, val high: Double, val predicate: RealPredicate) {
constructor (start: Double, end: Double, rangeType: RangeType): this(start, end,
when (rangeType) {
RangeType.CLOSED -> fun(d: Double) = d in start..end
RangeType.BOTH_OPEN -> fun(d: Double) = start < d && d < end
RangeType.LEFT_OPEN -> fun(d: Double) = start < d && d <= end
RangeType.RIGHT_OPEN -> fun(d: Double) = start <= d && d < end
}
)
fun contains(d: Double) = predicate(d)
infix fun union(other: RealSet): RealSet {
val low2 = minOf(low, other.low)
val high2 = maxOf(high, other.high)
return RealSet(low2, high2) { predicate(it) || other.predicate(it) }
}
infix fun intersect(other: RealSet): RealSet {
val low2 = maxOf(low, other.low)
val high2 = minOf(high, other.high)
return RealSet(low2, high2) { predicate(it) && other.predicate(it) }
}
infix fun subtract(other: RealSet) = RealSet(low, high) { predicate(it) && !other.predicate(it) }
var interval = 0.00001
val length: Double get() {
if (!low.isFinite() || !high.isFinite()) return -1.0 // error value
if (high <= low) return 0.0
var p = low
var count = 0
do {
if (predicate(p)) count++
p += interval
}
while (p < high)
return count * interval
}
fun isEmpty() = if (high == low) !predicate(low) else length == 0.0
}
fun main(args: Array<String>) {
val a = RealSet(0.0, 1.0, RangeType.LEFT_OPEN)
val b = RealSet(0.0, 2.0, RangeType.RIGHT_OPEN)
val c = RealSet(1.0, 2.0, RangeType.LEFT_OPEN)
val d = RealSet(0.0, 3.0, RangeType.RIGHT_OPEN)
val e = RealSet(0.0, 1.0, RangeType.BOTH_OPEN)
val f = RealSet(0.0, 1.0, RangeType.CLOSED)
val g = RealSet(0.0, 0.0, RangeType.CLOSED)
for (i in 0..2) {
val dd = i.toDouble()
println("(0, 1] ∪ [0, 2) contains $i is ${(a union b).contains(dd)}")
println("[0, 2) ∩ (1, 2] contains $i is ${(b intersect c).contains(dd)}")
println("[0, 3) − (0, 1) contains $i is ${(d subtract e).contains(dd)}")
println("[0, 3) − [0, 1] contains $i is ${(d subtract f).contains(dd)}\n")
}
println("[0, 0] is empty is ${g.isEmpty()}\n")
val aa = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) &&
Math.abs(Math.sin(Math.PI * x * x)) > 0.5 }
val bb = RealSet(0.0, 10.0) { x -> (0.0 < x && x < 10.0) &&
Math.abs(Math.sin(Math.PI * x)) > 0.5 }
val cc = aa subtract bb
println("Approx length of A - B is ${cc.length}")
} |
Shoelace formula for polygonal area | Kotlin | 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:
abs( (sum(x[0]*y[1] + ... x[n-1]*y[n]) + x[N]*y[0]) -
(sum(x[1]*y[0] + ... x[n]*y[n-1]) + x[0]*y[N])
) / 2
(Where abs returns the absolute value)
;Task:
Write a function/method/routine to use the the Shoelace formula to calculate the area of the polygon described by the ordered points:
(3,4), (5,11), (12,8), (9,5), and (5,6)
Show the answer here, on this page.
| // version 1.1.3
class Point(val x: Int, val y: Int) {
override fun toString() = "($x, $y)"
}
fun shoelaceArea(v: List<Point>): Double {
val n = v.size
var a = 0.0
for (i in 0 until n - 1) {
a += v[i].x * v[i + 1].y - v[i + 1].x * v[i].y
}
return Math.abs(a + v[n - 1].x * v[0].y - v[0].x * v[n -1].y) / 2.0
}
fun main(args: Array<String>) {
val v = listOf(
Point(3, 4), Point(5, 11), Point(12, 8), Point(9, 5), Point(5, 6)
)
val area = shoelaceArea(v)
println("Given a polygon with vertices at $v,")
println("its area is $area")
} |
Shortest common supersequence | Kotlin | 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.
;;Task:
Given 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.
Demonstrate this by printing s where u = "abcbdab" and v = "bdcaba".
;Also see:
* Wikipedia: shortest common supersequence
| // version 1.1.2
fun lcs(x: String, y: String): String {
if (x.length == 0 || y.length == 0) return ""
val x1 = x.dropLast(1)
val y1 = y.dropLast(1)
if (x.last() == y.last()) return lcs(x1, y1) + x.last()
val x2 = lcs(x, y1)
val y2 = lcs(x1, y)
return if (x2.length > y2.length) x2 else y2
}
fun scs(u: String, v: String): String{
val lcs = lcs(u, v)
var ui = 0
var vi = 0
val sb = StringBuilder()
for (i in 0 until lcs.length) {
while (ui < u.length && u[ui] != lcs[i]) sb.append(u[ui++])
while (vi < v.length && v[vi] != lcs[i]) sb.append(v[vi++])
sb.append(lcs[i])
ui++; vi++
}
if (ui < u.length) sb.append(u.substring(ui))
if (vi < v.length) sb.append(v.substring(vi))
return sb.toString()
}
fun main(args: Array<String>) {
val u = "abcbdab"
val v = "bdcaba"
println(scs(u, v))
} |
Show ASCII table | Kotlin from Go | Show the ASCII character set from values '''32''' to '''127''' (decimal) in a table format.
| // Version 1.2.60
fun main(args: Array<String>) {
for (i in 0..15) {
for (j in 32 + i..127 step 16) {
val k = when (j) {
32 -> "Spc"
127 -> "Del"
else -> j.toChar().toString()
}
System.out.printf("%3d : %-3s ", j, k)
}
println()
}
} |
Show the epoch | Kotlin from Java | Choose popular date libraries used by your language and show the epoch those libraries use.
A 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.
For consistency's sake, show the date in UTC time where possible.
;Related task:
* [[Date format]]
| // version 1.1.2
import java.util.Date
import java.util.TimeZone
import java.text.DateFormat
fun main( args: Array<String>) {
val epoch = Date(0)
val format = DateFormat.getDateTimeInstance()
format.timeZone = TimeZone.getTimeZone("UTC")
println(format.format(epoch))
} |
Sierpinski pentagon | Kotlin from Java | 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.
;See also
* Sierpinski pentagon
| // version 1.1.2
import java.awt.*
import java.awt.geom.Path2D
import java.util.Random
import javax.swing.*
class SierpinskiPentagon : JPanel() {
// exterior angle
private val degrees072 = Math.toRadians(72.0)
/* After scaling we'll have 2 sides plus a gap occupying the length
of a side before scaling. The gap is the base of an isosceles triangle
with a base angle of 72 degrees. */
private val scaleFactor = 1.0 / (2.0 + Math.cos(degrees072) * 2.0)
private val margin = 20
private var limit = 0
private val r = Random()
init {
preferredSize = Dimension(640, 640)
background = Color.white
Timer(3000) {
limit++
if (limit >= 5) limit = 0
repaint()
}.start()
}
private fun drawPentagon(g: Graphics2D, x: Double, y: Double, s: Double, depth: Int) {
var angle = 3.0 * degrees072 // starting angle
var xx = x
var yy = y
var side = s
if (depth == 0) {
val p = Path2D.Double()
p.moveTo(xx, yy)
// draw from the top
for (i in 0 until 5) {
xx += Math.cos(angle) * side
yy -= Math.sin(angle) * side
p.lineTo(xx, yy)
angle += degrees072
}
g.color = RandomHue.next()
g.fill(p)
}
else {
side *= scaleFactor
/* Starting at the top of the highest pentagon, calculate
the top vertices of the other pentagons by taking the
length of the scaled side plus the length of the gap. */
val distance = side + side * Math.cos(degrees072) * 2.0
/* The top positions form a virtual pentagon of their own,
so simply move from one to the other by changing direction. */
for (i in 0 until 5) {
xx += Math.cos(angle) * distance
yy -= Math.sin(angle) * distance
drawPentagon(g, xx, yy, side, depth - 1)
angle += degrees072
}
}
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val hw = width / 2
val radius = hw - 2.0 * margin
val side = radius * Math.sin(Math.PI / 5.0) * 2.0
drawPentagon(g, hw.toDouble(), 3.0 * margin, side, limit)
}
private class RandomHue {
/* Try to avoid random color values clumping together */
companion object {
val goldenRatioConjugate = (Math.sqrt(5.0) - 1.0) / 2.0
var hue = Math.random()
fun next(): Color {
hue = (hue + goldenRatioConjugate) % 1
return Color.getHSBColor(hue.toFloat(), 1.0f, 1.0f)
}
}
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
f.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
f.title = "Sierpinski Pentagon"
f.isResizable = true
f.add(SierpinskiPentagon(), BorderLayout.CENTER)
f.pack()
f.setLocationRelativeTo(null)
f.isVisible = true
}
} |
Sierpinski triangle/Graphical | Kotlin | Produce a graphical representation of a Sierpinski triangle of order N in any orientation.
An example of Sierpinski's triangle (order = 8) looks like this:
[[File:Sierpinski_Triangle_Unicon.PNG]]
| import java.awt.*
import javax.swing.JFrame
import javax.swing.JPanel
fun main(args: Array<String>) {
var i = 8 // Default
if (args.any()) {
try {
i = args.first().toInt()
} catch (e: NumberFormatException) {
i = 8
println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to $i")
}
}
object : JFrame("Sierpinsky Triangle - Kotlin") {
val panel = object : JPanel() {
val size = 800
init {
preferredSize = Dimension(size, size)
}
public override fun paintComponent(g: Graphics) {
g.color = Color.BLACK
if (g is Graphics2D) {
g.drawSierpinskyTriangle(i, 20, 20, size - 40)
}
}
}
init {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(panel)
pack()
isResizable = false
setLocationRelativeTo(null)
isVisible = true
}
}
}
internal fun Graphics2D.drawSierpinskyTriangle(level: Int, x: Int, y: Int, size: Int) {
if (level > 0) {
drawLine(x, y, x + size, y)
drawLine(x, y, x, y + size)
drawLine(x + size, y, x, y + size)
drawSierpinskyTriangle(level - 1, x, y, size / 2)
drawSierpinskyTriangle(level - 1, x + size / 2, y, size / 2)
drawSierpinskyTriangle(level - 1, x, y + size / 2, size / 2)
}
} |
Smith numbers | Kotlin from FreeBASIC | 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.
By definition, all primes are ''excluded'' as they (naturally) satisfy this condition!
Smith numbers are also known as ''joke'' numbers.
;Example
Using the number '''166'''
Find the prime factors of '''166''' which are: '''2''' x '''83'''
Then, take those two prime factors and sum all their decimal digits: '''2 + 8 + 3''' which is '''13'''
Then, take the decimal digits of '''166''' and add their decimal digits: '''1 + 6 + 6''' which is '''13'''
Therefore, the number '''166''' is a Smith number.
;Task
Write a program to find all Smith numbers ''below'' 10000.
;See also
* from Wikipedia: [Smith number].
* from MathWorld: [Smith number].
* from OEIS A6753: [OEIS sequence A6753].
* from OEIS A104170: [Number of Smith numbers below 10^n].
* from The Prime pages: [Smith numbers].
| // version 1.0.6
fun getPrimeFactors(n: Int): MutableList<Int> {
val factors = mutableListOf<Int>()
if (n < 2) return factors
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return factors
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
fun sumDigits(n: Int): Int = when {
n < 10 -> n
else -> {
var sum = 0
var nn = n
while (nn > 0) {
sum += (nn % 10)
nn /= 10
}
sum
}
}
fun isSmith(n: Int): Boolean {
if (n < 2) return false
val factors = getPrimeFactors(n)
if (factors.size == 1) return false
val primeSum = factors.sumBy { sumDigits(it) }
return sumDigits(n) == primeSum
}
fun main(args: Array<String>) {
println("The Smith numbers below 10000 are:\n")
var count = 0
for (i in 2 until 10000) {
if (isSmith(i)) {
print("%5d".format(i))
count++
}
}
println("\n\n$count numbers found")
} |
Solve a Hidato puzzle | Kotlin from Java | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
* You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
** The grid is not necessarily rectangular.
** The grid may have holes in it.
** The grid is always connected.
** 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.
** It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
* 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).
** 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.
** A square may only contain one number.
* In a proper Hidato puzzle, the solution is unique.
For example the following problem
Sample Hidato problem, from Wikipedia
has the following solution, with path marked on it:
Solution to sample Hidato problem
;Related tasks:
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]];
| // version 1.2.0
lateinit var board: List<IntArray>
lateinit var given: IntArray
lateinit var start: IntArray
fun setUp(input: List<String>) {
val nRows = input.size
val puzzle = List(nRows) { input[it].split(" ") }
val nCols = puzzle[0].size
val list = mutableListOf<Int>()
board = List(nRows + 2) { IntArray(nCols + 2) { -1 } }
for (r in 0 until nRows) {
val row = puzzle[r]
for (c in 0 until nCols) {
val cell = row[c]
if (cell == "_") {
board[r + 1][c + 1] = 0
}
else if (cell != ".") {
val value = cell.toInt()
board[r + 1][c + 1] = value
list.add(value)
if (value == 1) start = intArrayOf(r + 1, c + 1)
}
}
}
list.sort()
given = list.toIntArray()
}
fun solve(r: Int, c: Int, n: Int, next: Int): Boolean {
if (n > given[given.lastIndex]) return true
val back = board[r][c]
if (back != 0 && back != n) return false
if (back == 0 && given[next] == n) return false
var next2 = next
if (back == n) next2++
board[r][c] = n
for (i in -1..1)
for (j in -1..1)
if (solve(r + i, c + j, n + 1, next2)) return true
board[r][c] = back
return false
}
fun printBoard() {
for (row in board) {
for (c in row) {
if (c == -1)
print(" . ")
else
print(if (c > 0) "%2d ".format(c) else "__ ")
}
println()
}
}
fun main(args: Array<String>) {
var input = listOf(
"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"
)
setUp(input)
printBoard()
println("\nFound:")
solve(start[0], start[1], 1, 0)
printBoard()
} |
Solve a Holy Knight's tour | Kotlin from Python | 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.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:
;Example:
0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| // version 1.1.3
val moves = arrayOf(
intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2),
intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1)
)
val board1 =
" xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
val board2 =
".....s.x....." +
".....x.x....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean {
if (idx > cnt) return true
for (i in 0 until moves.size) {
val x = sx + moves[i][0]
val y = sy + moves[i][1]
if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) {
pz[x][y] = idx
if (solve(pz, sz, x, y, idx + 1, cnt)) return true
pz[x][y] = 0
}
}
return false
}
fun findSolution(b: String, sz: Int) {
val pz = Array(sz) { IntArray(sz) { -1 } }
var x = 0
var y = 0
var idx = 0
var cnt = 0
for (j in 0 until sz) {
for (i in 0 until sz) {
if (b[idx] == 'x') {
pz[i][j] = 0
cnt++
}
else if (b[idx] == 's') {
pz[i][j] = 1
cnt++
x = i
y = j
}
idx++
}
}
if (solve(pz, sz, x, y, 2, cnt)) {
for (j in 0 until sz) {
for (i in 0 until sz) {
if (pz[i][j] != -1)
print("%02d ".format(pz[i][j]))
else
print("-- ")
}
println()
}
}
else println("Cannot solve this puzzle!")
}
fun main(args: Array<String>) {
findSolution(board1, 8)
println()
findSolution(board2, 13)
} |
Solve a Hopido puzzle | Kotlin from Java | 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:
"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!"
Knowing 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.
Example:
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 0 . . .
Extra credits are available for other interesting designs.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| // version 1.2.0
val board = listOf(
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
)
val moves = listOf(
-3 to 0, 0 to 3, 3 to 0, 0 to -3,
2 to 2, 2 to -2, -2 to 2, -2 to -2
)
lateinit var grid: List<IntArray>
var totalToFill = 0
fun solve(r: Int, c: Int, count: Int): Boolean {
if (count > totalToFill) return true
val nbrs = neighbors(r, c)
if (nbrs.isEmpty() && count != totalToFill) return false
nbrs.sortBy { it[2] }
for (nb in nbrs) {
val rr = nb[0]
val cc = nb[1]
grid[rr][cc] = count
if (solve(rr, cc, count + 1)) return true
grid[rr][cc] = 0
}
return false
}
fun neighbors(r: Int, c: Int): MutableList<IntArray> {
val nbrs = mutableListOf<IntArray>()
for (m in moves) {
val x = m.first
val y = m.second
if (grid[r + y][c + x] == 0) {
val num = countNeighbors(r + y, c + x) - 1
nbrs.add(intArrayOf(r + y, c + x, num))
}
}
return nbrs
}
fun countNeighbors(r: Int, c: Int): Int {
var num = 0
for (m in moves)
if (grid[r + m.second][c + m.first] == 0) num++
return num
}
fun printResult() {
for (row in grid) {
for (i in row) {
print(if (i == -1) " " else "%2d ".format(i))
}
println()
}
}
fun main(args: Array<String>) {
val nRows = board.size + 6
val nCols = board[0].length + 6
grid = List(nRows) { IntArray(nCols) { -1} }
for (r in 0 until nRows) {
for (c in 3 until nCols - 3) {
if (r in 3 until nRows - 3) {
if (board[r - 3][c - 3] == '0') {
grid[r][c] = 0
totalToFill++
}
}
}
}
var pos = -1
var rr: Int
var cc: Int
do {
do {
pos++
rr = pos / nCols
cc = pos % nCols
}
while (grid[rr][cc] == -1)
grid[rr][cc] = 1
if (solve(rr, cc, 2)) break
grid[rr][cc] = 0
}
while (pos < nRows * nCols)
printResult()
} |
Solve a Numbrix puzzle | Kotlin from Java | Numbrix puzzles are similar to Hidato.
The 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).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
;Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
;Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
;Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve the no connection puzzle]]
| // version 1.2.0
val example1 = listOf(
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"
)
val example2 = listOf(
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00"
)
val moves = listOf(1 to 0, 0 to 1, -1 to 0, 0 to -1)
lateinit var board: List<String>
lateinit var grid: List<IntArray>
lateinit var clues: IntArray
var totalToFill = 0
fun solve(r: Int, c: Int, count: Int, nextClue: Int): Boolean {
if (count > totalToFill) return true
val back = grid[r][c]
if (back != 0 && back != count) return false
if (back == 0 && nextClue < clues.size && clues[nextClue] == count) {
return false
}
var nextClue2 = nextClue
if (back == count) nextClue2++
grid[r][c] = count
for (m in moves) {
if (solve(r + m.second, c + m.first, count + 1, nextClue2)) return true
}
grid[r][c] = back
return false
}
fun printResult(n: Int) {
println("Solution for example $n:")
for (row in grid) {
for (i in row) {
if (i == -1) continue
print("%2d ".format(i))
}
println()
}
}
fun main(args: Array<String>) {
for ((n, ex) in listOf(example1, example2).withIndex()) {
board = ex
val nRows = board.size + 2
val nCols = board[0].split(",").size + 2
var startRow = 0
var startCol = 0
grid = List(nRows) { IntArray(nCols) { -1 } }
totalToFill = (nRows - 2) * (nCols - 2)
val lst = mutableListOf<Int>()
for (r in 0 until nRows) {
if (r in 1 until nRows - 1) {
val row = board[r - 1].split(",")
for (c in 1 until nCols - 1) {
val value = row[c - 1].toInt()
if (value > 0) lst.add(value)
if (value == 1) {
startRow = r
startCol = c
}
grid[r][c] = value
}
}
}
lst.sort()
clues = lst.toIntArray()
if (solve(startRow, startCol, 1, 0)) printResult(n + 1)
}
} |
Sparkline in unicode | Kotlin from Java | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
;Task:
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '########'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
# 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
# 1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
:(note the mix of separators in this second case)!
;Notes:
* A space is not part of the generated sparkline.
* The sparkline may be accompanied by simple statistics of the data such as its range.
* 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:
:: "0, 1, 19, 20" -> ####
:: (Aiming to use just two spark levels)
:: "0, 999, 4000, 4999, 7000, 7999" -> ######
:: (Aiming to use just three spark levels)
:: It may be helpful to include these cases in output tests.
* You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| internal const val bars = "▁▂▃▄▅▆▇█"
internal const val n = bars.length - 1
fun <T: Number> Iterable<T>.toSparkline(): String {
var min = Double.MAX_VALUE
var max = Double.MIN_VALUE
val doubles = map { it.toDouble() }
doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } }
val range = max - min
return doubles.fold("") { line, d -> line + bars[Math.ceil((d - min) / range * n).toInt()] }
}
fun String.toSparkline() = replace(",", "").split(" ").map { it.toFloat() }.toSparkline()
fun main(args: Array<String>) {
val s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"
println(s1)
println(s1.toSparkline())
val s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"
println(s2)
println(s2.toSparkline())
} |
Spelling of ordinal numbers | Kotlin | '''Ordinal numbers''' (as used in this Rosetta Code task), are numbers that describe the ''position'' of something in a list.
It is this context that ordinal numbers will be used, using an English-spelled name of an ordinal number.
The ordinal numbers are (at least, one form of them):
1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th *** etc
sometimes expressed as:
1st 2nd 3rd 4th 5th 6th 7th *** 99th 100th *** 1000000000th ***
For this task, the following (English-spelled form) will be used:
first second third fourth fifth sixth seventh ninety-nineth one hundredth one billionth
Furthermore, the American version of numbers will be used here (as opposed to the British).
'''2,000,000,000''' is two billion, ''not'' two milliard.
;Task:
Write a driver and a function (subroutine/routine ***) that returns the English-spelled ordinal version of a specified number (a positive integer).
Optionally, 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.
Show all output here.
;Test cases:
Use (at least) the test cases of:
1 2 3 4 5 11 65 100 101 272 23456 8007006005004003
;Related tasks:
* [[Number names]]
* [[N'th]]
| // version 1.1.4-3
typealias IAE = IllegalArgumentException
val names = mapOf(
1 to "one",
2 to "two",
3 to "three",
4 to "four",
5 to "five",
6 to "six",
7 to "seven",
8 to "eight",
9 to "nine",
10 to "ten",
11 to "eleven",
12 to "twelve",
13 to "thirteen",
14 to "fourteen",
15 to "fifteen",
16 to "sixteen",
17 to "seventeen",
18 to "eighteen",
19 to "nineteen",
20 to "twenty",
30 to "thirty",
40 to "forty",
50 to "fifty",
60 to "sixty",
70 to "seventy",
80 to "eighty",
90 to "ninety"
)
val bigNames = mapOf(
1_000L to "thousand",
1_000_000L to "million",
1_000_000_000L to "billion",
1_000_000_000_000L to "trillion",
1_000_000_000_000_000L to "quadrillion",
1_000_000_000_000_000_000L to "quintillion"
)
val irregOrdinals = mapOf(
"one" to "first",
"two" to "second",
"three" to "third",
"five" to "fifth",
"eight" to "eighth",
"nine" to "ninth",
"twelve" to "twelfth"
)
fun String.toOrdinal(): String {
val splits = this.split(' ', '-')
var last = splits[splits.lastIndex]
return if (irregOrdinals.containsKey(last)) this.dropLast(last.length) + irregOrdinals[last]!!
else if (last.endsWith("y")) this.dropLast(1) + "ieth"
else this + "th"
}
fun numToOrdinalText(n: Long, uk: Boolean = false): String {
if (n == 0L) return "zeroth" // or alternatively 'zeroeth'
val neg = n < 0L
val maxNeg = n == Long.MIN_VALUE
var nn = if (maxNeg) -(n + 1) else if (neg) -n else n
val digits3 = IntArray(7)
for (i in 0..6) { // split number into groups of 3 digits from the right
digits3[i] = (nn % 1000).toInt()
nn /= 1000
}
fun threeDigitsToText(number: Int) : String {
val sb = StringBuilder()
if (number == 0) return ""
val hundreds = number / 100
val remainder = number % 100
if (hundreds > 0) {
sb.append(names[hundreds], " hundred")
if (remainder > 0) sb.append(if (uk) " and " else " ")
}
if (remainder > 0) {
val tens = remainder / 10
val units = remainder % 10
if (tens > 1) {
sb.append(names[tens * 10])
if (units > 0) sb.append("-", names[units])
}
else sb.append(names[remainder])
}
return sb.toString()
}
val strings = Array<String>(7) { threeDigitsToText(digits3[it]) }
var text = strings[0]
var andNeeded = uk && digits3[0] in 1..99
var big = 1000L
for (i in 1..6) {
if (digits3[i] > 0) {
var text2 = strings[i] + " " + bigNames[big]
if (text.length > 0) {
text2 += if (andNeeded) " and " else ", "
andNeeded = false
}
else andNeeded = uk && digits3[i] in 1..99
text = text2 + text
}
big *= 1000
}
if (maxNeg) text = text.dropLast(5) + "eight"
if (neg) text = "minus " + text
return text.toOrdinal()
}
fun numToOrdinalText(s: String, uk: Boolean = false): String {
val d = s.toDoubleOrNull() ?: throw IAE("String is not numeric")
if (d !in Long.MIN_VALUE.toDouble() .. Long.MAX_VALUE.toDouble())
throw IAE("Double is outside the range of a Long Integer")
val n = d.toLong()
if (n.toDouble() != d) throw IAE("String does not represent a Long Integer")
return numToOrdinalText(n, uk)
}
fun main(args: Array<String>) {
val la = longArrayOf(1, 2, 3, 4, 5, 11, 65, 100, 101, 272, 23456, 8007006005004003)
println("Using US representation:")
for (i in la) println("${"%16d".format(i)} = ${numToOrdinalText(i)}")
val sa = arrayOf("123", "00123.0", "1.23e2")
for (s in sa) println("${"%16s".format(s)} = ${numToOrdinalText(s)}")
} |
Split a character string based on change of character | Kotlin | Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
| // version 1.0.6
fun splitOnChange(s: String): String {
if (s.length < 2) return s
var t = s.take(1)
for (i in 1 until s.length)
if (t.last() == s[i]) t += s[i]
else t += ", " + s[i]
return t
}
fun main(args: Array<String>) {
val s = """gHHH5YY++///\"""
println(splitOnChange(s))
} |
Square-free integers | Kotlin from Go | Write a function to test if a number is ''square-free''.
A ''square-free'' is an integer which is divisible by no perfect square other
than '''1''' (unity).
For this task, only positive square-free numbers will be used.
Show here (on this page) all square-free integers (in a horizontal format) that are between:
::* '''1''' ---> '''145''' (inclusive)
::* '''1''' trillion ---> '''1''' trillion + '''145''' (inclusive)
(One trillion = 1,000,000,000,000)
Show here (on this page) the count of square-free integers from:
::* '''1''' ---> one hundred (inclusive)
::* '''1''' ---> one thousand (inclusive)
::* '''1''' ---> ten thousand (inclusive)
::* '''1''' ---> one hundred thousand (inclusive)
::* '''1''' ---> one million (inclusive)
;See also:
:* the Wikipedia entry: square-free integer
| // Version 1.2.50
import kotlin.math.sqrt
fun sieve(limit: Long): List<Long> {
val primes = mutableListOf(2L)
val c = BooleanArray(limit.toInt() + 1) // composite = true
// no need to process even numbers > 2
var p = 3
while (true) {
val p2 = p * p
if (p2 > limit) break
for (i in p2..limit step 2L * p) c[i.toInt()] = true
do { p += 2 } while (c[p])
}
for (i in 3..limit step 2)
if (!c[i.toInt()])
primes.add(i)
return primes
}
fun squareFree(r: LongProgression): List<Long> {
val primes = sieve(sqrt(r.last.toDouble()).toLong())
val results = mutableListOf<Long>()
outer@ for (i in r) {
for (p in primes) {
val p2 = p * p
if (p2 > i) break
if (i % p2 == 0L) continue@outer
}
results.add(i)
}
return results
}
fun printResults(r: LongProgression, c: Int, f: Int) {
println("Square-free integers from ${r.first} to ${r.last}:")
squareFree(r).chunked(c).forEach {
println()
it.forEach { print("%${f}d".format(it)) }
}
println('\n')
}
const val TRILLION = 1000000_000000L
fun main(args: Array<String>) {
printResults(1..145L, 20, 4)
printResults(TRILLION..TRILLION + 145L, 5, 14)
println("Number of square-free integers:\n")
longArrayOf(100, 1000, 10000, 100000, 1000000).forEach {
j -> println(" from 1 to $j = ${squareFree(1..j).size}")
}
} |
Square but not cube | Kotlin | Show the first '''30''' positive integers which are squares but not cubes of such integers.
Optionally, show also the first '''3''' positive integers which are both squares and cubes, and mark them as such.
| // Version 1.2.60
fun main(args: Array<String>) {
var n = 1
var count = 0
while (count < 30) {
val sq = n * n
val cr = Math.cbrt(sq.toDouble()).toInt()
if (cr * cr * cr != sq) {
count++
println(sq)
}
else {
println("$sq is square and cube")
}
n++
}
} |
Stair-climbing puzzle | Kotlin from D | From Chung-Chieh Shan (LtU):
Your 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.
Write 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?
Here's a pseudo-code of a simple recursive solution without using variables:
func step_up()
{
if not step() {
step_up();
step_up();
}
}
Inductive proof that step_up() steps up one step, if it terminates:
* Base case (if the step() call returns true): it stepped up one step. QED
* 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
The second (tail) recursion above can be turned into an iteration, as follows:
func step_up()
{
while not step() {
step_up();
}
}
| // version 1.2.0
import java.util.Random
val rand = Random(6321L) // generates short repeatable sequence
var position = 0
fun step(): Boolean {
val r = rand.nextBoolean()
if (r)
println("Climbed up to ${++position}")
else
println("Fell down to ${--position}")
return r
}
fun stepUp() {
while (!step()) stepUp()
}
fun main(args: Array<String>) {
stepUp()
} |
Start from a main routine | Kotlin | 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.
;Task:
Demonstrate the steps involved in causing the application to run a main procedure, rather than an event driven window at startup.
Languages that always run from main() can be omitted from this task.
| The version of Kotlin which targets the JVM always starts from the main(args: Array<String>) 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:
|
Statistics/Normal distribution | Kotlin from FreeBASIC | The derive normally distributed random numbers from a uniform generator.
;The task:
# 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.
# Mention any native language support for the generation of normally distributed random numbers.
;Reference:
* You may refer to code in [[Statistics/Basic]] if available.
| // version 1.1.2
val rand = java.util.Random()
fun normalStats(sampleSize: Int) {
if (sampleSize < 1) return
val r = DoubleArray(sampleSize)
val h = IntArray(12) // all zero by default
/*
Generate 'sampleSize' normally distributed random numbers with mean 0.5 and SD 0.25
and calculate in which box they will fall when drawing the histogram
*/
for (i in 0 until sampleSize) {
r[i] = 0.5 + rand.nextGaussian() / 4.0
when {
r[i] < 0.0 -> h[0]++
r[i] >= 1.0 -> h[11]++
else -> h[1 + (r[i] * 10).toInt()]++
}
}
// adjust one of the h[] values if necessary to ensure they sum to sampleSize
val adj = sampleSize - h.sum()
if (adj != 0) {
for (i in 0..11) {
h[i] += adj
if (h[i] >= 0) break
h[i] -= adj
}
}
val mean = r.average()
val sd = Math.sqrt(r.map { (it - mean) * (it - mean) }.average())
// Draw a histogram of the data with interval 0.1
var numStars: Int
// If sample size > 300 then normalize histogram to 300
val scale = if (sampleSize <= 300) 1.0 else 300.0 / sampleSize
println("Sample size $sampleSize\n")
println(" Mean ${"%1.6f".format(mean)} SD ${"%1.6f".format(sd)}\n")
for (i in 0..11) {
when (i) {
0 -> print("< 0.00 : ")
11 -> print(">=1.00 : ")
else -> print(" %1.2f : ".format(i / 10.0))
}
print("%5d ".format(h[i]))
numStars = (h[i] * scale + 0.5).toInt()
println("*".repeat(numStars))
}
println()
}
fun main(args: Array<String>) {
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) normalStats(sampleSize)
} |
Stern-Brocot sequence | Kotlin | For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [[Fibonacci sequence]].
# The first and second members of the sequence are both 1:
#* 1, 1
# Start by considering the second member of the sequence
# Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the sequence:
#* 1, 1, 2
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1
# Consider the next member of the series, (the third member i.e. 2)
# GOTO 3
#*
#* --- Expanding another loop we get: ---
#*
# Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the sequence:
#* 1, 1, 2, 1, 3
# Append the considered member of the sequence to the end of the sequence:
#* 1, 1, 2, 1, 3, 2
# Consider the next member of the series, (the fourth member i.e. 1)
;The task is to:
* Create a function/method/subroutine/procedure/... to generate the Stern-Brocot sequence of integers using the method outlined above.
* 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)
* Show the (1-based) index of where the numbers 1-to-10 first appear in the sequence.
* Show the (1-based) index of where the number 100 first appears in the sequence.
* Check that the greatest common divisor of all the two consecutive members of the series up to the 1000th member, is always one.
Show your output on this page.
;Related tasks:
:* [[Fusc sequence]].
:* [[Continued fraction/Arithmetic]]
;Ref:
* Infinite Fractions - Numberphile (Video).
* Trees, Teeth, and Time: The mathematics of clock making.
* A002487 The On-Line Encyclopedia of Integer Sequences.
| // version 1.1.0
val sbs = mutableListOf(1, 1)
fun sternBrocot(n: Int, fromStart: Boolean = true) {
if (n < 4 || (n % 2 != 0)) throw IllegalArgumentException("n must be >= 4 and even")
var consider = if (fromStart) 1 else n / 2 - 1
while (true) {
val sum = sbs[consider] + sbs[consider - 1]
sbs.add(sum)
sbs.add(sbs[consider])
if (sbs.size == n) break
consider++
}
}
fun gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
fun main(args: Array<String>) {
var n = 16 // needs to be even to ensure 'considered' number is added
println("First 15 members of the Stern-Brocot sequence")
sternBrocot(n)
println(sbs.take(15))
val firstFind = IntArray(11) // all zero by default
firstFind[0] = -1 // needs to be non-zero for subsequent test
for ((i, v) in sbs.withIndex())
if (v <= 10 && firstFind[v] == 0) firstFind[v] = i + 1
loop@ while (true) {
n += 2
sternBrocot(n, false)
val vv = sbs.takeLast(2)
var m = n - 1
for (v in vv) {
if (v <= 10 && firstFind[v] == 0) firstFind[v] = m
if (firstFind.all { it != 0 }) break@loop
m++
}
}
println("\nThe numbers 1 to 10 first appear at the following indices:")
for (i in 1..10) println("${"%2d".format(i)} -> ${firstFind[i]}")
print("\n100 first appears at index ")
while (true) {
n += 2
sternBrocot(n, false)
val vv = sbs.takeLast(2)
if (vv[0] == 100) {
println(n - 1); break
}
if (vv[1] == 100) {
println(n); break
}
}
print("\nThe GCDs of each pair of the series up to the 1000th member are ")
for (p in 0..998 step 2) {
if (gcd(sbs[p], sbs[p + 1]) != 1) {
println("not all one")
return
}
}
println("all one")
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.