title
stringlengths 3
86
| language
stringlengths 1
35
| task
stringlengths 41
8.77k
| solution
stringlengths 60
47.6k
|
---|---|---|---|
Hash join | Kotlin | {| class="wikitable"
|-
! Input
! Output
|-
|
{| style="border:none; border-collapse:collapse;"
|-
| style="border:none" | ''A'' =
| style="border:none" |
{| class="wikitable"
|-
! Age !! Name
|-
| 27 || Jonah
|-
| 18 || Alan
|-
| 28 || Glory
|-
| 18 || Popeye
|-
| 28 || Alan
|}
| style="border:none; padding-left:1.5em;" rowspan="2" |
| style="border:none" | ''B'' =
| style="border:none" |
{| class="wikitable"
|-
! Character !! Nemesis
|-
| Jonah || Whales
|-
| Jonah || Spiders
|-
| Alan || Ghosts
|-
| Alan || Zombies
|-
| Glory || Buffy
|}
|-
| style="border:none" | ''jA'' =
| style="border:none" | Name (i.e. column 1)
| style="border:none" | ''jB'' =
| style="border:none" | Character (i.e. column 0)
|}
|
{| class="wikitable" style="margin-left:1em"
|-
! A.Age !! A.Name !! B.Character !! B.Nemesis
|-
| 27 || Jonah || Jonah || Whales
|-
| 27 || Jonah || Jonah || Spiders
|-
| 18 || Alan || Alan || Ghosts
|-
| 18 || Alan || Alan || Zombies
|-
| 28 || Glory || Glory || Buffy
|-
| 28 || Alan || Alan || Ghosts
|-
| 28 || Alan || Alan || Zombies
|}
|}
The order of the rows in the output table is not significant.
If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
| data class A(val age: Int, val name: String)
data class B(val character: String, val nemesis: String)
data class C(val rowA: A, val rowB: B)
fun hashJoin(tableA: List<A>, tableB: List<B>): List<C> {
val mm = tableB.groupBy { it.character }
val tableC = mutableListOf<C>()
for (a in tableA) {
val value = mm[a.name] ?: continue
for (b in value) tableC.add(C(a, b))
}
return tableC.toList()
}
fun main(args: Array<String>) {
val tableA = listOf(
A(27, "Jonah"),
A(18, "Alan"),
A(28, "Glory"),
A(18, "Popeye"),
A(28, "Alan")
)
val tableB = listOf(
B("Jonah", "Whales"),
B("Jonah", "Spiders"),
B("Alan", "Ghosts"),
B("Alan", "Zombies"),
B("Glory", "Buffy")
)
val tableC = hashJoin(tableA, tableB)
println("A.Age A.Name B.Character B.Nemesis")
println("----- ------ ----------- ---------")
for (c in tableC) {
print("${c.rowA.age} ${c.rowA.name.padEnd(6)} ")
println("${c.rowB.character.padEnd(6)} ${c.rowB.nemesis}")
}
} |
Haversine formula | Kotlin from Groovy | {{Wikipedia}}
The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.
It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles".
;Task:
Implement a great-circle distance function, or use a library function,
to show the great-circle distance between:
* Nashville International Airport (BNA) in Nashville, TN, USA, which is:
'''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and-
* Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is:
'''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40)
User Kaimbridge clarified on the Talk page:
-- 6371.0 km is the authalic radius based on/extracted from surface area;
-- 6372.8 km is an approximation of the radius of the average circumference
(i.e., the average great-elliptic or great-circle radius), where the
boundaries are the meridian (6367.45 km) and the equator (6378.14 km).
Using either of these values results, of course, in differing distances:
6371.0 km -> 2886.44444283798329974715782394574671655 km;
6372.8 km -> 2887.25995060711033944886005029688505340 km;
(results extended for accuracy check: Given that the radii are only
approximations anyways, .01' 1.0621333 km and .001" .00177 km,
practical precision required is certainly no greater than about
.0000001----i.e., .1 mm!)
As distances are segments of great circles/circumferences, it is
recommended that the latter value (r = 6372.8 km) be used (which
most of the given solutions have already adopted, anyways).
Most of the examples below adopted Kaimbridge's recommended value of
6372.8 km for the earth radius. However, the derivation of this
ellipsoidal quadratic mean radius
is wrong (the averaging over azimuth is biased). When applying these
examples in real applications, it is better to use the
mean earth radius,
6371 km. This value is recommended by the International Union of
Geodesy and Geophysics and it minimizes the RMS relative error between the
great circle and geodesic distance.
| import java.lang.Math.*
const val R = 6372.8 // in kilometers
fun haversine(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val λ1 = toRadians(lat1)
val λ2 = toRadians(lat2)
val Δλ = toRadians(lat2 - lat1)
val Δφ = toRadians(lon2 - lon1)
return 2 * R * asin(sqrt(pow(sin(Δλ / 2), 2.0) + pow(sin(Δφ / 2), 2.0) * cos(λ1) * cos(λ2)))
}
fun main(args: Array<String>) = println("result: " + haversine(36.12, -86.67, 33.94, -118.40)) |
Hello world/Newbie | Kotlin | Guide a new user of a language through the steps necessary
to install the programming language and selection of a text editor if needed,
to run the languages' example in the [[Hello world/Text]] task.
* Assume the language-newbie is a programmer in another language.
* Assume the language-newbie is competent in installing software for the platform.
* Assume the language-newbie can use one simple text editor for the OS/platform, (but that may not necessarily be a particular one if the installation needs a particular editor).
* Refer to, (and link to), already existing documentation as much as possible (but provide a summary here).
* Remember to state where to view the output.
* If particular IDE's or editors are required that are not standard, then point to/explain their installation too.
;Note:
* If it is more natural for a language to give output via a GUI or to a file etc, then use that method of output rather than as text to a terminal/command-line, but remember to give instructions on how to view the output generated.
* You may use sub-headings if giving instructions for multiple platforms.
| fun main(args: Array<String>) {
println("Hello, World!")
} |
Here document | Kotlin | A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text.
Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string.
The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block.
;Task:
Demonstrate the use of ''here documents'' within the language.
;Related task:
* [[Documentation]]
| // version 1.1.0
fun main(args: Array<String>) {
val ev = "embed variables"
val here = """
This is a raw string literal
which does not treat escaped characters
(\t, \b, \n, \r, \', \", \\, \$ and \u)
specially and can contain new lines,
indentation and other whitespace
within the string.
"Quotes" or doubled ""quotes"" can
be included without problem but not
tripled quotes.
It's also possible to $ev
in a raw string literal using string
interpolation.
If you need to include a
literal ${'$'} sign in a raw string literal then
don't worry you've just done it!
"""
println(here)
} |
Heronian triangles | Kotlin from Scala | Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by:
:::: A = \sqrt{s(s-a)(s-b)(s-c)},
where ''s'' is half the perimeter of the triangle; that is,
:::: s=\frac{a+b+c}{2}.
'''Heronian triangles'''
are triangles whose sides ''and area'' are all integers.
: An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12''').
Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle.
Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor
of all three sides is '''1''' (unity).
This will exclude, for example, triangle '''6, 8, 10.'''
;Task:
# Create a named function/method/procedure/... that implements Hero's formula.
# Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200.
# Show the count of how many triangles are found.
# Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths
# Show the first ten ordered triangles in a table of sides, perimeter, and area.
# Show a similar ordered table for those triangles with area = 210
Show all output here.
'''Note''': when generating triangles it may help to restrict a <= b <= c
| import java.util.ArrayList
object Heron {
private val n = 200
fun run() {
val l = ArrayList<IntArray>()
for (c in 1..n)
for (b in 1..c)
for (a in 1..b)
if (gcd(gcd(a, b), c) == 1) {
val p = a + b + c
val s = p / 2.0
val area = Math.sqrt(s * (s - a) * (s - b) * (s - c))
if (isHeron(area))
l.add(intArrayOf(a, b, c, p, area.toInt()))
}
print("Number of primitive Heronian triangles with sides up to $n: " + l.size)
sort(l)
print("\n\nFirst ten when ordered by increasing area, then perimeter:" + header)
for (i in 0 until 10) {
print(format(l[i]))
}
val a = 210
print("\n\nArea = $a" + header)
l.filter { it[4] == a }.forEach { print(format(it)) }
}
private fun gcd(a: Int, b: Int): Int {
var leftover = 1
var dividend = if (a > b) a else b
var divisor = if (a > b) b else a
while (leftover != 0) {
leftover = dividend % divisor
if (leftover > 0) {
dividend = divisor
divisor = leftover
}
}
return divisor
}
fun sort(l: MutableList<IntArray>) {
var swapped = true
while (swapped) {
swapped = false
for (i in 1 until l.size)
if (l[i][4] < l[i - 1][4] || l[i][4] == l[i - 1][4] && l[i][3] < l[i - 1][3]) {
val temp = l[i]
l[i] = l[i - 1]
l[i - 1] = temp
swapped = true
}
}
}
private fun isHeron(h: Double) = h.rem(1) == 0.0 && h > 0
private val header = "\nSides Perimeter Area"
private fun format(a: IntArray) = "\n%3d x %3d x %3d %5d %10d".format(a[0], a[1], a[2], a[3], a[4])
}
fun main(args: Array<String>) = Heron.run() |
Hickerson series of almost integers | Kotlin from Java | The following function, due to D. Hickerson, is said to generate "Almost integers" by the
"Almost Integer" page of Wolfram MathWorld, (December 31 2013). (See formula numbered '''51'''.)
The function is: h(n) = {\operatorname{n}!\over2(\ln{2})^{n+1}}
It is said to produce "almost integers" for '''n''' between '''1''' and '''17'''.
The purpose of the task is to verify this assertion.
Assume that an "almost integer" has '''either a nine or a zero as its first digit after the decimal point''' of its decimal string representation
;Task:
Calculate all values of the function checking and stating which are "almost integers".
Note: Use extended/arbitrary precision numbers in your calculation if necessary to ensure you have adequate precision of results as for example:
h(18) = 3385534663256845326.39...
| // version 1.1.4
import java.math.BigDecimal
import java.math.BigInteger
import java.math.MathContext
object Hickerson {
private const val LN2 = "0.693147180559945309417232121458"
fun almostInteger(n: Int): Boolean {
val a = BigDecimal(LN2).pow(n + 1) * BigDecimal(2)
var nn = n
var f = n.toLong()
while (--nn > 1) f *= nn
val b = BigDecimal(f).divide(a, MathContext.DECIMAL128)
val c = b.movePointRight(1).toBigInteger() % BigInteger.TEN
return c.toString().matches(Regex("[09]"))
}
}
fun main(args: Array<String>) {
for (n in 1..17) println("${"%2d".format(n)} is almost integer: ${Hickerson.almostInteger(n)}")
} |
History variables | Kotlin | ''Storing the history of objects in a program is a common task.
Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.''
''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables.
''
"History Variables:
The Semantics, Formal Correctness, and Implementation of History Variables
in an Imperative Programming Language" by Mallon and Takaoka
Concept also discussed on LtU and Patents.com.
;Task:
Demonstrate History variable support:
* enable history variable support (if needed)
* define a history variable
* assign three values
* non-destructively display the history
* recall the three values.
For extra points, if the language of choice does not support history variables,
demonstrate how this might be implemented.
| // version 1.1.4
class HistoryVariable<T>(initialValue: T) {
private val history = mutableListOf<T>()
var currentValue: T
get() = history[history.size - 1]
set(value) {
history.add(value)
}
init {
currentValue = initialValue
}
fun showHistory() {
println("The variable's history, oldest values first, is:")
for (item in history) println(item)
}
}
fun main(args: Array<String>) {
val v = HistoryVariable(1)
v.currentValue = 2
v.currentValue = 3
v.showHistory()
println("\nCurrentvalue is ${v.currentValue}")
} |
Hofstadter-Conway $10,000 sequence | Kotlin | The definition of the sequence is colloquially described as:
* Starting with the list [1,1],
* Take the last number in the list so far: 1, I'll call it x.
* Count forward x places from the beginning of the list to find the first number to add (1)
* Count backward x places from the end of the list to find the second number to add (1)
* Add the two indexed numbers from the list and the result becomes the next number in the list (1+1)
* This would then produce [1,1,2] where 2 is the third element of the sequence.
Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''.
A less wordy description of the sequence is:
a(1)=a(2)=1
a(n)=a(a(n-1))+a(n-a(n-1))
The sequence begins:
1, 1, 2, 2, 3, 4, 4, 4, 5, ...
Interesting features of the sequence are that:
* a(n)/n tends to 0.5 as n grows towards infinity.
* a(n)/n where n is a power of 2 is 0.5
* For n>4 the maximal value of a(n)/n between successive powers of 2 decreases.
a(n) / n for n in 1..256
The sequence is so named because John Conway offered a prize of $10,000 to the first person who could
find the first position, p in the sequence where
|a(n)/n| < 0.55 for all n > p
It was later found that Hofstadter had also done prior work on the sequence.
The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article).
;Task:
# Create a routine to generate members of the Hofstadter-Conway $10,000 sequence.
# Use it to show the maxima of a(n)/n between successive powers of two up to 2**20
# As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20
;Also see:
* Conways Challenge Sequence, Mallows' own account.
* Mathworld Article.
| // version 1.1.2
fun main(args: Array<String>) {
val limit = (1 shl 20) + 1
val a = IntArray(limit)
a[1] = 1
a[2] = 1
for (n in 3 until limit) {
val p = a[n - 1]
a[n] = a[p] + a[n - p]
}
println(" Range Maximum")
println("---------------- --------")
var pow2 = 1
var p = 1
var max = a[1].toDouble()
for (n in 2 until limit) {
val r = a[n].toDouble() / n
if (r > max) max = r
if (n == pow2 * 2) {
println("2 ^ ${"%2d".format(p - 1)} to 2 ^ ${"%2d".format(p)} ${"%f".format(max)}")
pow2 *= 2
p++
max = r
}
}
var prize = 0
for (n in limit - 1 downTo 1) {
if (a[n].toDouble() / n >= 0.55) {
prize = n
break
}
}
println("\nMallows' number = $prize")
} |
Hofstadter Figure-Figure sequences | Kotlin | These two sequences of positive integers are defined as:
:::: \begin{align}
R(1)&=1\ ;\ S(1)=2 \\
R(n)&=R(n-1)+S(n-1), \quad n>1.
\end{align}
The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n).
Sequence R starts:
1, 3, 7, 12, 18, ...
Sequence S starts:
2, 4, 5, 6, 8, ...
;Task:
# Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
# No maximum value for '''n''' should be assumed.
# Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69
# Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once.
;References:
* Sloane's A005228 and A030124.
* Wolfram MathWorld
* Wikipedia: Hofstadter Figure-Figure sequences.
| fun ffr(n: Int) = get(n, 0)[n - 1]
fun ffs(n: Int) = get(0, n)[n - 1]
internal fun get(rSize: Int, sSize: Int): List<Int> {
val rlist = arrayListOf(1, 3, 7)
val slist = arrayListOf(2, 4, 5, 6)
val list = if (rSize > 0) rlist else slist
val targetSize = if (rSize > 0) rSize else sSize
while (list.size > targetSize)
list.removeAt(list.size - 1)
while (list.size < targetSize) {
val lastIndex = rlist.lastIndex
val lastr = rlist[lastIndex]
val r = lastr + slist[lastIndex]
rlist += r
var s = lastr + 1
while (s < r && list.size < targetSize)
slist += s++
}
return list
}
fun main(args: Array<String>) {
print("R():")
(1..10).forEach { print(" " + ffr(it)) }
println()
val first40R = (1..40).map { ffr(it) }
val first960S = (1..960).map { ffs(it) }
val indices = (1..1000).filter { it in first40R == it in first960S }
indices.forEach { println("Integer $it either in both or neither set") }
println("Done")
} |
Hofstadter Q sequence | Kotlin | The Hofstadter Q sequence is defined as:
:: \begin{align}
Q(1)&=Q(2)=1, \\
Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2.
\end{align}
It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.
;Task:
* Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6
* Confirm and display that the 1000th term is: 502
;Optional extra credit
* Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term.
* Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large.
(This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
| // version 1.1.4
fun main(args: Array<String>) {
val q = IntArray(100_001)
q[1] = 1
q[2] = 1
for (n in 3..100_000) q[n] = q[n - q[n - 1]] + q[n - q[n - 2]]
print("The first 10 terms are : ")
for (i in 1..10) print("${q[i]} ")
println("\n\nThe 1000th term is : ${q[1000]}")
val flips = (2..100_000).count { q[it] < q[it - 1] }
println("\nThe number of flips for the first 100,000 terms is : $flips")
} |
Honeycombs | Kotlin | The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five
columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should
display a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen.
Optionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.)
[[image:honeycomb.gif]]
| // version 1.1.4
import java.awt.BasicStroke
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.Graphics
import java.awt.Graphics2D
import java.awt.Polygon
import java.awt.RenderingHints
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.awt.event.WindowEvent
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.SwingUtilities
class Honeycombs : JPanel() {
private val comb: Array<Hexagon?> = arrayOfNulls(20)
init {
preferredSize = Dimension(600, 500)
background = Color.white
isFocusable = true
addMouseListener(object : MouseAdapter() {
override fun mousePressed(e: MouseEvent) {
for (hex in comb)
if (hex!!.contains(e.x, e.y)) {
hex.setSelected()
checkForClosure()
break
}
repaint()
}
})
addKeyListener(object : KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
for (hex in comb)
if (hex!!.letter == e.keyChar.toUpperCase()) {
hex.setSelected()
checkForClosure()
break
}
repaint()
}
})
val letters = "LRDGITPFBVOKANUYCESM".toCharArray()
val x1 = 150
val y1 = 100
val x2 = 225
val y2 = 143
val w = 150
val h = 87
for (i in 0 until comb.size) {
var x: Int
var y: Int
if (i < 12) {
x = x1 + (i % 3) * w
y = y1 + (i / 3) * h
}
else {
x = x2 + (i % 2) * w
y = y2 + ((i - 12) / 2) * h
}
comb[i] = Hexagon(x, y, w / 3, letters[i])
}
requestFocus()
}
override fun paintComponent(gg: Graphics) {
super.paintComponent(gg)
val g = gg as Graphics2D
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON)
g.font = Font("SansSerif", Font.BOLD, 30)
g.stroke = BasicStroke(3.0f)
for (hex in comb) hex!!.draw(g)
}
private fun checkForClosure() {
if (comb.all { it!!.hasBeenSelected } ) {
val f = SwingUtilities.getWindowAncestor(this) as JFrame
f.dispatchEvent(WindowEvent(f, WindowEvent.WINDOW_CLOSING))
}
}
}
class Hexagon(x: Int, y: Int, halfWidth: Int, c: Char) : Polygon() {
private val baseColor = Color.yellow
private val selectedColor = Color.magenta
var hasBeenSelected = false
val letter = c
init {
for (i in 0..5)
addPoint((x + halfWidth * Math.cos(i * Math.PI / 3.0)).toInt(),
(y + halfWidth * Math.sin(i * Math.PI / 3.0)).toInt())
getBounds()
}
fun setSelected() {
hasBeenSelected = true
}
fun draw(g: Graphics2D) {
with(g) {
color = if (hasBeenSelected) selectedColor else baseColor
fillPolygon(this@Hexagon)
color = Color.black
drawPolygon(this@Hexagon)
color = if (hasBeenSelected) Color.black else Color.red
drawCenteredString(g, letter.toString())
}
}
private fun drawCenteredString(g: Graphics2D, s: String) {
val fm = g.fontMetrics
val asc = fm.ascent
val dec = fm.descent
val x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2
val y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2)
g.drawString(s, x, y)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = JFrame()
with(f) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
add(Honeycombs(), BorderLayout.CENTER)
title = "Honeycombs"
isResizable = false
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
} |
Horner's rule for polynomial evaluation | Kotlin | A fast scheme for evaluating a polynomial such as:
: -19+7x-4x^2+6x^3\,
when
: x=3\;.
is to arrange the computation as follows:
: ((((0) x + 6) x + (-4)) x + 7) x + (-19)\;
And compute the result from the innermost brackets outwards as in this pseudocode:
coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order''
x ''':=''' 3
accumulator ''':=''' 0
'''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do'''
''# Assumes 1-based indexing for arrays''
accumulator ''':=''' ( accumulator * x ) + coefficients[i]
'''done'''
''# accumulator now has the answer''
'''Task Description'''
:Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule.
Cf. [[Formal power series]]
| // version 1.1.2
fun horner(coeffs: DoubleArray, x: Double): Double {
var sum = 0.0
for (i in coeffs.size - 1 downTo 0) sum = sum * x + coeffs[i]
return sum
}
fun main(args: Array<String>) {
val coeffs = doubleArrayOf(-19.0, 7.0, -4.0, 6.0)
println(horner(coeffs, 3.0))
} |
ISBN13 check digit | Kotlin | Validate the check digit of an ISBN-13 code:
::* Multiply every other digit by '''3'''.
::* Add these numbers and the other digits.
::* Take the remainder of this number after division by '''10'''.
::* If it is '''0''', the ISBN-13 check digit is correct.
You might use the following codes for testing:
::::* 978-0596528126 (good)
::::* 978-0596528120 (bad)
::::* 978-1788399081 (good)
::::* 978-1788399083 (bad)
Show output here, on this page
;See also:
:* for details: 13-digit ISBN method of validation. (installs cookies.)
| describe("ISBN Utilities") {
mapOf(
"978-1734314502" to true,
"978-1734314509" to false,
"978-1788399081" to true,
"978-1788399083" to false
).forEach { (input, expected) ->
it("returns $expected for $input") {
println("$input: ${when(isValidISBN13(input)) {
true -> "good"
else -> "bad"
}}")
assert(isValidISBN13(input) == expected)
}
}
}
|
I before E except after C | Kotlin | The phrase "I before E, except after C" is a
widely known mnemonic which is supposed to help when spelling English words.
;Task:
Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt,
check if the two sub-clauses of the phrase are plausible individually:
:::# ''"I before E when not preceded by C"''
:::# ''"E before I when preceded by C"''
If both sub-phrases are plausible then the original phrase can be said to be plausible.
Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate).
;Stretch goal:
As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account.
''Show your output here as well as your program.''
;cf.:
* Schools to rethink 'i before e' - BBC news, 20 June 2009
* I Before E Except After C - QI Series 8 Ep 14, (humorous)
* Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
| // version 1.0.6
import java.net.URL
import java.io.InputStreamReader
import java.io.BufferedReader
fun isPlausible(n1: Int, n2: Int) = n1 > 2 * n2
fun printResults(source: String, counts: IntArray) {
println("Results for $source")
println(" i before e except after c")
println(" for ${counts[0]}")
println(" against ${counts[1]}")
val plausible1 = isPlausible(counts[0], counts[1])
println(" sub-rule is${if (plausible1) "" else " not"} plausible\n")
println(" e before i when preceded by c")
println(" for ${counts[2]}")
println(" against ${counts[3]}")
val plausible2 = isPlausible(counts[2], counts[3])
println(" sub-rule is${if (plausible2) "" else " not"} plausible\n")
val plausible = plausible1 && plausible2
println(" rule is${if (plausible) "" else " not"} plausible")
}
fun main(args: Array<String>) {
val url = URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
val isr = InputStreamReader(url.openStream())
val reader = BufferedReader(isr)
val regexes = arrayOf(
Regex("(^|[^c])ie"), // i before e when not preceded by c (includes words starting with ie)
Regex("(^|[^c])ei"), // e before i when not preceded by c (includes words starting with ei)
Regex("cei"), // e before i when preceded by c
Regex("cie") // i before e when preceded by c
)
val counts = IntArray(4) // corresponding counts of occurrences
var word = reader.readLine()
while (word != null) {
for (i in 0..3) counts[i] += regexes[i].findAll(word).toList().size
word = reader.readLine()
}
reader.close()
printResults("unixdict.txt", counts)
val url2 = URL("http://ucrel.lancs.ac.uk/bncfreq/lists/1_2_all_freq.txt")
val isr2 = InputStreamReader(url2.openStream())
val reader2 = BufferedReader(isr2)
val counts2 = IntArray(4)
reader2.readLine() // read header line
var line = reader2.readLine() // read first line and store it
var words: List<String>
val splitter = Regex("""(\t+|\s+)""")
while (line != null) {
words = line.split(splitter)
if (words.size == 4) // first element is empty
for (i in 0..3) counts2[i] += regexes[i].findAll(words[1]).toList().size * words[3].toInt()
line = reader2.readLine()
}
reader2.close()
println()
printResults("British National Corpus", counts2)
} |
Identity matrix | Kotlin | Build an identity matrix of a size known at run-time.
An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''',
where the diagonal elements are all '''1'''s (ones),
and all the other elements are all '''0'''s (zeroes).
I_n = \begin{bmatrix}
1 & 0 & 0 & \cdots & 0 \\
0 & 1 & 0 & \cdots & 0 \\
0 & 0 & 1 & \cdots & 0 \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
0 & 0 & 0 & \cdots & 1 \\
\end{bmatrix}
;Related tasks:
* [[Spiral matrix]]
* [[Zig-zag matrix]]
* [[Ulam_spiral_(for_primes)]]
| // version 1.0.6
fun main(args: Array<String>) {
print("Enter size of matrix : ")
val n = readLine()!!.toInt()
println()
val identity = Array(n) { IntArray(n) } // create n x n matrix of integers
// enter 1s in diagonal elements
for(i in 0 until n) identity[i][i] = 1
// print identity matrix if n <= 40
if (n <= 40)
for (i in 0 until n) println(identity[i].joinToString(" "))
else
println("Matrix is too big to display on 80 column console")
} |
Idiomatically determine all the characters that can be used for symbols | Kotlin from Java | Idiomatically determine all the characters that can be used for ''symbols''.
The word ''symbols'' is meant things like names of variables, procedures (i.e., named fragments of programs, functions, subroutines, routines), statement labels, events or conditions, and in general, anything a computer programmer can choose to ''name'', but not being restricted to this list. ''Identifiers'' might be another name for ''symbols''.
The method should find the characters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all the characters that can be used for symbols which can be used (allowed) by the computer program.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
Note that most languages have additional restrictions on what characters can't be used for the first character of a variable or statement label, for instance. These type of restrictions needn't be addressed here (but can be mentioned).
;See also
* Idiomatically determine all the lowercase and uppercase letters.
| // version 1.1.4-3
typealias CharPredicate = (Char) -> Boolean
fun printChars(msg: String, start: Int, end: Int, limit: Int, p: CharPredicate, asInt: Boolean) {
print(msg)
(start until end).map { it.toChar() }
.filter { p(it) }
.take(limit)
.forEach { print(if (asInt) "[${it.toInt()}]" else it) }
println("...")
}
fun main(args: Array<String>) {
printChars("Kotlin Identifier start: ", 0, 0x10FFFF, 72,
Char::isJavaIdentifierStart, false)
printChars("Kotlin Identifier part: ", 0, 0x10FFFF, 25,
Character::isJavaIdentifierPart, true)
printChars("Kotlin Identifier ignorable: ", 0, 0x10FFFF, 25,
Character::isIdentifierIgnorable, true)
} |
Idiomatically determine all the lowercase and uppercase letters | Kotlin | Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language.
The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other).
;Task requirements
Display the set of all:
::::::* lowercase letters
::::::* uppercase letters
that can be used (allowed) by the computer program,
where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''.
You may want to mention what hardware architecture is being used, and if applicable, the operating system.
;See also
* Idiomatically determine all the characters that can be used for symbols.
| // version 1.0.6
fun main(args: Array<String>) {
print("Lower case : ")
for (ch in 'a'..'z') print(ch)
print("\nUpper case : ")
for (ch in 'A'..'Z') print(ch)
println()
} |
Imaginary base numbers | Kotlin | Imaginary base numbers are a non-standard positional numeral system which uses an imaginary number as its radix. The most common is quater-imaginary with radix 2i.
''The quater-imaginary numeral system was first proposed by Donald Knuth in 1955 as a submission for a high school science talent search. [Ref.]''
Other imaginary bases are possible too but are not as widely discussed and aren't specifically named.
'''Task:''' Write a set of procedures (functions, subroutines, however they are referred to in your language) to convert base 10 numbers to an imaginary base and back.
At a minimum, support quater-imaginary (base 2i).
For extra kudos, support positive or negative bases 2i through 6i (or higher).
As a stretch goal, support converting non-integer numbers ( E.G. 227.65625+10.859375i ) to an imaginary base.
See Wikipedia: Quater-imaginary_base for more details.
For reference, here are some some decimal and complex numbers converted to quater-imaginary.
Base 10
Base 2i
1
1
2
2
3
3
4
10300
5
10301
6
10302
7
10303
8
10200
9
10201
10
10202
11
10203
12
10100
13
10101
14
10102
15
10103
16
10000
Base 10
Base 2i
-1
103
-2
102
-3
101
-4
100
-5
203
-6
202
-7
201
-8
200
-9
303
-10
302
-11
301
-12
300
-13
1030003
-14
1030002
-15
1030001
-16
1030000
Base 10
Base 2i
1i
10.2
2i
10.0
3i
20.2
4i
20.0
5i
30.2
6i
30.0
7i
103000.2
8i
103000.0
9i
103010.2
10i
103010.0
11i
103020.2
12i
103020.0
13i
103030.2
14i
103030.0
15i
102000.2
16i
102000.0
Base 10
Base 2i
-1i
0.2
-2i
1030.0
-3i
1030.2
-4i
1020.0
-5i
1020.2
-6i
1010.0
-7i
1010.2
-8i
1000.0
-9i
1000.2
-10i
2030.0
-11i
2030.2
-12i
2020.0
-13i
2020.2
-14i
2010.0
-15i
2010.2
-16i
2000.0
| // version 1.2.10
import kotlin.math.ceil
class Complex(val real: Double, val imag: Double) {
constructor(r: Int, i: Int) : this(r.toDouble(), i.toDouble())
operator fun plus(other: Complex) = Complex(real + other.real, imag + other.imag)
operator fun times(other: Complex) = Complex(
real * other.real - imag * other.imag,
real * other.imag + imag * other.real
)
operator fun times(other: Double) = Complex(real * other, imag * other)
fun inv(): Complex {
val denom = real * real + imag * imag
return Complex(real / denom, -imag / denom)
}
operator fun unaryMinus() = Complex(-real, -imag)
operator fun minus(other: Complex) = this + (-other)
operator fun div(other: Complex) = this * other.inv()
// only works properly if 'real' and 'imag' are both integral
fun toQuaterImaginary(): QuaterImaginary {
if (real == 0.0 && imag == 0.0) return QuaterImaginary("0")
var re = real.toInt()
var im = imag.toInt()
var fi = -1
val sb = StringBuilder()
while (re != 0) {
var rem = re % -4
re /= -4
if (rem < 0) {
rem = 4 + rem
re++
}
sb.append(rem)
sb.append(0)
}
if (im != 0) {
var f = (Complex(0.0, imag) / Complex(0.0, 2.0)).real
im = ceil(f).toInt()
f = -4.0 * (f - im.toDouble())
var index = 1
while (im != 0) {
var rem = im % -4
im /= -4
if (rem < 0) {
rem = 4 + rem
im++
}
if (index < sb.length) {
sb[index] = (rem + 48).toChar()
}
else {
sb.append(0)
sb.append(rem)
}
index += 2
}
fi = f.toInt()
}
sb.reverse()
if (fi != -1) sb.append(".$fi")
var s = sb.toString().trimStart('0')
if (s.startsWith(".")) s = "0$s"
return QuaterImaginary(s)
}
override fun toString(): String {
val real2 = if (real == -0.0) 0.0 else real // get rid of negative zero
val imag2 = if (imag == -0.0) 0.0 else imag // ditto
var result = if (imag2 >= 0.0) "$real2 + ${imag2}i" else "$real2 - ${-imag2}i"
result = result.replace(".0 ", " ").replace(".0i", "i").replace(" + 0i", "")
if (result.startsWith("0 + ")) result = result.drop(4)
if (result.startsWith("0 - ")) result = "-" + result.drop(4)
return result
}
}
class QuaterImaginary(val b2i: String) {
init {
if (b2i == "" || !b2i.all { it in "0123." } || b2i.count { it == '.'} > 1 )
throw RuntimeException("Invalid Base 2i number")
}
fun toComplex(): Complex {
val pointPos = b2i.indexOf(".")
var posLen = if (pointPos != -1) pointPos else b2i.length
var sum = Complex(0.0, 0.0)
var prod = Complex(1.0, 0.0)
for (j in 0 until posLen) {
val k = (b2i[posLen - 1 - j] - '0').toDouble()
if (k > 0.0) sum += prod * k
prod *= twoI
}
if (pointPos != -1) {
prod = invTwoI
for (j in posLen + 1 until b2i.length) {
val k = (b2i[j] - '0').toDouble()
if (k > 0.0) sum += prod * k
prod *= invTwoI
}
}
return sum
}
override fun toString() = b2i
companion object {
val twoI = Complex(0.0, 2.0)
val invTwoI = twoI.inv()
}
}
fun main(args: Array<String>) {
val fmt = "%4s -> %8s -> %4s"
for (i in 1..16) {
var c1 = Complex(i, 0)
var qi = c1.toQuaterImaginary()
var c2 = qi.toComplex()
print("$fmt ".format(c1, qi, c2))
c1 = -c1
qi = c1.toQuaterImaginary()
c2 = qi.toComplex()
println(fmt.format(c1, qi, c2))
}
println()
for (i in 1..16) {
var c1 = Complex(0, i)
var qi = c1.toQuaterImaginary()
var c2 = qi.toComplex()
print("$fmt ".format(c1, qi, c2))
c1 = -c1
qi = c1.toQuaterImaginary()
c2 = qi.toComplex()
println(fmt.format(c1, qi, c2))
}
} |
Include a file | Kotlin | Demonstrate the language's ability to include source code from other files.
;See Also
* [[Compiler/Simple file inclusion pre processor]]
| // version 1.1.2
import package1.f // import f from package `package1`
fun main(args: Array<String>) {
f() // invoke f without qualification
} |
Index finite lists of positive integers | Kotlin | It is known that the set of finite lists of positive integers is countable.
This means that there exists a subset of natural integers which can be mapped to the set of finite lists of positive integers.
;Task:
Implement such a mapping:
:* write a function ''rank'' which assigns an integer to any finite, arbitrarily long list of arbitrary large positive integers.
:* write a function ''unrank'' which is the ''rank'' inverse function.
Demonstrate your solution by:
:* picking a random-length list of random positive integers
:* turn it into an integer, and
:* get the list back.
There are many ways to do this. Feel free to choose any one you like.
;Extra credit:
Make the ''rank'' function as a bijection and show ''unrank(n)'' for '''n''' varying from '''0''' to '''10'''.
| // version 1.1.2
import java.math.BigInteger
/* Separates each integer in the list with an 'a' then encodes in base 11. Empty list mapped to '-1' */
fun rank(li: List<Int>) = when (li.size) {
0 -> -BigInteger.ONE
else -> BigInteger(li.joinToString("a"), 11)
}
fun unrank(r: BigInteger) = when (r) {
-BigInteger.ONE -> emptyList<Int>()
else -> r.toString(11).split('a').map { if (it != "") it.toInt() else 0 }
}
/* Each integer n in the list mapped to '1' plus n '0's. Empty list mapped to '0' */
fun rank2(li:List<Int>): BigInteger {
if (li.isEmpty()) return BigInteger.ZERO
val sb = StringBuilder()
for (i in li) sb.append("1" + "0".repeat(i))
return BigInteger(sb.toString(), 2)
}
fun unrank2(r: BigInteger) = when (r) {
BigInteger.ZERO -> emptyList<Int>()
else -> r.toString(2).drop(1).split('1').map { it.length }
}
fun main(args: Array<String>) {
var li: List<Int>
var r: BigInteger
li = listOf(0, 1, 2, 3, 10, 100, 987654321)
println("Before ranking : $li")
r = rank(li)
println("Rank = $r")
li = unrank(r)
println("After unranking : $li")
println("\nAlternative approach (not suitable for large numbers)...\n")
li = li.dropLast(1)
println("Before ranking : $li")
r = rank2(li)
println("Rank = $r")
li = unrank2(r)
println("After unranking : $li")
println()
for (i in 0..10) {
val bi = BigInteger.valueOf(i.toLong())
li = unrank2(bi)
println("${"%2d".format(i)} -> ${li.toString().padEnd(9)} -> ${rank2(li)}")
}
} |
Integer overflow | Kotlin | Some languages support one or more integer types of the underlying processor.
This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit.
The integers supported by such a type can be ''signed'' or ''unsigned''.
Arithmetic for machine level integers can often be done by single CPU instructions.
This allows high performance and is the main reason to support machine level integers.
;Definition:
An integer overflow happens when the result of a computation does not fit into the fixed size integer.
The result can be too small or too big to be representable in the fixed size integer.
;Task:
When a language has fixed size integer types, create a program that
does arithmetic computations for the fixed size integers of the language.
These computations must be done such that the result would overflow.
The program should demonstrate what the following expressions do.
For 32-bit signed integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit signed integer
|-
| -(-2147483647-1)
| 2147483648
|-
| 2000000000 + 2000000000
| 4000000000
|-
| -2147483647 - 2147483647
| -4294967294
|-
| 46341 * 46341
| 2147488281
|-
| (-2147483647-1) / -1
| 2147483648
|}
For 64-bit signed integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit signed integer
|-
| -(-9223372036854775807-1)
| 9223372036854775808
|-
| 5000000000000000000+5000000000000000000
| 10000000000000000000
|-
| -9223372036854775807 - 9223372036854775807
| -18446744073709551614
|-
| 3037000500 * 3037000500
| 9223372037000250000
|-
| (-9223372036854775807-1) / -1
| 9223372036854775808
|}
For 32-bit unsigned integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit unsigned integer
|-
| -4294967295
| -4294967295
|-
| 3000000000 + 3000000000
| 6000000000
|-
| 2147483647 - 4294967295
| -2147483648
|-
| 65537 * 65537
| 4295098369
|}
For 64-bit unsigned integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit unsigned integer
|-
| -18446744073709551615
| -18446744073709551615
|-
| 10000000000000000000 + 10000000000000000000
| 20000000000000000000
|-
| 9223372036854775807 - 18446744073709551615
| -9223372036854775808
|-
| 4294967296 * 4294967296
| 18446744073709551616
|}
;Notes:
:* When the integer overflow does trigger an exception show how the exception is caught.
:* When the integer overflow produces some value, print it.
:* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results.
:* This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
:* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted.
:* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
| // The Kotlin compiler can detect expressions of signed constant integers that will overflow.
// It cannot detect unsigned integer overflow, however.
@Suppress("INTEGER_OVERFLOW")
fun main() {
println("*** Signed 32 bit integers ***\n")
println(-(-2147483647 - 1))
println(2000000000 + 2000000000)
println(-2147483647 - 2147483647)
println(46341 * 46341)
println((-2147483647 - 1) / -1)
println("\n*** Signed 64 bit integers ***\n")
println(-(-9223372036854775807 - 1))
println(5000000000000000000 + 5000000000000000000)
println(-9223372036854775807 - 9223372036854775807)
println(3037000500 * 3037000500)
println((-9223372036854775807 - 1) / -1)
println("\n*** Unsigned 32 bit integers ***\n")
// println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator
// println(0U - 4294967295U) // this works
println((-4294967295).toUInt()) // converting from the signed Int type also produces the overflow; this is intended behavior of toUInt()
println(3000000000U + 3000000000U)
println(2147483647U - 4294967295U)
println(65537U * 65537U)
println("\n*** Unsigned 64 bit integers ***\n")
println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction
println(10000000000000000000U + 10000000000000000000U)
println(9223372036854775807U - 18446744073709551615U)
println(4294967296U * 4294967296U)
} |
Integer sequence | Kotlin | Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time.
An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library.
If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
| import java.math.BigInteger
// version 1.0.5-2
fun main(args: Array<String>) {
// print until 2147483647
(0..Int.MAX_VALUE).forEach { println(it) }
// print forever
var n = BigInteger.ZERO
while (true) {
println(n)
n += BigInteger.ONE
}
} |
Intersecting number wheels | Kotlin from Java | A number wheel has:
* A ''name'' which is an uppercase letter.
* A set of ordered ''values'' which are either ''numbers'' or ''names''.
A ''number'' is generated/yielded from a named wheel by:
:1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel":
::1.a If the value is a number, yield it.
::1.b If the value is a name, yield the next value from the named wheel
::1.c Advance the position of this wheel.
Given the wheel
: A: 1 2 3
the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ...
'''Note:''' When more than one wheel is defined as a set of intersecting wheels then the
first named wheel is assumed to be the one that values are generated from.
;Examples:
Given the wheels:
A: 1 B 2
B: 3 4
The series of numbers generated starts:
1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2...
The intersections of number wheels can be more complex, (and might loop forever),
and wheels may be multiply connected.
'''Note:''' If a named wheel is referenced more than
once by one or many other wheels, then there is only one position of the wheel
that is advanced by each and all references to it.
E.g.
A: 1 D D
D: 6 7 8
Generates:
1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ...
;Task:
Generate and show the first twenty terms of the sequence of numbers generated
from these groups:
Intersecting Number Wheel group:
A: 1 2 3
Intersecting Number Wheel group:
A: 1 B 2
B: 3 4
Intersecting Number Wheel group:
A: 1 D D
D: 6 7 8
Intersecting Number Wheel group:
A: 1 B C
B: 3 4
C: 5 B
Show your output here, on this page.
| import java.util.Collections
import java.util.stream.IntStream
object WheelController {
private val IS_NUMBER = "[0-9]".toRegex()
private const val TWENTY = 20
private var wheelMap = mutableMapOf<String, WheelModel>()
private fun advance(wheel: String) {
val w = wheelMap[wheel]
if (w!!.list[w.position].matches(IS_NUMBER)) {
w.printThePosition()
} else {
val wheelName = w.list[w.position]
advance(wheelName)
}
w.advanceThePosition()
}
private fun run() {
println(wheelMap)
IntStream.rangeClosed(1, TWENTY)
.forEach { advance("A") }
println()
wheelMap.clear()
}
@JvmStatic
fun main(args: Array<String>) {
wheelMap["A"] = WheelModel("1", "2", "3")
run()
wheelMap["A"] = WheelModel("1", "B", "2")
wheelMap["B"] = WheelModel("3", "4")
run()
wheelMap["A"] = WheelModel("1", "D", "D")
wheelMap["D"] = WheelModel("6", "7", "8")
run()
wheelMap["A"] = WheelModel("1", "B", "C")
wheelMap["B"] = WheelModel("3", "4")
wheelMap["C"] = WheelModel("5", "B")
run()
}
}
internal class WheelModel(vararg values: String?) {
var list = mutableListOf<String>()
var position: Int
private var endPosition: Int
override fun toString(): String {
return list.toString()
}
fun advanceThePosition() {
if (position == endPosition) {
position = INITIAL // new beginning
} else {
position++ // advance position
}
}
fun printThePosition() {
print(" ${list[position]}")
}
companion object {
private const val INITIAL = 0
}
init {
Collections.addAll<String>(list, *values)
position = INITIAL
endPosition = list.size - 1
}
} |
Inverted syntax | Kotlin | '''Inverted syntax with conditional expressions'''
In traditional syntax conditional expressions are usually shown before the action within a statement or code block:
IF raining=true THEN needumbrella=true
In inverted syntax, the action is listed before the conditional expression in the statement or code block:
needumbrella=true IF raining=true
'''Inverted syntax with assignment'''
In traditional syntax, assignments are usually expressed with the variable appearing before the expression:
a = 6
In inverted syntax, the expression appears before the variable:
6 = a
'''Task'''
The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
| // version 1.0.6
infix fun Boolean.iif(cond: Boolean) = if (cond) this else !this
fun main(args: Array<String>) {
val raining = true
val needUmbrella = true iif (raining)
println("Do I need an umbrella? ${if(needUmbrella) "Yes" else "No"}")
} |
Isqrt (integer square root) of X | Kotlin from Go | Sometimes a function is needed to find the integer square root of '''X''', where '''X''' can be a
real non-negative number.
Often '''X''' is actually a non-negative integer.
For the purposes of this task, '''X''' can be an integer or a real number, but if it
simplifies things in your computer programming language, assume it's an integer.
One of the most common uses of '''Isqrt''' is in the division of an integer by all factors (or
primes) up to the
X of that
integer, either to find the factors of that integer, or to determine primality.
An alternative method for finding the '''Isqrt''' of a number is to
calculate: floor( sqrt(X) )
::* where '''sqrt''' is the square root function for non-negative real numbers, and
::* where '''floor''' is the floor function for real numbers.
If the hardware supports the computation of (real) square roots, the above method might be a faster method for
small numbers that don't have very many significant (decimal) digits.
However, floating point arithmetic is limited in the number of (binary or decimal) digits that it can support.
;Pseudo-code using quadratic residue:
For this task, the integer square root of a non-negative number will be computed using a version
of ''quadratic residue'', which has the advantage that no ''floating point'' calculations are
used, only integer arithmetic.
Furthermore, the two divisions can be performed by bit shifting, and the one multiplication can also be be performed by bit shifting or additions.
The disadvantage is the limitation of the size of the largest integer that a particular computer programming language can support.
Pseudo-code of a procedure for finding the integer square root of '''X''' (all variables are integers):
q <-- 1 /*initialize Q to unity. */
/*find a power of 4 that's greater than X.*/
perform while q <= x /*perform while Q <= X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
/*Q is now greater than X.*/
z <-- x /*set Z to the value of X.*/
r <-- 0 /*initialize R to zero. */
perform while q > 1 /*perform while Q > unity. */
q <-- q / 4 /*integer divide by four. */
t <-- z - r - q /*compute value of T. */
r <-- r / 2 /*integer divide by two. */
if t >= 0 then do
z <-- t /*set Z to value of T. */
r <-- r + q /*compute new value of R. */
end
end /*perform*/
/*R is now the Isqrt(X). */
/* Sidenote: Also, Z is now the remainder after square root (i.e. */
/* R^2 + Z = X, so if Z = 0 then X is a perfect square). */
Another version for the (above) 1st '''perform''' is:
perform until q > X /*perform until Q > X. */
q <-- q * 4 /*multiply Q by four. */
end /*perform*/
Integer square roots of some values:
Isqrt( 0) is 0 Isqrt(60) is 7 Isqrt( 99) is 9
Isqrt( 1) is 1 Isqrt(61) is 7 Isqrt(100) is 10
Isqrt( 2) is 1 Isqrt(62) is 7 Isqrt(102) is 10
Isqrt( 3) is 1 Isqrt(63) is 7
Isqrt( 4) is 2 Isqrt(64) is 8 Isqet(120) is 10
Isqrt( 5) is 2 Isqrt(65) is 8 Isqrt(121) is 11
Isqrt( 6) is 2 Isqrt(66) is 8 Isqrt(122) is 11
Isqrt( 7) is 2 Isqrt(67) is 8
Isqrt( 8) is 2 Isqrt(68) is 8 Isqrt(143) is 11
Isqrt( 9) is 3 Isqrt(69) is 8 Isqrt(144) is 12
Isqrt(10) is 3 Isqrt(70) is 8 Isqrt(145) is 12
;Task:
Compute and show all output here (on this page) for:
::* the Isqrt of the integers from '''0''' ---> '''65''' (inclusive), shown in a horizontal format.
::* the Isqrt of the odd powers from '''71''' ---> '''773''' (inclusive), shown in a vertical format.
::* use commas in the displaying of larger numbers.
You can show more numbers for the 2nd requirement if the displays fits on one screen on Rosetta Code.
If your computer programming language only supports smaller integers, show what you can.
;Related tasks:
:* sequence of non-squares
:* integer roots
:* square root by hand
| import java.math.BigInteger
fun isqrt(x: BigInteger): BigInteger {
if (x < BigInteger.ZERO) {
throw IllegalArgumentException("Argument cannot be negative")
}
var q = BigInteger.ONE
while (q <= x) {
q = q.shiftLeft(2)
}
var z = x
var r = BigInteger.ZERO
while (q > BigInteger.ONE) {
q = q.shiftRight(2)
var t = z
t -= r
t -= q
r = r.shiftRight(1)
if (t >= BigInteger.ZERO) {
z = t
r += q
}
}
return r
}
fun main() {
println("The integer square root of integers from 0 to 65 are:")
for (i in 0..65) {
print("${isqrt(BigInteger.valueOf(i.toLong()))} ")
}
println()
println("The integer square roots of powers of 7 from 7^1 up to 7^73 are:")
println("power 7 ^ power integer square root")
println("----- --------------------------------------------------------------------------------- -----------------------------------------")
var pow7 = BigInteger.valueOf(7)
val bi49 = BigInteger.valueOf(49)
for (i in (1..73).step(2)) {
println("%2d %,84d %,41d".format(i, pow7, isqrt(pow7)))
pow7 *= bi49
}
} |
Iterated digits squaring | Kotlin from FreeBASIC | If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89:
15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89
7 -> 49 -> 97 -> 130 -> 10 -> 1
An example in Python:
>>> step = lambda x: sum(int(d) ** 2 for d in str(x))
>>> iterate = lambda x: x if x in [1, 89] else iterate(step(x))
>>> [iterate(x) for x in xrange(1, 20)]
[1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1]
;Task:
: Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89.
Or, for much less credit - (showing that your algorithm and/or language is slow):
: Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89.
This problem derives from the Project Euler problem 92.
For a quick algorithm for this task see the talk page
;Related tasks:
* [[Combinations with repetitions]]
* [[Digital root]]
* [[Digital root/Multiplicative digital root]]
| // version 1.0.6
fun endsWith89(n: Int): Boolean {
var digit: Int
var sum = 0
var nn = n
while (true) {
while (nn > 0) {
digit = nn % 10
sum += digit * digit
nn /= 10
}
if (sum == 89) return true
if (sum == 1) return false
nn = sum
sum = 0
}
}
fun main(args: Array<String>) {
val sums = IntArray(8 * 81 + 1)
sums[0] = 1
sums[1] = 0
var s: Int
for (n in 1 .. 8)
for (i in n * 81 downTo 1)
for (j in 1 .. 9) {
s = j * j
if (s > i) break
sums[i] += sums[i - s]
}
var count89 = 0
for (i in 1 .. 8 * 81)
if (endsWith89(i)) count89 += sums[i]
println("There are $count89 numbers from 1 to 100 million ending with 89")
} |
JSON | Kotlin | Load a JSON string into a data structure.
Also, create a new data structure and serialize it into JSON.
Use objects and arrays (as appropriate for your language)
and make sure your JSON is valid (https://jsonformatter.org).
| // version 1.2.21
data class JsonObject(val foo: Int, val bar: Array<String>)
data class JsonObject2(val ocean: String, val blue: Array<Int>)
fun main(args: Array<String>) {
// JSON to object
val data: JsonObject = JSON.parse("""{ "foo": 1, "bar": ["10", "apples"] }""")
println(JSON.stringify(data))
// object to JSON
val data2 = JsonObject2("water", arrayOf(1, 2))
println(JSON.stringify(data2))
} |
Jacobi symbol | Kotlin | The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p)
* (a | p) 1 if a is a square (mod p)
* (a | p) -1 if a is not a square (mod p)
* (a | p) 0 if a 0
If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n).
;Task:
Calculate the Jacobi symbol (a | n).
;Reference:
* Wikipedia article on Jacobi symbol.
| fun jacobi(A: Int, N: Int): Int {
assert(N > 0 && N and 1 == 1)
var a = A % N
var n = N
var result = 1
while (a != 0) {
var aMod4 = a and 3
while (aMod4 == 0) { // remove factors of four
a = a shr 2
aMod4 = a and 3
}
if (aMod4 == 2) { // if even
a = a shr 1 // remove factor 2 and possibly change sign
if ((n and 7).let { it == 3 || it == 5 })
result = -result
aMod4 = a and 3
}
if (aMod4 == 3 && n and 3 == 3)
result = -result
a = (n % a).also { n = a }
}
return if (n == 1) result else 0
} |
Jaro similarity | Kotlin from Java | The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match.
;;Definition
The Jaro similarity d_j of two given strings s_1 and s_2 is
: d_j = \left\{
\begin{array}{l l}
0 & \text{if }m = 0\\
\frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right.
Where:
* m is the number of ''matching characters'';
* t is half the number of ''transpositions''.
Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters.
Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one.
;;Example
Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find:
* m = 4
* |s_1| = 6
* |s_2| = 5
* t = 0
We find a Jaro score of:
: d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822
;Task
Implement the Jaro algorithm and show the similarity scores for each of the following pairs:
* ("MARTHA", "MARHTA")
* ("DIXON", "DICKSONX")
* ("JELLYFISH", "SMELLYFISH")
; See also
* Jaro-Winkler distance on Wikipedia.
| object Jaro {
fun distance(s1: String, s2: String): Double {
val s1_len = s1.length
val s2_len = s2.length
if (s1_len == 0 && s2_len == 0) return 1.0
val match_distance = Math.max(s1_len, s2_len) / 2 - 1
val s1_matches = BooleanArray(s1_len)
val s2_matches = BooleanArray(s2_len)
var matches = 0
for (i in 0..s1_len - 1) {
val start = Math.max(0, i - match_distance)
val end = Math.min(i + match_distance + 1, s2_len)
(start..end - 1).find { j -> !s2_matches[j] && s1[i] == s2[j] } ?. let {
s1_matches[i] = true
s2_matches[it] = true
matches++
}
}
if (matches == 0) return 0.0
var t = 0.0
var k = 0
(0..s1_len - 1).filter { s1_matches[it] }.forEach { i ->
while (!s2_matches[k]) k++
if (s1[i] != s2[k]) t += 0.5
k++
}
val m = matches.toDouble()
return (m / s1_len + m / s2_len + (m - t) / m) / 3.0
}
}
fun main(args: Array<String>) {
println(Jaro.distance("MARTHA", "MARHTA"))
println(Jaro.distance("DIXON", "DICKSONX"))
println(Jaro.distance("JELLYFISH", "SMELLYFISH"))
} |
Jewels and stones | Kotlin | Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer.
Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct.
The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'.
Note that:
:# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered.
:# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'.
:# The parameters do not need to have exactly the same names.
:# Validating the arguments is unnecessary.
So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3.
This task was inspired by this problem.
| // Version 1.2.40
fun countJewels(s: String, j: String) = s.count { it in j }
fun main(args: Array<String>) {
println(countJewels("aAAbbbb", "aA"))
println(countJewels("ZZ", "z"))
} |
Julia set | Kotlin | Task
Generate and draw a Julia set.
;Related tasks
* Mandelbrot Set
| import java.awt.*
import java.awt.image.BufferedImage
import javax.swing.JFrame
import javax.swing.JPanel
class JuliaPanel : JPanel() {
init {
preferredSize = Dimension(800, 600)
background = Color.white
}
private val maxIterations = 300
private val zoom = 1
private val moveX = 0.0
private val moveY = 0.0
private val cX = -0.7
private val cY = 0.27015
public override fun paintComponent(graphics: Graphics) {
super.paintComponent(graphics)
with(graphics as Graphics2D) {
setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
val image = BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
(0 until width).forEach { x ->
(0 until height).forEach { y ->
var zx = 1.5 * (x - width / 2) / (0.5 * zoom * width) + moveX
var zy = (y - height / 2) / (0.5 * zoom * height) + moveY
var i = maxIterations.toFloat()
while (zx * zx + zy * zy < 4 && i > 0) {
val tmp = zx * zx - zy * zy + cX
zy = 2.0 * zx * zy + cY
zx = tmp
i--
}
image.setRGB(x, y, Color.HSBtoRGB(maxIterations / i % 1, 1f, (if (i > 0) 1 else 0).toFloat()))
}
}
drawImage(image, 0, 0, null)
}
}
}
fun main() {
with(JFrame()) {
defaultCloseOperation = JFrame.EXIT_ON_CLOSE
title = "Julia Set"
isResizable = false
add(JuliaPanel(), BorderLayout.CENTER)
pack()
setLocationRelativeTo(null)
isVisible = true
}
} |
Jump anywhere | Kotlin | Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range.
This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports.
For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions!
* Some languages can ''go to'' any global label in a program.
* Some languages can break multiple function calls, also known as ''unwinding the call stack''.
* Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation).
These jumps are not all alike.
A simple ''goto'' never touches the call stack.
A continuation saves the call stack, so you can continue a function call after it ends.
;Task:
Use your language to demonstrate the various types of jumps that it supports.
Because the possibilities vary by language, this task is not specific.
You have the freedom to use these jumps for different purposes.
You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
| // version 1.0.6
fun main(args: Array<String>) {
intArrayOf(4, 5, 6).forEach lambda@ {
if (it == 5) return@lambda
println(it)
}
println()
loop@ for (i in 0 .. 3) {
for (j in 0 .. 3) {
if (i + j == 4) continue@loop
if (i + j == 5) break@loop
println(i + j)
}
}
} |
K-d tree | Kotlin from Go | {{wikipedia|K-d tree}}
A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches).
k-d trees are a special case of binary space partitioning trees.
k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''.
Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.
'''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets:
# The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)].
# 1000 3-d points uniformly distributed in a 3-d cube.
For the Wikipedia example, find the nearest neighbor to point (9, 2)
For the random data, pick a random location and find the nearest neighbor.
In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed.
Output should show the point searched for, the point found,
the distance to the point, and the number of nodes visited.
There are variant algorithms for constructing the tree.
You can use a simple median strategy or implement something more efficient.
Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches.
You do not have to implement these.
The requirement for this task is specifically the nearest single neighbor.
Also there are algorithms for inserting, deleting, and balancing k-d trees.
These are also not required for the task.
| // version 1.1.51
import java.util.Random
typealias Point = DoubleArray
fun Point.sqd(p: Point) = this.zip(p) { a, b -> (a - b) * (a - b) }.sum()
class HyperRect (val min: Point, val max: Point) {
fun copy() = HyperRect(min.copyOf(), max.copyOf())
}
data class NearestNeighbor(val nearest: Point?, val distSqd: Double, val nodesVisited: Int)
class KdNode(
val domElt: Point,
val split: Int,
var left: KdNode?,
var right: KdNode?
)
class KdTree {
val n: KdNode?
val bounds: HyperRect
constructor(pts: MutableList<Point>, bounds: HyperRect) {
fun nk2(exset: MutableList<Point>, split: Int): KdNode? {
if (exset.size == 0) return null
val exset2 = exset.sortedBy { it[split] }
for (i in 0 until exset.size) exset[i] = exset2[i]
var m = exset.size / 2
val d = exset[m]
while (m + 1 < exset.size && exset[m + 1][split] == d[split]) m++
var s2 = split + 1
if (s2 == d.size) s2 = 0
return KdNode(
d,
split,
nk2(exset.subList(0, m), s2),
nk2(exset.subList(m + 1, exset.size), s2)
)
}
this.n = nk2(pts, 0)
this.bounds = bounds
}
fun nearest(p: Point) = nn(n, p, bounds, Double.POSITIVE_INFINITY)
private fun nn(
kd: KdNode?,
target: Point,
hr: HyperRect,
maxDistSqd: Double
): NearestNeighbor {
if (kd == null) return NearestNeighbor(null, Double.POSITIVE_INFINITY, 0)
var nodesVisited = 1
val s = kd.split
val pivot = kd.domElt
val leftHr = hr.copy()
val rightHr = hr.copy()
leftHr.max[s] = pivot[s]
rightHr.min[s] = pivot[s]
val targetInLeft = target[s] <= pivot[s]
val nearerKd = if (targetInLeft) kd.left else kd.right
val nearerHr = if (targetInLeft) leftHr else rightHr
val furtherKd = if (targetInLeft) kd.right else kd.left
val furtherHr = if (targetInLeft) rightHr else leftHr
var (nearest, distSqd, nv) = nn(nearerKd, target, nearerHr, maxDistSqd)
nodesVisited += nv
var maxDistSqd2 = if (distSqd < maxDistSqd) distSqd else maxDistSqd
var d = pivot[s] - target[s]
d *= d
if (d > maxDistSqd2) return NearestNeighbor(nearest, distSqd, nodesVisited)
d = pivot.sqd(target)
if (d < distSqd) {
nearest = pivot
distSqd = d
maxDistSqd2 = distSqd
}
val temp = nn(furtherKd, target, furtherHr, maxDistSqd2)
nodesVisited += temp.nodesVisited
if (temp.distSqd < distSqd) {
nearest = temp.nearest
distSqd = temp.distSqd
}
return NearestNeighbor(nearest, distSqd, nodesVisited)
}
}
val rand = Random()
fun randomPt(dim: Int) = Point(dim) { rand.nextDouble() }
fun randomPts(dim: Int, n: Int) = MutableList<Point>(n) { randomPt(dim) }
fun showNearest(heading: String, kd: KdTree, p: Point) {
println("$heading:")
println("Point : ${p.asList()}")
val (nn, ssq, nv) = kd.nearest(p)
println("Nearest neighbor : ${nn?.asList()}")
println("Distance : ${Math.sqrt(ssq)}")
println("Nodes visited : $nv")
println()
}
fun main(args: Array<String>) {
val points = mutableListOf(
doubleArrayOf(2.0, 3.0),
doubleArrayOf(5.0, 4.0),
doubleArrayOf(9.0, 6.0),
doubleArrayOf(4.0, 7.0),
doubleArrayOf(8.0, 1.0),
doubleArrayOf(7.0, 2.0)
)
var hr = HyperRect(doubleArrayOf(0.0, 0.0), doubleArrayOf(10.0, 10.0))
var kd = KdTree(points, hr)
showNearest("WP example data", kd, doubleArrayOf(9.0, 2.0))
hr = HyperRect(doubleArrayOf(0.0, 0.0, 0.0), doubleArrayOf(1.0, 1.0, 1.0))
kd = KdTree(randomPts(3, 1000), hr)
showNearest("1000 random 3D points", kd, randomPt(3))
hr = hr.copy()
kd = KdTree(randomPts(3, 400_000), hr)
showNearest("400,000 random 3D points", kd, randomPt(3))
} |
Kaprekar numbers | Kotlin from Java | A positive integer is a Kaprekar number if:
* It is '''1''' (unity)
* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number.
Note that a split resulting in a part consisting purely of 0s is not valid,
as 0 is not considered positive.
;Example Kaprekar numbers:
* 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223.
* The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, ....
;Example process:
10000 (1002) splitting from left to right:
* The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive.
* Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid.
;Task:
Generate and show all Kaprekar numbers less than 10,000.
;Extra credit:
Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000.
;Extra extra credit:
The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers);
if you can, show that Kaprekar numbers exist in other bases too.
For this purpose, do the following:
* Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million);
* Display each of them in base 10 representation;
* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square.
For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g
;Reference:
* The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version
;Related task:
* [[Casting out nines]]
| import java.lang.Long.parseLong
import java.lang.Long.toString
fun String.splitAt(idx: Int): Array<String> {
val ans = arrayOf(substring(0, idx), substring(idx))
if (ans.first() == "") ans[0] = "0" // parsing "" throws an exception
return ans
}
fun Long.getKaprekarParts(sqrStr: String, base: Int): Array<String>? {
for (j in 0..sqrStr.length / 2) {
val parts = sqrStr.splitAt(j)
val (first, second) = parts.map { parseLong(it, base) }
// if the right part is all zeroes, then it will be forever, so break
if (second == 0L) return null
if (first + second == this) return parts
}
return null
}
fun main(args: Array<String>) {
val base = if (args.isNotEmpty()) args[0].toInt() else 10
var count = 0
val max = 1000000L
for (i in 1..max) {
val s = toString(i * i, base)
val p = i.getKaprekarParts(s, base)
if (p != null) {
println("%6d\t%6s\t%12s\t%7s + %7s".format(i, toString(i, base), s, p[0], p[1]))
count++
}
}
println("$count Kaprekar numbers < $max (base 10) in base $base")
} |
Kernighans large earthquake problem | Kotlin | Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based.
;Problem:
You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event.
Example lines from the file would be lines like:
8/27/1883 Krakatoa 8.8
5/18/1980 MountStHelens 7.6
3/13/2009 CostaRica 5.1
;Task:
* Create a program or script invocation to find all the events with magnitude greater than 6
* Assuming an appropriate name e.g. "data.txt" for the file:
:# Either: Show how your program is invoked to process a data file of that name.
:# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
| // Version 1.2.40
import java.io.File
fun main(args: Array<String>) {
val r = Regex("""\s+""")
println("Those earthquakes with a magnitude > 6.0 are:\n")
File("data.txt").forEachLine {
if (it.split(r)[2].toDouble() > 6.0) println(it)
}
} |
Keyboard input/Obtain a Y or N response | Kotlin | Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]].
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated.
The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
| // version 1.0.6
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities
class Test: JFrame() {
init {
while (System.`in`.available() > 0) System.`in`.read()
println("Do you want to quit Y/N")
addKeyListener(object: KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_Y) {
println("OK, quitting")
quit()
} else if (e.keyCode == KeyEvent.VK_N) {
println("N was pressed but the program is about to end anyway")
quit()
} else {
println("Only Y/N are acceptable, please try again")
}
}
})
}
private fun quit() {
isVisible = false
dispose()
System.exit(0)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = Test()
f.isFocusable = true
f.isVisible = true
}
} |
Knight's tour | Kotlin from Haskell | Task
Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard.
Input: starting square
Output: move sequence
;Related tasks
* [[A* search algorithm]]
* [[N-queens problem]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| data class Square(val x : Int, val y : Int)
val board = Array(8 * 8, { Square(it / 8 + 1, it % 8 + 1) })
val axisMoves = arrayOf(1, 2, -1, -2)
fun <T> allPairs(a: Array<T>) = a.flatMap { i -> a.map { j -> Pair(i, j) } }
fun knightMoves(s : Square) : List<Square> {
val moves = allPairs(axisMoves).filter{ Math.abs(it.first) != Math.abs(it.second) }
fun onBoard(s : Square) = board.any {it == s}
return moves.map { Square(s.x + it.first, s.y + it.second) }.filter(::onBoard)
}
fun knightTour(moves : List<Square>) : List<Square> {
fun findMoves(s: Square) = knightMoves(s).filterNot { m -> moves.any { it == m } }
val newSquare = findMoves(moves.last()).minBy { findMoves(it).size }
return if (newSquare == null) moves else knightTour(moves + newSquare)
}
fun knightTourFrom(start : Square) = knightTour(listOf(start))
fun main(args : Array<String>) {
var col = 0
for ((x, y) in knightTourFrom(Square(1, 1))) {
System.out.print("$x,$y")
System.out.print(if (col == 7) "\n" else " ")
col = (col + 1) % 8
}
} |
Knuth's algorithm S | Kotlin from Java | This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end.
This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change).
;The algorithm:
:* Select the first n items as the sample as they become available;
:* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample.
:* Repeat 2nd step for any subsequent items.
;The Task:
:* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item.
:* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S.
:* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of:
:::# Use the s_of_n_creator with n == 3 to generate an s_of_n.
:::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9.
Note: A class taking n and generating a callable instance/function might also be used.
;Reference:
* The Art of Computer Programming, Vol 2, 3.4.2 p.142
;Related tasks:
* [[One of n lines in a file]]
* [[Accumulator factory]]
| // version 1.2.51
import java.util.Random
val rand = Random()
class SOfN<T>(val n: Int) {
private val sample = ArrayList<T>(n)
private var i = 0
fun process(item: T): List<T> {
if (++i <= n)
sample.add(item)
else if (rand.nextInt(i) < n)
sample[rand.nextInt(n)] = item
return sample
}
}
fun main(args: Array<String>) {
val bin = IntArray(10)
(1..100_000).forEach {
val sOfn = SOfN<Int>(3)
for (d in 0..8) sOfn.process(d)
for (s in sOfn.process(9)) bin[s]++
}
println(bin.contentToString())
} |
Koch curve | Kotlin from Ring | Draw a Koch curve. See details: Koch curve
| // Version 1.2.41
import java.awt.Color
import java.awt.Graphics
import java.awt.image.BufferedImage
import kotlin.math.*
import java.io.File
import javax.imageio.ImageIO
val Double.asI get() = this.toInt()
class Point(var x: Int, var y: Int)
class BasicBitmapStorage(width: Int, height: Int) {
val image = BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR)
fun fill(c: Color) {
val g = image.graphics
g.color = c
g.fillRect(0, 0, image.width, image.height)
}
fun setPixel(x: Int, y: Int, c: Color) = image.setRGB(x, y, c.getRGB())
fun getPixel(x: Int, y: Int) = Color(image.getRGB(x, y))
fun drawLine(x0: Int, y0: Int, x1: Int, y1: Int, c: Color) {
val dx = abs(x1 - x0)
val dy = abs(y1 - y0)
val sx = if (x0 < x1) 1 else -1
val sy = if (y0 < y1) 1 else -1
var xx = x0
var yy = y0
var e1 = (if (dx > dy) dx else -dy) / 2
var e2: Int
while (true) {
setPixel(xx, yy, c)
if (xx == x1 && yy == y1) break
e2 = e1
if (e2 > -dx) { e1 -= dy; xx += sx }
if (e2 < dy) { e1 += dx; yy += sy }
}
}
fun koch(x1: Double, y1: Double, x2: Double, y2: Double, it: Int) {
val angle = PI / 3.0 // 60 degrees
val clr = Color.blue
var iter = it
val x3 = (x1 * 2.0 + x2) / 3.0
val y3 = (y1 * 2.0 + y2) / 3.0
val x4 = (x1 + x2 * 2.0) / 3.0
val y4 = (y1 + y2 * 2.0) / 3.0
val x5 = x3 + (x4 - x3) * cos(angle) + (y4 - y3) * sin(angle)
val y5 = y3 - (x4 - x3) * sin(angle) + (y4 - y3) * cos(angle)
if (iter > 0) {
iter--
koch(x1, y1, x3, y3, iter)
koch(x3, y3, x5, y5, iter)
koch(x5, y5, x4, y4, iter)
koch(x4, y4, x2, y2, iter)
}
else {
drawLine(x1.asI, y1.asI, x3.asI, y3.asI, clr)
drawLine(x3.asI, y3.asI, x5.asI, y5.asI, clr)
drawLine(x5.asI, y5.asI, x4.asI, y4.asI, clr)
drawLine(x4.asI, y4.asI, x2.asI, y2.asI, clr)
}
}
}
fun main(args: Array<String>) {
val width = 512
val height = 512
val bbs = BasicBitmapStorage(width, height)
with (bbs) {
fill(Color.white)
koch(100.0, 100.0, 400.0, 400.0, 4)
val kFile = File("koch_curve.jpg")
ImageIO.write(image, "jpg", kFile)
}
} |
Kolakoski sequence | Kotlin | The natural numbers, (excluding zero); with the property that:
: ''if you form a new sequence from the counts of runs of the same number in the first sequence, this new sequence is the same as the first sequence''.
;Example:
This is ''not'' a Kolakoski sequence:
1,1,2,2,2,1,2,2,1,2,...
Its sequence of run counts, (sometimes called a run length encoding, (RLE); but a true RLE also gives the character that each run encodes), is calculated like this:
: Starting from the leftmost number of the sequence we have 2 ones, followed by 3 twos, then 1 ones, 2 twos, 1 one, ...
The above gives the RLE of:
2, 3, 1, 2, 1, ...
The original sequence is different from its RLE in this case. '''It would be the same for a true Kolakoski sequence'''.
;Creating a Kolakoski sequence:
Lets start with the two numbers (1, 2) that we will cycle through; i.e. they will be used in this order: 1,2,1,2,1,2,....
# We start the sequence s with the first item from the cycle c: 1
# An index, k, into the, (expanding), sequence will step, or index through each item of the sequence s from the first, at its own rate.
We will arrange that the k'th item of s states how many ''times'' the ''last'' item of sshould appear at the end of s.
We started s with 1 and therefore s[k] states that it should appear only the 1 time.
Increment k
Get the next item from c and append it to the end of sequence s. s will then become: 1, 2
k was moved to the second item in the list and s[k] states that it should appear two times, so append another of the last item to the sequence s: 1, 2,2
Increment k
Append the next item from the cycle to the list: 1, 2,2, 1
k is now at the third item in the list that states that the last item should appear twice so add another copy of the last item to the sequence s: 1, 2,2, 1,1
increment k
...
'''Note''' that the RLE of 1, 2, 2, 1, 1, ... begins 1, 2, 2 which is the beginning of the original sequence. The generation algorithm ensures that this will always be the case.
;Task:
# Create a routine/proceedure/function/... that given an initial ordered list/array/tuple etc of the natural numbers (1, 2), returns the next number from the list when accessed in a cycle.
# Create another routine that when given the initial ordered list (1, 2) and the minimum length of the sequence to generate; uses the first routine and the algorithm above, to generate at least the requested first members of the kolakoski sequence.
# Create a routine that when given a sequence, creates the run length encoding of that sequence (as defined above) and returns the result of checking if sequence starts with the exact members of its RLE. (But ''note'', due to sampling, do not compare the last member of the RLE).
# Show, on this page, (compactly), the first 20 members of the sequence generated from (1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 20 members of the sequence generated from (2, 1)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 1, 2)
# Check the sequence againt its RLE.
# Show, on this page, the first 30 members of the Kolakoski sequence generated from (1, 3, 2, 1)
# Check the sequence againt its RLE.
(There are rules on generating Kolakoski sequences from this method that are broken by the last example)
| // Version 1.2.41
fun IntArray.nextInCycle(index: Int) = this[index % this.size]
fun IntArray.kolakoski(len: Int): IntArray {
val s = IntArray(len)
var i = 0
var k = 0
while (true) {
s[i] = this.nextInCycle(k)
if (s[k] > 1) {
repeat(s[k] - 1) {
if (++i == len) return s
s[i] = s[i - 1]
}
}
if (++i == len) return s
k++
}
}
fun IntArray.possibleKolakoski(): Boolean {
val len = this.size
val rle = mutableListOf<Int>()
var prev = this[0]
var count = 1
for (i in 1 until len) {
if (this[i] == prev) {
count++
}
else {
rle.add(count)
count = 1
prev = this[i]
}
}
// no point adding final 'count' to rle as we're not going to compare it anyway
for (i in 0 until rle.size) {
if (rle[i] != this[i]) return false
}
return true
}
fun main(args: Array<String>) {
val ias = listOf(
intArrayOf(1, 2), intArrayOf(2, 1),
intArrayOf(1, 3, 1, 2), intArrayOf(1, 3, 2, 1)
)
val lens = intArrayOf(20, 20, 30, 30)
for ((i, ia) in ias.withIndex()) {
val len = lens[i]
val kol = ia.kolakoski(len)
println("First $len members of the sequence generated by ${ia.asList()}:")
println(kol.asList())
val p = kol.possibleKolakoski()
println("Possible Kolakoski sequence? ${if (p) "Yes" else "No"}\n")
}
} |
Kosaraju | Kotlin from Go | {{wikipedia|Graph}}
Kosaraju's algorithm (also known as the Kosaraju-Sharir algorithm) is a linear time algorithm to find the strongly connected components of a directed graph. Aho, Hopcroft and Ullman credit it to an unpublished paper from 1978 by S. Rao Kosaraju. The same algorithm was independently discovered by Micha Sharir and published by him in 1981. It makes use of the fact that the transpose graph (the same graph with the direction of every edge reversed) has exactly the same strongly connected components as the original graph.
For this task consider the directed graph with these connections:
0 -> 1
1 -> 2
2 -> 0
3 -> 1, 3 -> 2, 3 -> 4
4 -> 3, 4 -> 5
5 -> 2, 5 -> 6
6 -> 5
7 -> 4, 7 -> 6, 7 -> 7
And report the kosaraju strongly connected component for each node.
;References:
* The article on Wikipedia.
| // version 1.1.3
/* the list index is the first vertex in the edge(s) */
val g = listOf(
intArrayOf(1), // 0
intArrayOf(2), // 1
intArrayOf(0), // 2
intArrayOf(1, 2, 4), // 3
intArrayOf(3, 5), // 4
intArrayOf(2, 6), // 5
intArrayOf(5), // 6
intArrayOf(4, 6, 7) // 7
)
fun kosaraju(g: List<IntArray>): List<List<Int>> {
// 1. For each vertex u of the graph, mark u as unvisited. Let l be empty.
val size = g.size
val vis = BooleanArray(size) // all false by default
val l = IntArray(size) // all zero by default
var x = size // index for filling l in reverse order
val t = List(size) { mutableListOf<Int>() } // transpose graph
// Recursive subroutine 'visit':
fun visit(u: Int) {
if (!vis[u]) {
vis[u] = true
for (v in g[u]) {
visit(v)
t[v].add(u) // construct transpose
}
l[--x] = u
}
}
// 2. For each vertex u of the graph do visit(u)
for (u in g.indices) visit(u)
val c = IntArray(size) // used for component assignment
// Recursive subroutine 'assign':
fun assign(u: Int, root: Int) {
if (vis[u]) { // repurpose vis to mean 'unassigned'
vis[u] = false
c[u] = root
for (v in t[u]) assign(v, root)
}
}
// 3: For each element u of l in order, do assign(u, u)
for (u in l) assign(u, u)
// Obtain list of SCC's from 'c' and return it
return c.withIndex()
.groupBy { it.value }.values
.map { ivl -> ivl.map { it.index } }
}
fun main(args: Array<String>) {
println(kosaraju(g).joinToString("\n"))
} |
Lah numbers | Kotlin from Perl | Lah numbers, sometimes referred to as ''Stirling numbers of the third kind'', are coefficients of polynomial expansions expressing rising factorials in terms of falling factorials.
Unsigned Lah numbers count the number of ways a set of '''n''' elements can be partitioned into '''k''' non-empty linearly ordered subsets.
Lah numbers are closely related to Stirling numbers of the first & second kinds, and may be derived from them.
Lah numbers obey the identities and relations:
L(n, 0), L(0, k) = 0 # for n, k > 0
L(n, n) = 1
L(n, 1) = n!
L(n, k) = ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For unsigned Lah numbers
''or''
L(n, k) = (-1)**n * ( n! * (n - 1)! ) / ( k! * (k - 1)! ) / (n - k)! # For signed Lah numbers
;Task:
:* Write a routine (function, procedure, whatever) to find '''unsigned Lah numbers'''. There are several methods to generate unsigned Lah numbers. You are free to choose the most appropriate for your language. If your language has a built-in, or easily, publicly available library implementation, it is acceptable to use that.
:* Using the routine, generate and show here, on this page, a table (or triangle) showing the unsigned Lah numbers, '''L(n, k)''', up to '''L(12, 12)'''. it is optional to show the row / column for n == 0 and k == 0. It is optional to show places where L(n, k) == 0 (when k > n).
:* If your language supports large integers, find and show here, on this page, the maximum value of '''L(n, k)''' where '''n == 100'''.
;See also:
:* '''Wikipedia - Lah number'''
:* '''OEIS:A105278 - Unsigned Lah numbers'''
:* '''OEIS:A008297 - Signed Lah numbers'''
;Related Tasks:
:* '''Stirling numbers of the first kind'''
:* '''Stirling numbers of the second kind'''
:* '''Bell numbers'''
| import java.math.BigInteger
fun factorial(n: BigInteger): BigInteger {
if (n == BigInteger.ZERO) return BigInteger.ONE
if (n == BigInteger.ONE) return BigInteger.ONE
var prod = BigInteger.ONE
var num = n
while (num > BigInteger.ONE) {
prod *= num
num--
}
return prod
}
fun lah(n: BigInteger, k: BigInteger): BigInteger {
if (k == BigInteger.ONE) return factorial(n)
if (k == n) return BigInteger.ONE
if (k > n) return BigInteger.ZERO
if (k < BigInteger.ONE || n < BigInteger.ONE) return BigInteger.ZERO
return (factorial(n) * factorial(n - BigInteger.ONE)) / (factorial(k) * factorial(k - BigInteger.ONE)) / factorial(n - k)
}
fun main() {
println("Unsigned Lah numbers: L(n, k):")
print("n/k ")
for (i in 0..12) {
print("%10d ".format(i))
}
println()
for (row in 0..12) {
print("%-3d".format(row))
for (i in 0..row) {
val l = lah(BigInteger.valueOf(row.toLong()), BigInteger.valueOf(i.toLong()))
print("%11d".format(l))
}
println()
}
println("\nMaximum value from the L(100, *) row:")
println((0..100).map { lah(BigInteger.valueOf(100.toLong()), BigInteger.valueOf(it.toLong())) }.max())
} |
Largest int from concatenated ints | Kotlin from C# | Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
Use the following two sets of integers as tests and show your program output here.
:::::* {1, 34, 3, 98, 9, 76, 45, 4}
:::::* {54, 546, 548, 60}
;Possible algorithms:
# A solution could be found by trying all combinations and return the best.
# Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X.
# Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key.
;See also:
* Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number?
* Constructing the largest number possible by rearranging a list
| import kotlin.Comparator
fun main(args: Array<String>) {
val comparator = Comparator<Int> { x, y -> "$x$y".compareTo("$y$x") }
fun findLargestSequence(array: IntArray): String {
return array.sortedWith(comparator.reversed()).joinToString("") { it.toString() }
}
for (array in listOf(
intArrayOf(1, 34, 3, 98, 9, 76, 45, 4),
intArrayOf(54, 546, 548, 60),
)) {
println("%s -> %s".format(array.contentToString(), findLargestSequence(array)))
}
} |
Largest number divisible by its digits | Kotlin | Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits.
These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the
(base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits.
;Example:
'''135''' is evenly divisible by '''1''', '''3''', and '''5'''.
Note that the digit zero (0) can not be in the number as integer division by zero is undefined.
The digits must all be unique so a base ten number will have at most '''9''' digits.
Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.)
;Stretch goal:
Do the same thing for hexadecimal.
;Related tasks:
:* gapful numbers.
:* palindromic gapful numbers.
;Also see:
:* The OEIS sequence: A115569: Lynch-Bell numbers.
| // version 1.1.4-3
fun Int.divByAll(digits: List<Char>) = digits.all { this % (it - '0') == 0 }
fun main(args: Array<String>) {
val magic = 9 * 8 * 7
val high = 9876432 / magic * magic
for (i in high downTo magic step magic) {
if (i % 10 == 0) continue // can't end in '0'
val s = i.toString()
if ('0' in s || '5' in s) continue // can't contain '0' or '5'
val sd = s.toCharArray().distinct()
if (sd.size != s.length) continue // digits must be unique
if (i.divByAll(sd)) {
println("Largest decimal number is $i")
return
}
}
} |
Last Friday of each month | Kotlin | Write a program or a script that returns the date of the last Fridays of each month of a given year.
The year may be given through any simple input method in your language (command line, std in, etc).
Example of an expected output:
./last_fridays 2012
2012-01-27
2012-02-24
2012-03-30
2012-04-27
2012-05-25
2012-06-29
2012-07-27
2012-08-31
2012-09-28
2012-10-26
2012-11-30
2012-12-28
;Related tasks
* [[Five weekends]]
* [[Day of the week]]
* [[Find the last Sunday of each month]]
| // version 1.0.6
import java.util.*
fun main(args: Array<String>) {
print("Enter a year : ")
val year = readLine()!!.toInt()
println("The last Fridays of each month in $year are as follows:")
val calendar = GregorianCalendar(year, 0, 31)
for (month in 1..12) {
val daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
var offset = calendar[Calendar.DAY_OF_WEEK] - Calendar.FRIDAY
if (offset < 0) offset += 7
val lastFriday = daysInMonth - offset
println("$year-" + "%02d-".format(month) + "%02d".format(lastFriday))
if (month < 12) {
calendar.add(Calendar.DAY_OF_MONTH, 1)
calendar.add(Calendar.MONTH, 1)
calendar.add(Calendar.DAY_OF_MONTH, -1)
}
}
} |
Last letter-first letter | Kotlin from Java | A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game.
For example, with "animals" as the category,
Child 1: dog
Child 2: goldfish
Child 1: hippopotamus
Child 2: snake
...
;Task:
Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name.
No Pokemon name is to be repeated.
audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon
cresselia croagunk darmanitan deino emboar emolga exeggcute gabite
girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan
kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine
nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2
porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking
sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko
tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask
Extra brownie points for dealing with the full list of 646 names.
| // version 1.1.2
var maxPathLength = 0
var maxPathLengthCount = 0
val maxPathExample = StringBuilder(500)
val names = arrayOf(
"audino", "bagon", "baltoy", "banette", "bidoof",
"braviary", "bronzor", "carracosta", "charmeleon", "cresselia",
"croagunk", "darmanitan", "deino", "emboar", "emolga",
"exeggcute", "gabite", "girafarig", "gulpin", "haxorus",
"heatmor", "heatran", "ivysaur", "jellicent", "jumpluff",
"kangaskhan", "kricketune", "landorus", "ledyba", "loudred",
"lumineon", "lunatone", "machamp", "magnezone", "mamoswine",
"nosepass", "petilil", "pidgeotto", "pikachu", "pinsir",
"poliwrath", "poochyena", "porygon2", "porygonz", "registeel",
"relicanth", "remoraid", "rufflet", "sableye", "scolipede",
"scrafty", "seaking", "sealeo", "silcoon", "simisear",
"snivy", "snorlax", "spoink", "starly", "tirtouga",
"trapinch", "treecko", "tyrogue", "vigoroth", "vulpix",
"wailord", "wartortle", "whismur", "wingull", "yamask"
)
fun search(part: Array<String>, offset: Int) {
if (offset > maxPathLength) {
maxPathLength = offset
maxPathLengthCount = 1
}
else if (offset == maxPathLength) {
maxPathLengthCount++
maxPathExample.setLength(0)
for (i in 0 until offset) {
maxPathExample.append(if (i % 5 == 0) "\n " else " ")
maxPathExample.append(part[i])
}
}
val lastChar = part[offset - 1].last()
for (i in offset until part.size) {
if (part[i][0] == lastChar) {
val tmp = names[offset]
names[offset] = names[i]
names[i] = tmp
search(names, offset + 1)
names[i] = names[offset]
names[offset] = tmp
}
}
}
fun main(args: Array<String>) {
for (i in 0 until names.size) {
val tmp = names[0]
names[0] = names[i]
names[i] = tmp
search(names, 1)
names[i] = names[0]
names[0] = tmp
}
println("Maximum path length : $maxPathLength")
println("Paths of that length : $maxPathLengthCount")
println("Example path of that length : $maxPathExample")
} |
Latin Squares in reduced form | Kotlin from D | A Latin Square is in its reduced form if the first row and first column contain items in their natural order. The order n is the number of items. For any given n there is a set of reduced Latin Squares whose size increases rapidly with n. g is a number which identifies a unique element within the set of reduced Latin Squares of order n. The objective of this task is to construct the set of all Latin Squares of a given order and to provide a means which given suitable values for g any element within the set may be obtained.
For a reduced Latin Square the first row is always 1 to n. The second row is all [[Permutations/Derangements]] of 1 to n starting with 2. The third row is all [[Permutations/Derangements]] of 1 to n starting with 3 which do not clash (do not have the same item in any column) with row 2. The fourth row is all [[Permutations/Derangements]] of 1 to n starting with 4 which do not clash with rows 2 or 3. Likewise continuing to the nth row.
Demonstrate by:
* displaying the four reduced Latin Squares of order 4.
* for n = 1 to 6 (or more) produce the set of reduced Latin Squares; produce a table which shows the size of the set of reduced Latin Squares and compares this value times n! times (n-1)! with the values in OEIS A002860.
| typealias Matrix = MutableList<MutableList<Int>>
fun dList(n: Int, sp: Int): Matrix {
val start = sp - 1 // use 0 basing
val a = generateSequence(0) { it + 1 }.take(n).toMutableList()
a[start] = a[0].also { a[0] = a[start] }
a.subList(1, a.size).sort()
val first = a[1]
// recursive closure permutes a[1:]
val r = mutableListOf<MutableList<Int>>()
fun recurse(last: Int) {
if (last == first) {
// bottom of recursion. you get here once for each permutation.
// test if permutation is deranged
for (jv in a.subList(1, a.size).withIndex()) {
if (jv.index + 1 == jv.value) {
return // no, ignore it
}
}
// yes, save a copy with 1 based indexing
val b = a.map { it + 1 }
r.add(b.toMutableList())
return
}
for (i in last.downTo(1)) {
a[i] = a[last].also { a[last] = a[i] }
recurse(last - 1)
a[i] = a[last].also { a[last] = a[i] }
}
}
recurse(n - 1)
return r
}
fun reducedLatinSquares(n: Int, echo: Boolean): Long {
if (n <= 0) {
if (echo) {
println("[]\n")
}
return 0
} else if (n == 1) {
if (echo) {
println("[1]\n")
}
return 1
}
val rlatin = MutableList(n) { MutableList(n) { it } }
// first row
for (j in 0 until n) {
rlatin[0][j] = j + 1
}
var count = 0L
fun recurse(i: Int) {
val rows = dList(n, i)
outer@
for (r in 0 until rows.size) {
rlatin[i - 1] = rows[r].toMutableList()
for (k in 0 until i - 1) {
for (j in 1 until n) {
if (rlatin[k][j] == rlatin[i - 1][j]) {
if (r < rows.size - 1) {
continue@outer
}
if (i > 2) {
return
}
}
}
}
if (i < n) {
recurse(i + 1)
} else {
count++
if (echo) {
printSquare(rlatin)
}
}
}
}
// remaining rows
recurse(2)
return count
}
fun printSquare(latin: Matrix) {
for (row in latin) {
println(row)
}
println()
}
fun factorial(n: Long): Long {
if (n == 0L) {
return 1
}
var prod = 1L
for (i in 2..n) {
prod *= i
}
return prod
}
fun main() {
println("The four reduced latin squares of order 4 are:\n")
reducedLatinSquares(4, true)
println("The size of the set of reduced latin squares for the following orders")
println("and hence the total number of latin squares of these orders are:\n")
for (n in 1 until 7) {
val size = reducedLatinSquares(n, false)
var f = factorial(n - 1.toLong())
f *= f * n * size
println("Order $n: Size %-4d x $n! x ${n - 1}! => Total $f".format(size))
}
} |
Law of cosines - triples | Kotlin from Go | The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula:
A2 + B2 - 2ABcos(g) = C2
;Specific angles:
For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation":
A2 + B2 = C2
For an angle of '''60o''' this becomes the less familiar equation:
A2 + B2 - AB = C2
And finally for an angle of '''120o''' this becomes the equation:
A2 + B2 + AB = C2
;Task:
* Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered.
* Restrain all sides to the integers '''1..13''' inclusive.
* Show how many results there are for each of the three angles mentioned above.
* Display results on this page.
Note: Triangles with the same length sides but different order are to be treated as the same.
;Optional Extra credit:
* How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''.
;Related Task
* [[Pythagorean triples]]
;See also:
* Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
| // Version 1.2.70
val squares13 = mutableMapOf<Int, Int>()
val squares10000 = mutableMapOf<Int, Int>()
class Trio(val a: Int, val b: Int, val c: Int) {
override fun toString() = "($a $b $c)"
}
fun init() {
for (i in 1..13) squares13.put(i * i, i)
for (i in 1..10000) squares10000.put(i * i, i)
}
fun solve(angle :Int, maxLen: Int, allowSame: Boolean): List<Trio> {
val solutions = mutableListOf<Trio>()
for (a in 1..maxLen) {
inner@ for (b in a..maxLen) {
var lhs = a * a + b * b
if (angle != 90) {
when (angle) {
60 -> lhs -= a * b
120 -> lhs += a * b
else -> throw RuntimeException("Angle must be 60, 90 or 120 degrees")
}
}
when (maxLen) {
13 -> {
val c = squares13[lhs]
if (c != null) {
if (!allowSame && a == b && b == c) continue@inner
solutions.add(Trio(a, b, c))
}
}
10000 -> {
val c = squares10000[lhs]
if (c != null) {
if (!allowSame && a == b && b == c) continue@inner
solutions.add(Trio(a, b, c))
}
}
else -> throw RuntimeException("Maximum length must be either 13 or 10000")
}
}
}
return solutions
}
fun main(args: Array<String>) {
init()
print("For sides in the range [1, 13] ")
println("where they can all be of the same length:-\n")
val angles = intArrayOf(90, 60, 120)
lateinit var solutions: List<Trio>
for (angle in angles) {
solutions = solve(angle, 13, true)
print(" For an angle of ${angle} degrees")
println(" there are ${solutions.size} solutions, namely:")
println(" ${solutions.joinToString(" ", "[", "]")}\n")
}
print("For sides in the range [1, 10000] ")
println("where they cannot ALL be of the same length:-\n")
solutions = solve(60, 10000, false)
print(" For an angle of 60 degrees")
println(" there are ${solutions.size} solutions.")
} |
Least common multiple | Kotlin | Compute the least common multiple (LCM) of two integers.
Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors.
;Example:
The least common multiple of '''12''' and '''18''' is '''36''', because:
:* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and
:* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and
:* there is no positive integer less than '''36''' that has both factors.
As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero.
One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''.
If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''.
:::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)}
One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''.
;Related task
:* greatest common divisor.
;See also:
* MathWorld entry: Least Common Multiple.
* Wikipedia entry: Least common multiple.
| fun main(args: Array<String>) {
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
fun lcm(a: Long, b: Long): Long = a / gcd(a, b) * b
println(lcm(15, 9))
}
|
Left factorials | Kotlin | '''Left factorials''', !n, may refer to either ''subfactorials'' or to ''factorial sums'';
the same notation can be confusingly seen being used for the two different definitions.
Sometimes, ''subfactorials'' (also known as ''derangements'') may use any of the notations:
:::::::* !''n''`
:::::::* !''n''
:::::::* ''n''!
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.)
This Rosetta Code task will be using this formula (''factorial sums'') for '''left factorial''':
::::: !n = \sum_{k=0}^{n-1} k!
:::: where
::::: !0 = 0
;Task
Display the left factorials for:
* zero through ten (inclusive)
* 20 through 110 (inclusive) by tens
Display the length (in decimal digits) of the left factorials for:
* 1,000 through 10,000 (inclusive), by thousands.
;Also see:
* The OEIS entry: A003422 left factorials
* The MathWorld entry: left factorial
* The MathWorld entry: factorial sums
* The MathWorld entry: subfactorial
;Related task:
* permutations/derangements (subfactorials)
| // version 1.0.6
import java.math.BigInteger
fun leftFactorial(n: Int): BigInteger {
if (n == 0) return BigInteger.ZERO
var fact = BigInteger.ONE
var sum = fact
for (i in 1 until n) {
fact *= BigInteger.valueOf(i.toLong())
sum += fact
}
return sum
}
fun main(args: Array<String>) {
for (i in 0..110)
if (i <= 10 || (i % 10) == 0)
println("!${i.toString().padEnd(3)} = ${leftFactorial(i)}")
println("\nLength of the following left factorials:")
for (i in 1000..10000 step 1000)
println("!${i.toString().padEnd(5)} has ${leftFactorial(i).toString().length} digits")
} |
Levenshtein distance | Kotlin | {{Wikipedia}}
In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
;Example:
The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
::# '''k'''itten '''s'''itten (substitution of 'k' with 's')
::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i')
::# sittin sittin'''g''' (insert 'g' at the end).
''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''.
''The distance between two strings is same as that when both strings are reversed.''
;Task:
Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting".
;Related task:
* [[Longest common subsequence]]
| // version 1.0.6
// Uses the "iterative with two matrix rows" algorithm referred to in the Wikipedia article.
fun levenshtein(s: String, t: String): Int {
// degenerate cases
if (s == t) return 0
if (s == "") return t.length
if (t == "") return s.length
// create two integer arrays of distances and initialize the first one
val v0 = IntArray(t.length + 1) { it } // previous
val v1 = IntArray(t.length + 1) // current
var cost: Int
for (i in 0 until s.length) {
// calculate v1 from v0
v1[0] = i + 1
for (j in 0 until t.length) {
cost = if (s[i] == t[j]) 0 else 1
v1[j + 1] = Math.min(v1[j] + 1, Math.min(v0[j + 1] + 1, v0[j] + cost))
}
// copy v1 to v0 for next iteration
for (j in 0 .. t.length) v0[j] = v1[j]
}
return v1[t.length]
}
fun main(args: Array<String>) {
println("'kitten' to 'sitting' => ${levenshtein("kitten", "sitting")}")
println("'rosettacode' to 'raisethysword' => ${levenshtein("rosettacode", "raisethysword")}")
println("'sleep' to 'fleeting' => ${levenshtein("sleep", "fleeting")}")
} |
Levenshtein distance/Alignment | Kotlin from Java | The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order.
An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is:
P-LACE
PALACE
;Task:
Write a function that shows the alignment of two strings for the corresponding levenshtein distance.
As an example, use the words "rosettacode" and "raisethysword".
You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).
| // version 1.1.3
fun levenshteinAlign(a: String, b: String): Array<String> {
val aa = a.toLowerCase()
val bb = b.toLowerCase()
val costs = Array(a.length + 1) { IntArray(b.length + 1) }
for (j in 0..b.length) costs[0][j] = j
for (i in 1..a.length) {
costs[i][0] = i
for (j in 1..b.length) {
val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1)
costs[i][j] = minOf(1 + minOf(costs[i - 1][j], costs[i][j - 1]), temp)
}
}
// walk back through matrix to figure out path
val aPathRev = StringBuilder()
val bPathRev = StringBuilder()
var i = a.length
var j = b.length
while (i != 0 && j != 0) {
val temp = costs[i - 1][j - 1] + (if (aa[i - 1] == bb[j - 1]) 0 else 1)
when (costs[i][j]) {
temp -> {
aPathRev.append(aa[--i])
bPathRev.append(bb[--j])
}
1 + costs[i-1][j] -> {
aPathRev.append(aa[--i])
bPathRev.append('-')
}
1 + costs[i][j-1] -> {
aPathRev.append('-')
bPathRev.append(bb[--j])
}
}
}
return arrayOf(aPathRev.reverse().toString(), bPathRev.reverse().toString())
}
fun main(args: Array<String>) {
var result = levenshteinAlign("place", "palace")
println(result[0])
println(result[1])
println()
result = levenshteinAlign("rosettacode","raisethysword")
println(result[0])
println(result[1])
} |
List rooted trees | Kotlin from C | You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical.
If we use a matching pair of parentheses to represent a bag, the ways are:
For 1 bag, there's one way:
() <- a bag
for 2 bags, there's one way:
(()) <- one bag in another
for 3 bags, there are two:
((())) <- 3 bags nested Russian doll style
(()()) <- 2 bags side by side, inside the third
for 4 bags, four:
(()()())
((())())
((()()))
(((())))
Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration.
It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81.
;Task:
Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive.
This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size.
As an example output, run 5 bags. There should be 9 ways.
| // version 1.1.3
typealias Tree = Long
val treeList = mutableListOf<Tree>()
val offset = IntArray(32) { if (it == 1) 1 else 0 }
fun append(t: Tree) {
treeList.add(1L or (t shl 1))
}
fun show(t: Tree, l: Int) {
var tt = t
var ll = l
while (ll-- > 0) {
print(if (tt % 2L == 1L) "(" else ")")
tt = tt ushr 1
}
}
fun listTrees(n: Int) {
for (i in offset[n] until offset[n + 1]) {
show(treeList[i], n * 2)
println()
}
}
/* assemble tree from subtrees
n: length of tree we want to make
t: assembled parts so far
sl: length of subtree we are looking at
pos: offset of subtree we are looking at
rem: remaining length to be put together
*/
fun assemble(n: Int, t: Tree, sl: Int, pos: Int, rem: Int) {
if (rem == 0) {
append(t)
return
}
var pp = pos
var ss = sl
if (sl > rem) { // need smaller subtrees
ss = rem
pp = offset[ss]
}
else if (pp >= offset[ss + 1]) {
// used up sl-trees, try smaller ones
ss--
if(ss == 0) return
pp = offset[ss]
}
assemble(n, (t shl (2 * ss)) or treeList[pp], ss, pp, rem - ss)
assemble(n, t, ss, pp + 1, rem)
}
fun makeTrees(n: Int) {
if (offset[n + 1] != 0) return
if (n > 0) makeTrees(n - 1)
assemble(n, 0, n - 1, offset[n - 1], n - 1)
offset[n + 1] = treeList.size
}
fun main(args: Array<String>) {
if (args.size != 1) {
throw IllegalArgumentException("There must be exactly 1 command line argument")
}
val n = args[0].toIntOrNull()
if (n == null) throw IllegalArgumentException("Argument is not a valid number")
// n limited to 12 to avoid overflowing default stack
if (n !in 1..12) throw IllegalArgumentException("Argument must be between 1 and 12")
// init 1-tree
append(0)
makeTrees(n)
println("Number of $n-trees: ${offset[n + 1] - offset[n]}")
listTrees(n)
} |
Long literals, with continuations | Kotlin | This task is about writing a computer program that has long literals (character
literals that may require specifying the words/tokens on more than one (source)
line, either with continuations or some other method, such as abutments or
concatenations (or some other mechanisms).
The literal is to be in the form of a "list", a literal that contains many
words (tokens) separated by a blank (space), in this case (so as to have a
common list), the (English) names of the chemical elements of the periodic table.
The list is to be in (ascending) order of the (chemical) element's atomic number:
''hydrogen helium lithium beryllium boron carbon nitrogen oxygen fluorine neon sodium aluminum silicon ...''
... up to the last known (named) chemical element (at this time).
Do not include any of the "unnamed" chemical element names such as:
''ununennium unquadnilium triunhexium penthextrium penthexpentium septhexunium octenntrium ennennbium''
To make computer programming languages comparable, the statement widths should be
restricted to less than '''81''' bytes (characters), or less
if a computer programming language has more restrictive limitations or standards.
Also mention what column the programming statements can start in if ''not''
in column one.
The list ''may'' have leading/embedded/trailing blanks during the
declaration (the actual program statements), this is allow the list to be
more readable. The "final" list shouldn't have any leading/trailing or superfluous
blanks (when stored in the program's "memory").
This list should be written with the idea in mind that the
program ''will'' be updated, most likely someone other than the
original author, as there will be newer (discovered) elements of the periodic
table being added (possibly in the near future). These future updates
should be one of the primary concerns in writing these programs and it should be "easy"
for someone else to add chemical elements to the list (within the computer
program).
Attention should be paid so as to not exceed the ''clause length'' of
continued or specified statements, if there is such a restriction. If the
limit is greater than (say) 4,000 bytes or so, it needn't be mentioned here.
;Task:
:* Write a computer program (by whatever name) to contain a list of the known elements.
:* The program should eventually contain a long literal of words (the elements).
:* The literal should show how one could create a long list of blank-delineated words.
:* The "final" (stored) list should only have a single blank between elements.
:* Try to use the most idiomatic approach(es) in creating the final list.
:* Use continuation if possible, and/or show alternatives (possibly using concatenation).
:* Use a program comment to explain what the continuation character is if it isn't obvious.
:* The program should contain a variable that has the date of the last update/revision.
:* The program, when run, should display with verbiage:
:::* The last update/revision date (and should be unambiguous).
:::* The number of chemical elements in the list.
:::* The name of the highest (last) element name.
Show all output here, on this page.
| import java.time.Instant
const val elementsChunk = """
hydrogen helium lithium beryllium
boron carbon nitrogen oxygen
fluorine neon sodium magnesium
aluminum silicon phosphorous sulfur
chlorine argon potassium calcium
scandium titanium vanadium chromium
manganese iron cobalt nickel
copper zinc gallium germanium
arsenic selenium bromine krypton
rubidium strontium yttrium zirconium
niobium molybdenum technetium ruthenium
rhodium palladium silver cadmium
indium tin antimony tellurium
iodine xenon cesium barium
lanthanum cerium praseodymium neodymium
promethium samarium europium gadolinium
terbium dysprosium holmium erbium
thulium ytterbium lutetium hafnium
tantalum tungsten rhenium osmium
iridium platinum gold mercury
thallium lead bismuth polonium
astatine radon francium radium
actinium thorium protactinium uranium
neptunium plutonium americium curium
berkelium californium einsteinium fermium
mendelevium nobelium lawrencium rutherfordium
dubnium seaborgium bohrium hassium
meitnerium darmstadtium roentgenium copernicium
nihonium flerovium moscovium livermorium
tennessine oganesson
"""
const val unamedElementsChunk = """
ununennium unquadnilium triunhexium penthextrium
penthexpentium septhexunium octenntrium ennennbium
"""
fun main() {
fun String.splitToList() = trim().split("\\s+".toRegex());
val elementsList =
elementsChunk.splitToList()
.filterNot(unamedElementsChunk.splitToList().toSet()::contains)
println("Last revision Date: ${Instant.now()}")
println("Number of elements: ${elementsList.size}")
println("Last element : ${elementsList.last()}")
println("The elements are : ${elementsList.joinToString(" ", limit = 5)}")
} |
Long year | Kotlin | Most years have 52 weeks, some have 53, according to ISO8601.
;Task:
Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
| fun main() {
val has53Weeks = { year: Int -> LocalDate.of(year, 12, 28).get(WeekFields.ISO.weekOfYear()) == 53 }
println("Long years this century:")
(2000..2100).filter(has53Weeks)
.forEach { year -> print("$year ")}
}
|
Longest common subsequence | Kotlin | '''Introduction'''
Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string.
The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings.
Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B.
An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n.
The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''.
Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly.
We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''.
Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly.
A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable.
A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j].
Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''.
According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique.
'''Background'''
Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing.
The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case.
This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions.
In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth.
A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n'').
'''Note'''
[Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)'').
'''Legend'''
A, B are input strings of lengths m, n respectively
p is the length of the LCS
M is the set of matches (i, j) such that A[i] = B[j]
r is the magnitude of M
s is the magnitude of the alphabet S of distinct symbols in A + B
'''References'''
[Dilworth 1950] "A decomposition theorem for partially ordered sets"
by Robert P. Dilworth, published January 1950,
Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166]
[Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common
Subsequence Problem" by Heiko Goeman and Michael Clausen,
published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66]
[Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences"
by Daniel S. Hirschberg, published June 1975
Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343]
[Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison"
by James W. Hunt and M. Douglas McIlroy, June 1976
Computing Science Technical Report, Bell Laboratories 41
[Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences"
by James W. Hunt and Thomas G. Szymanski, published May 1977
Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353]
[Rick 2000] "Simple and fast linear space computation of longest common subsequences"
by Claus Rick, received 17 March 2000, Information Processing Letters,
Elsevier Science [Volume 75, ''pp.'' 275-281]
'''Examples'''
The sequences "1234" and "1224533324" have an LCS of "1234":
'''1234'''
'''12'''245'''3'''332'''4'''
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
'''t'''hi'''si'''sa'''test'''
'''t'''e'''s'''t'''i'''ng123'''test'''ing
In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's.
For more information on this problem please see Wikipedia.
| // 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 main(args: Array<String>) {
val x = "thisisatest"
val y = "testing123testing"
println(lcs(x, y))
} |
Longest common substring | Kotlin from Java | Write a function that returns the longest common substring of two strings.
Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing".
Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them.
Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test".
;References:
*Generalize Suffix Tree
*[[Ukkonen's Suffix Tree Construction]]
| // version 1.1.2
fun lcs(a: String, b: String): String {
if (a.length > b.length) return lcs(b, a)
var res = ""
for (ai in 0 until a.length) {
for (len in a.length - ai downTo 1) {
for (bi in 0 until b.length - len) {
if (a.regionMatches(ai, b, bi,len) && len > res.length) {
res = a.substring(ai, ai + len)
}
}
}
}
return res
}
fun main(args: Array<String>) = println(lcs("testing123testing", "thisisatest")) |
Longest increasing subsequence | Kotlin | Calculate and show here a longest increasing subsequence of the list:
:\{3, 2, 6, 4, 5, 1\}
And of the list:
:\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\}
Note that a list may have more than one subsequence that is of the maximum length.
;Ref:
# Dynamic Programming #1: Longest Increasing Subsequence on YouTube
# An efficient solution can be based on Patience sorting.
| // version 1.1.0
fun longestIncreasingSubsequence(x: IntArray): IntArray =
when (x.size) {
0 -> IntArray(0)
1 -> x
else -> {
val n = x.size
val p = IntArray(n)
val m = IntArray(n + 1)
var len = 0
for (i in 0 until n) {
var lo = 1
var hi = len
while (lo <= hi) {
val mid = Math.ceil((lo + hi) / 2.0).toInt()
if (x[m[mid]] < x[i]) lo = mid + 1
else hi = mid - 1
}
val newLen = lo
p[i] = m[newLen - 1]
m[newLen] = i
if (newLen > len) len = newLen
}
val s = IntArray(len)
var k = m[len]
for (i in len - 1 downTo 0) {
s[i] = x[k]
k = p[k]
}
s
}
}
fun main(args: Array<String>) {
val lists = listOf(
intArrayOf(3, 2, 6, 4, 5, 1),
intArrayOf(0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15)
)
lists.forEach { println(longestIncreasingSubsequence(it).asList()) }
} |
Lucky and even lucky numbers | Kotlin | Note that in the following explanation list indices are assumed to start at ''one''.
;Definition of lucky numbers
''Lucky numbers'' are positive integers that are formed by:
# Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ...
# Return the first number from the list (which is '''1''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''3''').
#* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''7''').
#* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ...
#* Note then return the 4th number from the list (which is '''9''').
#* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ...
#* Take the 5th, i.e. '''13'''. Remove every 13th.
#* Take the 6th, i.e. '''15'''. Remove every 15th.
#* Take the 7th, i.e. '''21'''. Remove every 21th.
#* Take the 8th, i.e. '''25'''. Remove every 25th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.
;Definition of even lucky numbers
This follows the same rules as the definition of lucky numbers above ''except for the very first step'':
# Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ...
# Return the first number from the list (which is '''2''').
# (Loop begins here)
#* Note then return the second number from the list (which is '''4''').
#* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ...
# (Expanding the loop a few more times...)
#* Note then return the third number from the list (which is '''6''').
#* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ...
#* Take the 4th, i.e. '''10'''. Remove every 10th.
#* Take the 5th, i.e. '''12'''. Remove every 12th.
# (Rule for the loop)
#* Note the nth, which is m.
#* Remove every mth.
#* Increment n.
;Task requirements
* Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers''
* Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors:
** missing arguments
** too many arguments
** number (or numbers) aren't legal
** misspelled argument ('''lucky''' or '''evenLucky''')
* The command line handling should:
** support mixed case handling of the (non-numeric) arguments
** support printing a particular number
** support printing a range of numbers by their index
** support printing a range of numbers by their values
* The resulting list of numbers should be printed on a single line.
The program should support the arguments:
what is displayed (on a single line)
argument(s) (optional verbiage is encouraged)
+-------------------+----------------------------------------------------+
| j | Jth lucky number |
| j , lucky | Jth lucky number |
| j , evenLucky | Jth even lucky number |
| | |
| j k | Jth through Kth (inclusive) lucky numbers |
| j k lucky | Jth through Kth (inclusive) lucky numbers |
| j k evenLucky | Jth through Kth (inclusive) even lucky numbers |
| | |
| j -k | all lucky numbers in the range j --> |k| |
| j -k lucky | all lucky numbers in the range j --> |k| |
| j -k evenLucky | all even lucky numbers in the range j --> |k| |
+-------------------+----------------------------------------------------+
where |k| is the absolute value of k
Demonstrate the program by:
* showing the first twenty ''lucky'' numbers
* showing the first twenty ''even lucky'' numbers
* showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive)
* showing all ''even lucky'' numbers in the same range as above
* showing the 10,000th ''lucky'' number (extra credit)
* showing the 10,000th ''even lucky'' number (extra credit)
;See also:
* This task is related to the [[Sieve of Eratosthenes]] task.
* OEIS Wiki Lucky numbers.
* Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences.
* Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences.
* Entry lucky numbers on The Eric Weisstein's World of Mathematics.
| // version 1.1.51
typealias IAE = IllegalArgumentException
val luckyOdd = MutableList(100000) { it * 2 + 1 }
val luckyEven = MutableList(100000) { it * 2 + 2 }
fun filterLuckyOdd() {
var n = 2
while (n < luckyOdd.size) {
val m = luckyOdd[n - 1]
val end = (luckyOdd.size / m) * m - 1
for (j in end downTo m - 1 step m) luckyOdd.removeAt(j)
n++
}
}
fun filterLuckyEven() {
var n = 2
while (n < luckyEven.size) {
val m = luckyEven[n - 1]
val end = (luckyEven.size / m) * m - 1
for (j in end downTo m - 1 step m) luckyEven.removeAt(j)
n++
}
}
fun printSingle(j: Int, odd: Boolean) {
if (odd) {
if (j >= luckyOdd.size) throw IAE("Argument is too big")
println("Lucky number $j = ${luckyOdd[j - 1]}")
}
else {
if (j >= luckyEven.size) throw IAE("Argument is too big")
println("Lucky even number $j = ${luckyEven[j - 1]}")
}
}
fun printRange(j: Int, k: Int, odd: Boolean) {
if (odd) {
if (k >= luckyOdd.size) throw IAE("Argument is too big")
println("Lucky numbers $j to $k are:\n${luckyOdd.drop(j - 1).take(k - j + 1)}")
}
else {
if (k >= luckyEven.size) throw IAE("Argument is too big")
println("Lucky even numbers $j to $k are:\n${luckyEven.drop(j - 1).take(k - j + 1)}")
}
}
fun printBetween(j: Int, k: Int, odd: Boolean) {
val range = mutableListOf<Int>()
if (odd) {
val max = luckyOdd[luckyOdd.lastIndex]
if (j > max || k > max) {
throw IAE("At least one argument is too big")
}
for (num in luckyOdd) {
if (num < j) continue
if (num > k) break
range.add(num)
}
println("Lucky numbers between $j and $k are:\n$range")
}
else {
val max = luckyEven[luckyEven.lastIndex]
if (j > max || k > max) {
throw IAE("At least one argument is too big")
}
for (num in luckyEven) {
if (num < j) continue
if (num > k) break
range.add(num)
}
println("Lucky even numbers between $j and $k are:\n$range")
}
}
fun main(args: Array<String>) {
if (args.size !in 1..3) throw IAE("There must be between 1 and 3 command line arguments")
filterLuckyOdd()
filterLuckyEven()
val j = args[0].toIntOrNull()
if (j == null || j < 1) throw IAE("First argument must be a positive integer")
if (args.size == 1) { printSingle(j, true); return }
if (args.size == 2) {
val k = args[1].toIntOrNull()
if (k == null) throw IAE("Second argument must be an integer")
if (k >= 0) {
if (j > k) throw IAE("Second argument can't be less than first")
printRange(j, k, true)
}
else {
val l = -k
if (j > l) throw IAE("The second argument can't be less in absolute value than first")
printBetween(j, l, true)
}
return
}
var odd =
if (args[2].toLowerCase() == "lucky") true
else if (args[2].toLowerCase() == "evenlucky") false
else throw IAE("Third argument is invalid")
if (args[1] == ",") {
printSingle(j, odd)
return
}
val k = args[1].toIntOrNull()
if (k == null) throw IAE("Second argument must be an integer or a comma")
if (k >= 0) {
if (j > k) throw IAE("Second argument can't be less than first")
printRange(j, k, odd)
}
else {
val l = -k
if (j > l) throw IAE("The second argument can't be less in absolute value than first")
printBetween(j, l, odd)
}
} |
Lychrel numbers | Kotlin | ::# Take an integer n, greater than zero.
::# Form the next n of its series by reversing the digits of the current n and adding the result to the current n.
::# Stop when n becomes palindromic - i.e. the digits of n in reverse order == n.
The above recurrence relation when applied to most starting numbers n = 1, 2, ... terminates in a palindrome quite quickly.
;Example:
If n0 = 12 we get
12
12 + 21 = 33, a palindrome!
And if n0 = 55 we get
55
55 + 55 = 110
110 + 011 = 121, a palindrome!
Notice that the check for a palindrome happens ''after'' an addition.
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome.
These numbers that do not end in a palindrome are called '''Lychrel numbers'''.
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
;Seed and related Lychrel numbers:
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
In general, any sequence from one Lychrel number ''might'' converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
196
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
...
689
689 + 986 = 1675
1675 + 5761 = 7436
...
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
Because of this we can further split the Lychrel numbers into true '''Seed''' Lychrel number candidates, and '''Related''' numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
;Task:
* Find the number of seed Lychrel number candidates and related numbers for n in the range 1..10000 inclusive. (With that iteration limit of 500).
* Print the number of seed Lychrels found; the actual seed Lychrels; and just the ''number'' of relateds found.
* Print any seed Lychrel or related number that is itself a palindrome.
Show all output here.
;References:
* What's special about 196? Numberphile video.
* A023108 Positive integers which apparently never result in a palindrome under repeated applications of the function f(x) = x + (x with digits reversed).
* Status of the 196 conjecture? Mathoverflow.
| // version 1.0.6
import java.math.BigInteger
const val ITERATIONS = 500
const val LIMIT = 10000
val bigLimit = BigInteger.valueOf(LIMIT.toLong())
// In the sieve, 0 = not Lychrel, 1 = Seed Lychrel, 2 = Related Lychrel
val lychrelSieve = IntArray(LIMIT + 1) // all zero by default
val seedLychrels = mutableListOf<Int>()
val relatedLychrels = mutableSetOf<BigInteger>()
fun isPalindrome(bi: BigInteger): Boolean {
val s = bi.toString()
return s == s.reversed()
}
fun lychrelTest(i: Int, seq: MutableList<BigInteger>){
if (i < 1) return
var bi = BigInteger.valueOf(i.toLong())
(1 .. ITERATIONS).forEach {
bi += BigInteger(bi.toString().reversed())
seq.add(bi)
if (isPalindrome(bi)) return
}
for (j in 0 until seq.size) {
if (seq[j] <= bigLimit) lychrelSieve[seq[j].toInt()] = 2
else break
}
val sizeBefore = relatedLychrels.size
relatedLychrels.addAll(seq) // if all of these can be added 'i' must be a seed Lychrel
if (relatedLychrels.size - sizeBefore == seq.size) {
seedLychrels.add(i)
lychrelSieve[i] = 1
}
else {
relatedLychrels.add(BigInteger.valueOf(i.toLong()))
lychrelSieve[i] = 2
}
}
fun main(args: Array<String>) {
val seq = mutableListOf<BigInteger>()
for (i in 1 .. LIMIT)
if (lychrelSieve[i] == 0) {
seq.clear()
lychrelTest(i, seq)
}
var related = lychrelSieve.count { it == 2 }
println("Lychrel numbers in the range [1, $LIMIT]")
println("Maximum iterations = $ITERATIONS")
println("\nThere are ${seedLychrels.size} seed Lychrel numbers, namely")
println(seedLychrels)
println("\nThere are also $related related Lychrel numbers in this range")
val palindromes = mutableListOf<Int>()
for (i in 1 .. LIMIT)
if (lychrelSieve[i] > 0 && isPalindrome(BigInteger.valueOf(i.toLong()))) palindromes.add(i)
println("\nThere are ${palindromes.size} palindromic Lychrel numbers, namely")
println(palindromes)
} |
MAC vendor lookup | Kotlin | Every connected device around the world comes with a unique Media Access Control address, or a MAC address.
A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address.
;Task:
Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address.
A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result.
Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls.
'''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
| // version 1.1.2
import java.net.URL
fun lookupVendor(mac: String) = URL("http://api.macvendors.com/" + mac).readText()
fun main(args: Array<String>) {
val macs = arrayOf("FC-A1-3E", "FC:FB:FB:01:FA:21", "88:53:2E:67:07:BE", "D4:F4:6F:C9:EF:8D")
for (mac in macs) println(lookupVendor(mac))
} |
MD4 | Kotlin | Find the MD4 message digest of a string of [[octet]]s.
Use the ASCII encoded string "Rosetta Code" (without quotes).
You may either call an MD4 library, or implement MD4 in your language.
'''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols.
RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
| // version 1.0.6
import java.security.MessageDigest
class MD4() : MessageDigest("MD4"), Cloneable {
private val blockLength = 64
private var context = IntArray(4)
private var count = 0L
private var buffer = ByteArray(blockLength)
private var x = IntArray(16)
init {
engineReset()
}
private constructor(md: MD4): this() {
context = md.context.clone()
buffer = md.buffer.clone()
count = md.count
}
override fun clone(): Any = MD4(this)
override fun engineReset() {
context[0] = 0x67452301
context[1] = 0xefcdab89.toInt()
context[2] = 0x98badcfe.toInt()
context[3] = 0x10325476
count = 0L
for (i in 0 until blockLength) buffer[i] = 0
}
override fun engineUpdate(b: Byte) {
val i = (count % blockLength).toInt()
count++
buffer[i] = b
if (i == blockLength - 1) transform(buffer, 0)
}
override fun engineUpdate(input: ByteArray, offset: Int, len: Int) {
if (offset < 0 || len < 0 || offset.toLong() + len > input.size.toLong())
throw ArrayIndexOutOfBoundsException()
var bufferNdx = (count % blockLength).toInt()
count += len
val partLen = blockLength - bufferNdx
var i = 0
if (len >= partLen) {
System.arraycopy(input, offset, buffer, bufferNdx, partLen)
transform(buffer, 0)
i = partLen
while (i + blockLength - 1 < len) {
transform(input, offset + i)
i += blockLength
}
bufferNdx = 0
}
if (i < len) System.arraycopy(input, offset + i, buffer, bufferNdx, len - i)
}
override fun engineDigest(): ByteArray {
val bufferNdx = (count % blockLength).toInt()
val padLen = if (bufferNdx < 56) 56 - bufferNdx else 120 - bufferNdx
val tail = ByteArray(padLen + 8)
tail[0] = 0x80.toByte()
for (i in 0..7) tail[padLen + i] = ((count * 8) ushr (8 * i)).toByte()
engineUpdate(tail, 0, tail.size)
val result = ByteArray(16)
for (i in 0..3)
for (j in 0..3)
result[i * 4 + j] = (context[i] ushr (8 * j)).toByte()
engineReset()
return result
}
private fun transform (block: ByteArray, offset: Int) {
var offset2 = offset
for (i in 0..15)
x[i] = ((block[offset2++].toInt() and 0xff) ) or
((block[offset2++].toInt() and 0xff) shl 8 ) or
((block[offset2++].toInt() and 0xff) shl 16) or
((block[offset2++].toInt() and 0xff) shl 24)
var a = context[0]
var b = context[1]
var c = context[2]
var d = context[3]
a = ff(a, b, c, d, x[ 0], 3)
d = ff(d, a, b, c, x[ 1], 7)
c = ff(c, d, a, b, x[ 2], 11)
b = ff(b, c, d, a, x[ 3], 19)
a = ff(a, b, c, d, x[ 4], 3)
d = ff(d, a, b, c, x[ 5], 7)
c = ff(c, d, a, b, x[ 6], 11)
b = ff(b, c, d, a, x[ 7], 19)
a = ff(a, b, c, d, x[ 8], 3)
d = ff(d, a, b, c, x[ 9], 7)
c = ff(c, d, a, b, x[10], 11)
b = ff(b, c, d, a, x[11], 19)
a = ff(a, b, c, d, x[12], 3)
d = ff(d, a, b, c, x[13], 7)
c = ff(c, d, a, b, x[14], 11)
b = ff(b, c, d, a, x[15], 19)
a = gg(a, b, c, d, x[ 0], 3)
d = gg(d, a, b, c, x[ 4], 5)
c = gg(c, d, a, b, x[ 8], 9)
b = gg(b, c, d, a, x[12], 13)
a = gg(a, b, c, d, x[ 1], 3)
d = gg(d, a, b, c, x[ 5], 5)
c = gg(c, d, a, b, x[ 9], 9)
b = gg(b, c, d, a, x[13], 13)
a = gg(a, b, c, d, x[ 2], 3)
d = gg(d, a, b, c, x[ 6], 5)
c = gg(c, d, a, b, x[10], 9)
b = gg(b, c, d, a, x[14], 13)
a = gg(a, b, c, d, x[ 3], 3)
d = gg(d, a, b, c, x[ 7], 5)
c = gg(c, d, a, b, x[11], 9)
b = gg(b, c, d, a, x[15], 13)
a = hh(a, b, c, d, x[ 0], 3)
d = hh(d, a, b, c, x[ 8], 9)
c = hh(c, d, a, b, x[ 4], 11)
b = hh(b, c, d, a, x[12], 15)
a = hh(a, b, c, d, x[ 2], 3)
d = hh(d, a, b, c, x[10], 9)
c = hh(c, d, a, b, x[ 6], 11)
b = hh(b, c, d, a, x[14], 15)
a = hh(a, b, c, d, x[ 1], 3)
d = hh(d, a, b, c, x[ 9], 9)
c = hh(c, d, a, b, x[ 5], 11)
b = hh(b, c, d, a, x[13], 15)
a = hh(a, b, c, d, x[ 3], 3)
d = hh(d, a, b, c, x[11], 9)
c = hh(c, d, a, b, x[ 7], 11)
b = hh(b, c, d, a, x[15], 15)
context[0] += a
context[1] += b
context[2] += c
context[3] += d
}
private fun ff(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
val t = a + ((b and c) or (b.inv() and d)) + x
return (t shl s) or (t ushr (32 - s))
}
private fun gg(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
val t = a + ((b and (c or d)) or (c and d)) + x + 0x5a827999
return (t shl s) or (t ushr (32 - s))
}
private fun hh(a: Int, b: Int, c: Int, d: Int, x: Int, s: Int): Int {
val t = a + (b xor c xor d) + x + 0x6ed9eba1
return (t shl s) or (t ushr (32 - s))
}
}
fun main(args: Array<String>) {
val text = "Rosetta Code"
val bytes = text.toByteArray(Charsets.US_ASCII)
val md: MessageDigest = MD4()
val digest = md.digest(bytes)
for (byte in digest) print("%02x".format(byte))
println()
} |
Machine code | Kotlin from C | The task requires poking machine code directly into memory and executing it. The machine code is the architecture-specific opcodes which have the simple task of adding two unsigned bytes together and making the result available to the high-level language.
For example, the following assembly language program is given for x86 (32 bit) architectures:
mov EAX, [ESP+4]
add EAX, [ESP+8]
ret
This would translate into the following opcode bytes:
139 68 36 4 3 68 36 8 195
Or in hexadecimal:
8B 44 24 04 03 44 24 08 C3
;Task:
If different than 32-bit x86, specify the target architecture of the machine code for your example. It may be helpful to also include an assembly version of the machine code for others to reference and understand what is being executed. Then, implement the following in your favorite programming language:
* Poke the necessary opcodes into a memory location.
* Provide a means to pass two values to the machine code.
* Execute the machine code with the following arguments: unsigned-byte argument of value 7; unsigned-byte argument of value 12; The result would be 19.
* Perform any clean up actions that are appropriate for your chosen language (free the pointer or memory allocations, etc.)
| // Kotlin Native version 0.3
import kotlinx.cinterop.*
import string.*
import mman.*
import mcode.*
fun main(args: Array<String>) {
memScoped {
val bytes = byteArrayOf(
144 - 256, // Align
144 - 256,
106, 12, // Prepare stack
184 - 256, 7, 0, 0, 0,
72, 193 - 256, 224 - 256, 32,
80,
139 - 256, 68, 36, 4, 3, 68, 36, 8, // Rosetta task code
76, 137 - 256, 227 - 256, // Get result
137 - 256, 195 - 256,
72, 193 - 256, 227 - 256, 4,
128 - 256, 203 - 256, 2,
72, 131 - 256, 196 - 256, 16, // Clean up stack
195 - 256 // Return
)
val len = bytes.size
val code = allocArray<ByteVar>(len)
for (i in 0 until len) code[i] = bytes[i]
val buf = mmap(null, len.toLong(), PROT_READ or PROT_WRITE or PROT_EXEC,
MAP_PRIVATE or MAP_ANON, -1, 0)
memcpy(buf, code, len.toLong())
val a: Byte = 7
val b: Byte = 12
val c = runMachineCode(buf, a, b)
munmap(buf, len.toLong())
println("$a + $b = ${if(c >= 0) c.toInt() else c + 256}")
}
} |
Mad Libs | Kotlin | {{wikipedia}}
Mad Libs is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
;Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
went for a walk in the park.
found a . decided to take it home.
Given this example, it should then ask for a name, a he or she and a noun ( gets replaced both times with the same value).
| // version 1.1.2
fun main(args: Array<String>) {
println("Please enter a multi-line story template terminated by a blank line\n")
val sb = StringBuilder()
while (true) {
val line = readLine()!!
if (line.isEmpty()) break
sb.append("$line\n") // preserve line breaks
}
var story = sb.toString()
// identify blanks
val r = Regex("<.*?>")
val blanks = r.findAll(story).map { it.value }.distinct()
println("Please enter your replacements for the following 'blanks' in the story:")
for (blank in blanks) {
print("${blank.drop(1).dropLast(1)} : ")
val repl = readLine()!!
story = story.replace(blank, repl)
}
println("\n$story")
} |
Magic 8-ball | Kotlin | Create Magic 8-Ball.
See details at: Magic 8-Ball.
| // Version 1.2.40
import java.util.Random
fun main(args: Array<String>) {
val answers = listOf(
"It is certain", "It is decidedly so", "Without a doubt",
"Yes, definitely", "You may rely on it", "As I see it, yes",
"Most likely", "Outlook good", "Signs point to yes", "Yes",
"Reply hazy, try again", "Ask again later",
"Better not tell you now", "Cannot predict now",
"Concentrate and ask again", "Don't bet on it",
"My reply is no", "My sources say no", "Outlook not so good",
"Very doubtful"
)
val rand = Random()
println("Please enter your question or a blank line to quit.")
while (true) {
print("\n? : ")
val question = readLine()!!
if (question.trim() == "") return
val answer = answers[rand.nextInt(20)]
println("\n$answer")
}
} |
Magic squares of doubly even order | Kotlin from Java | A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
A magic square of doubly even order has a size that is a multiple of four (e.g. '''4''', '''8''', '''12''').
This means that the subsquares also have an even size, which plays a role in the construction.
{| class="wikitable" style="float:right;border: 2px solid black; background:lightblue; color:black; margin-left:auto;margin-right:auto;text-align:center;width:22em;height:15em;table-layout:fixed;font-size:100%"
|-
|'''1'''||'''2'''||'''62'''||'''61'''||'''60'''||'''59'''||'''7'''||'''8'''
|-
|'''9'''||'''10'''||'''54'''||'''53'''||'''52'''||'''51'''||'''15'''||'''16'''
|-
|'''48'''||'''47'''||'''19'''||'''20'''||'''21'''||'''22'''||'''42'''||'''41'''
|-
|'''40'''||'''39'''||'''27'''||'''28'''||'''29'''||'''30'''||'''34'''||'''33'''
|-
|'''32'''||'''31'''||'''35'''||'''36'''||'''37'''||'''38'''||'''26'''||'''25'''
|-
|'''24'''||'''23'''||'''43'''||'''44'''||'''45'''||'''46'''||'''18'''||'''17'''
|-
|'''49'''||'''50'''||'''14'''||'''13'''||'''12'''||'''11'''||'''55'''||'''56'''
|-
|'''57'''||'''58'''||'''6'''||'''5'''||'''4'''||'''3'''||'''63'''||'''64'''
|}
;Task
Create a magic square of '''8 x 8'''.
;Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of singly even order]]
;See also:
* Doubly Even Magic Squares (1728.org)
| // version 1.1.0
fun magicSquareDoublyEven(n: Int): Array<IntArray> {
if ( n < 4 || n % 4 != 0)
throw IllegalArgumentException("Base must be a positive multiple of 4")
// pattern of count-up vs count-down zones
val bits = 0b1001_0110_0110_1001
val size = n * n
val mult = n / 4 // how many multiples of 4
val result = Array(n) { IntArray(n) }
var i = 0
for (r in 0 until n)
for (c in 0 until n) {
val bitPos = c / mult + r / mult * 4
result[r][c] = if (bits and (1 shl bitPos) != 0) i + 1 else size - i
i++
}
return result
}
fun main(args: Array<String>) {
val n = 8
for (ia in magicSquareDoublyEven(n)) {
for (i in ia) print("%2d ".format(i))
println()
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
} |
Magic squares of odd order | Kotlin from C | A magic square is an '''NxN''' square matrix whose numbers (usually integers) consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both long (main) diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
The numbers are usually (but not always) the first '''N'''2 positive integers.
A magic square whose rows and columns add up to a magic number but whose main diagonals do not, is known as a ''semimagic square''.
{| class="wikitable" style="float:right;border: 4px solid blue; background:lightgreen; color:black; margin-left:auto;margin-right:auto;text-align:center;width:15em;height:15em;table-layout:fixed;font-size:150%"
|-
| '''8''' || '''1''' || '''6'''
|-
| '''3''' || '''5''' || '''7'''
|-
| '''4''' || '''9''' || '''2'''
|}
;Task
For any odd '''N''', generate a magic square with the integers ''' 1''' --> '''N''', and show the results here.
Optionally, show the ''magic number''.
You should demonstrate the generator by showing at least a magic square for '''N''' = '''5'''.
; Related tasks
* [[Magic squares of singly even order]]
* [[Magic squares of doubly even order]]
; See also:
* MathWorld(tm) entry: Magic_square
* Odd Magic Squares (1728.org)
| // version 1.0.6
fun f(n: Int, x: Int, y: Int) = (x + y * 2 + 1) % n
fun main(args: Array<String>) {
var n: Int
while (true) {
print("Enter the order of the magic square : ")
n = readLine()!!.toInt()
if (n < 1 || n % 2 == 0) println("Must be odd and >= 1, try again")
else break
}
println()
for (i in 0 until n) {
for (j in 0 until n) print("%4d".format(f(n, n - j - 1, i) * n + f(n, j, i) + 1))
println()
}
println("\nThe magic constant is ${(n * n + 1) / 2 * n}")
} |
Magic squares of singly even order | Kotlin from Java | A magic square is an '''NxN''' square matrix whose numbers consist of consecutive numbers arranged so that the sum of each row and column, ''and'' both diagonals are equal to the same sum (which is called the ''magic number'' or ''magic constant'').
A magic square of singly even order has a size that is a multiple of 4, plus 2 (e.g. 6, 10, 14). This means that the subsquares have an odd size, which plays a role in the construction.
;Task
Create a magic square of 6 x 6.
; Related tasks
* [[Magic squares of odd order]]
* [[Magic squares of doubly even order]]
; See also
* Singly Even Magic Squares (1728.org)
| // version 1.0.6
fun magicSquareOdd(n: Int): Array<IntArray> {
if (n < 3 || n % 2 == 0)
throw IllegalArgumentException("Base must be odd and > 2")
var value = 0
val gridSize = n * n
var c = n / 2
var r = 0
val result = Array(n) { IntArray(n) }
while (++value <= gridSize) {
result[r][c] = value
if (r == 0) {
if (c == n - 1) r++
else {
r = n - 1
c++
}
}
else if (c == n - 1) {
r--
c = 0
}
else if (result[r - 1][c + 1] == 0) {
r--
c++
}
else r++
}
return result
}
fun magicSquareSinglyEven(n: Int): Array<IntArray> {
if (n < 6 || (n - 2) % 4 != 0)
throw IllegalArgumentException("Base must be a positive multiple of 4 plus 2")
val size = n * n
val halfN = n / 2
val subSquareSize = size / 4
val subSquare = magicSquareOdd(halfN)
val quadrantFactors = intArrayOf(0, 2, 3, 1)
val result = Array(n) { IntArray(n) }
for (r in 0 until n)
for (c in 0 until n) {
val quadrant = r / halfN * 2 + c / halfN
result[r][c] = subSquare[r % halfN][c % halfN]
result[r][c] += quadrantFactors[quadrant] * subSquareSize
}
val nColsLeft = halfN / 2
val nColsRight = nColsLeft - 1
for (r in 0 until halfN)
for (c in 0 until n)
if (c < nColsLeft || c >= n - nColsRight || (c == nColsLeft && r == nColsLeft)) {
if (c == 0 && r == nColsLeft) continue
val tmp = result[r][c]
result[r][c] = result[r + halfN][c]
result[r + halfN][c] = tmp
}
return result
}
fun main(args: Array<String>) {
val n = 6
for (ia in magicSquareSinglyEven(n)) {
for (i in ia) print("%2d ".format(i))
println()
}
println("\nMagic constant ${(n * n + 1) * n / 2}")
} |
Map range | Kotlin | Given two ranges:
:::* [a_1,a_2] and
:::* [b_1,b_2];
:::* then a value s in range [a_1,a_2]
:::* is linearly mapped to a value t in range [b_1,b_2]
where:
:::* t = b_1 + {(s - a_1)(b_2 - b_1) \over (a_2 - a_1)}
;Task:
Write a function/subroutine/... that takes two ranges and a real number, and returns the mapping of the real number from the first to the second range.
Use this function to map values from the range [0, 10] to the range [-1, 0].
;Extra credit:
Show additional idiomatic ways of performing the mapping, using tools available to the language.
| // version 1.0.6
class FloatRange(override val start: Float, override val endInclusive: Float) : ClosedRange<Float>
fun mapRange(range1: FloatRange, range2: FloatRange, value: Float): Float {
if (value !in range1) throw IllegalArgumentException("value is not within the first range")
if (range1.endInclusive == range1.start) throw IllegalArgumentException("first range cannot be single-valued")
return range2.start + (value - range1.start) * (range2.endInclusive - range2.start) / (range1.endInclusive - range1.start)
}
fun main(args: Array<String>) {
for (i in 0..10) {
val mappedValue = mapRange(FloatRange(0.0f, 10.0f), FloatRange(-1.0f, 0.0f), i.toFloat())
println(String.format("%2d maps to %+4.2f", i, mappedValue))
}
} |
Maximum triangle path sum | Kotlin from C | Starting from the top of a pyramid of numbers like this, you can walk down going one step on the right or on the left, until you reach the bottom row:
55
94 48
95 30 96
77 71 26 67
One of such walks is 55 - 94 - 30 - 26.
You can compute the total of the numbers you have seen in such walk,
in this case it's 205.
Your problem is to find the maximum total among all possible paths from the top to the bottom row of the triangle. In the little example above it's 321.
;Task:
Find the maximum total in the triangle below:
55
94 48
95 30 96
77 71 26 67
97 13 76 38 45
07 36 79 16 37 68
48 07 09 18 70 26 06
18 72 79 46 59 79 29 90
20 76 87 11 32 07 07 49 18
27 83 58 35 71 11 25 57 29 85
14 64 36 96 27 11 58 56 92 18 55
02 90 03 60 48 49 41 46 33 36 47 23
92 50 48 02 36 59 42 79 72 20 82 77 42
56 78 38 80 39 75 02 71 66 66 01 03 55 72
44 25 67 84 71 67 11 61 40 57 58 89 40 56 36
85 32 25 85 57 48 84 35 47 62 17 01 01 99 89 52
06 71 28 75 94 48 37 10 23 51 06 48 53 18 74 98 15
27 02 92 23 08 71 76 84 15 52 92 63 81 10 44 10 69 93
Such numbers can be included in the solution code, or read from a "triangle.txt" file.
This task is derived from the Euler Problem #18.
| // version 1.1.2
val tri = intArrayOf(
55,
94, 48,
95, 30, 96,
77, 71, 26, 67,
97, 13, 76, 38, 45,
7, 36, 79, 16, 37, 68,
48, 7, 9, 18, 70, 26, 6,
18, 72, 79, 46, 59, 79, 29, 90,
20, 76, 87, 11, 32, 7, 7, 49, 18,
27, 83, 58, 35, 71, 11, 25, 57, 29, 85,
14, 64, 36, 96, 27, 11, 58, 56, 92, 18, 55,
2, 90, 3, 60, 48, 49, 41, 46, 33, 36, 47, 23,
92, 50, 48, 2, 36, 59, 42, 79, 72, 20, 82, 77, 42,
56, 78, 38, 80, 39, 75, 2, 71, 66, 66, 1, 3, 55, 72,
44, 25, 67, 84, 71, 67, 11, 61, 40, 57, 58, 89, 40, 56, 36,
85, 32, 25, 85, 57, 48, 84, 35, 47, 62, 17, 1, 1, 99, 89, 52,
6, 71, 28, 75, 94, 48, 37, 10, 23, 51, 6, 48, 53, 18, 74, 98, 15,
27, 2, 92, 23, 8, 71, 76, 84, 15, 52, 92, 63, 81, 10, 44, 10, 69, 93
)
fun main(args: Array<String>) {
val triangles = arrayOf(tri.sliceArray(0..9), tri)
for (triangle in triangles) {
val size = triangle.size
val base = ((Math.sqrt(8.0 * size + 1.0) - 1.0)/ 2.0).toInt()
var step = base - 1
var stepc = 0
for (i in (size - base - 1) downTo 0) {
triangle[i] += maxOf(triangle[i + step], triangle[i + step + 1])
if (++stepc == step) {
step--
stepc = 0
}
}
println("Maximum total = ${triangle[0]}")
}
} |
McNuggets problem | Kotlin from Go | From Wikipedia:
The McNuggets version of the coin problem was introduced by Henri Picciotto,
who included it in his algebra textbook co-authored with Anita Wah. Picciotto
thought of the application in the 1980s while dining with his son at
McDonald's, working the problem out on a napkin. A McNugget number is
the total number of McDonald's Chicken McNuggets in any number of boxes.
In the United Kingdom, the original boxes (prior to the introduction of
the Happy Meal-sized nugget boxes) were of 6, 9, and 20 nuggets.
;Task:
Calculate (from 0 up to a limit of 100) the largest non-McNuggets
number (a number ''n'' which cannot be expressed with ''6x + 9y + 20z = n''
where ''x'', ''y'' and ''z'' are natural numbers).
| // Version 1.2.71
fun mcnugget(limit: Int) {
val sv = BooleanArray(limit + 1) // all false by default
for (s in 0..limit step 6)
for (n in s..limit step 9)
for (t in n..limit step 20) sv[t] = true
for (i in limit downTo 0) {
if (!sv[i]) {
println("Maximum non-McNuggets number is $i")
return
}
}
}
fun main(args: Array<String>) {
mcnugget(100)
} |
Memory layout of a data structure | Kotlin | It is often useful to control the memory layout of fields in a data structure to match an interface control definition, or to interface with hardware. Define a data structure matching the RS-232 Plug Definition. Use the 9-pin definition for brevity.
Pin Settings for Plug
(Reverse order for socket.)
__________________________________________
1 2 3 4 5 6 7 8 9 10 11 12 13
14 15 16 17 18 19 20 21 22 23 24 25
_________________
1 2 3 4 5
6 7 8 9
25 pin 9 pin
1 - PG Protective ground
2 - TD Transmitted data 3
3 - RD Received data 2
4 - RTS Request to send 7
5 - CTS Clear to send 8
6 - DSR Data set ready 6
7 - SG Signal ground 5
8 - CD Carrier detect 1
9 - + voltage (testing)
10 - - voltage (testing)
11 -
12 - SCD Secondary CD
13 - SCS Secondary CTS
14 - STD Secondary TD
15 - TC Transmit clock
16 - SRD Secondary RD
17 - RC Receiver clock
18 -
19 - SRS Secondary RTS
20 - DTR Data terminal ready 4
21 - SQD Signal quality detector
22 - RI Ring indicator 9
23 - DRS Data rate select
24 - XTC External clock
25 -
| // version 1.0.6
const val OFF = false
const val ON = true
fun toOnOff(b: Boolean) = if (b) "ON" else "OFF"
data class Rs232Pins9(
var carrierDetect : Boolean = OFF,
var receivedData : Boolean = OFF,
var transmittedData : Boolean = OFF,
var dataTerminalReady : Boolean = OFF,
var signalGround : Boolean = OFF,
var dataSetReady : Boolean = OFF,
var requestToSend : Boolean = OFF,
var clearToSend : Boolean = OFF,
var ringIndicator : Boolean = OFF
) {
fun setPin(n: Int, v: Boolean) {
when (n) {
1 -> carrierDetect = v
2 -> receivedData = v
3 -> transmittedData = v
4 -> dataTerminalReady = v
5 -> signalGround = v
6 -> dataSetReady = v
7 -> requestToSend = v
8 -> clearToSend = v
9 -> ringIndicator = v
}
}
}
fun main(args: Array<String>) {
val plug = Rs232Pins9(carrierDetect = ON, receivedData = ON) // set first two pins, say
println(toOnOff(plug.component2())) // print value of pin 2 by number
plug.transmittedData = ON // set pin 3 by name
plug.setPin(4, ON) // set pin 4 by number
println(toOnOff(plug.component3())) // print value of pin 3 by number
println(toOnOff(plug.dataTerminalReady)) // print value of pin 4 by name
println(toOnOff(plug.ringIndicator)) // print value of pin 9 by name
} |
Metallic ratios | Kotlin from Go | Many people have heard of the '''Golden ratio''', phi ('''ph'''). Phi is just one of a series
of related ratios that are referred to as the "'''Metallic ratios'''".
The '''Golden ratio''' was discovered and named by ancient civilizations as it was
thought to be the most pure and beautiful (like Gold). The '''Silver ratio''' was was
also known to the early Greeks, though was not named so until later as a nod to
the '''Golden ratio''' to which it is closely related. The series has been extended to
encompass all of the related ratios and was given the general name '''Metallic ratios''' (or ''Metallic means'').
''Somewhat incongruously as the original Golden ratio referred to the adjective "golden" rather than the metal "gold".''
'''Metallic ratios''' are the real roots of the general form equation:
x2 - bx - 1 = 0
where the integer '''b''' determines which specific one it is.
Using the quadratic equation:
( -b +- (b2 - 4ac) ) / 2a = x
Substitute in (from the top equation) '''1''' for '''a''', '''-1''' for '''c''', and recognising that -b is negated we get:
( b +- (b2 + 4) ) ) / 2 = x
We only want the real root:
( b + (b2 + 4) ) ) / 2 = x
When we set '''b''' to '''1''', we get an irrational number: the '''Golden ratio'''.
( 1 + (12 + 4) ) / 2 = (1 + 5) / 2 = ~1.618033989...
With '''b''' set to '''2''', we get a different irrational number: the '''Silver ratio'''.
( 2 + (22 + 4) ) / 2 = (2 + 8) / 2 = ~2.414213562...
When the ratio '''b''' is '''3''', it is commonly referred to as the '''Bronze''' ratio, '''4''' and '''5'''
are sometimes called the '''Copper''' and '''Nickel''' ratios, though they aren't as
standard. After that there isn't really any attempt at standardized names. They
are given names here on this page, but consider the names fanciful rather than
canonical.
Note that technically, '''b''' can be '''0''' for a "smaller" ratio than the '''Golden ratio'''.
We will refer to it here as the '''Platinum ratio''', though it is kind-of a
degenerate case.
'''Metallic ratios''' where '''b''' > '''0''' are also defined by the irrational continued fractions:
[b;b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b...]
So, The first ten '''Metallic ratios''' are:
:::::: {| class="wikitable" style="text-align: center;"
|+ Metallic ratios
!Name!!'''b'''!!Equation!!Value!!Continued fraction!!OEIS link
|-
|Platinum||0||(0 + 4) / 2|| 1||-||-
|-
|Golden||1||(1 + 5) / 2|| 1.618033988749895...||[1;1,1,1,1,1,1,1,1,1,1...]||[[OEIS:A001622]]
|-
|Silver||2||(2 + 8) / 2|| 2.414213562373095...||[2;2,2,2,2,2,2,2,2,2,2...]||[[OEIS:A014176]]
|-
|Bronze||3||(3 + 13) / 2|| 3.302775637731995...||[3;3,3,3,3,3,3,3,3,3,3...]||[[OEIS:A098316]]
|-
|Copper||4||(4 + 20) / 2|| 4.23606797749979...||[4;4,4,4,4,4,4,4,4,4,4...]||[[OEIS:A098317]]
|-
|Nickel||5||(5 + 29) / 2|| 5.192582403567252...||[5;5,5,5,5,5,5,5,5,5,5...]||[[OEIS:A098318]]
|-
|Aluminum||6||(6 + 40) / 2|| 6.16227766016838...||[6;6,6,6,6,6,6,6,6,6,6...]||[[OEIS:A176398]]
|-
|Iron||7||(7 + 53) / 2|| 7.140054944640259...||[7;7,7,7,7,7,7,7,7,7,7...]||[[OEIS:A176439]]
|-
|Tin||8||(8 + 68) / 2|| 8.123105625617661...||[8;8,8,8,8,8,8,8,8,8,8...]||[[OEIS:A176458]]
|-
|Lead||9||(9 + 85) / 2|| 9.109772228646444...||[9;9,9,9,9,9,9,9,9,9,9...]||[[OEIS:A176522]]
|}
There are other ways to find the '''Metallic ratios'''; one, (the focus of this task)
is through '''successive approximations of Lucas sequences'''.
A traditional '''Lucas sequence''' is of the form:
x''n'' = P * x''n-1'' - Q * x''n-2''
and starts with the first 2 values '''0, 1'''.
For our purposes in this task, to find the metallic ratios we'll use the form:
x''n'' = b * x''n-1'' + x''n-2''
( '''P''' is set to '''b''' and '''Q''' is set to '''-1'''. ) To avoid "divide by zero" issues we'll start the sequence with the first two terms '''1, 1'''. The initial starting value has very little effect on the final ratio or convergence rate. ''Perhaps it would be more accurate to call it a Lucas-like sequence.''
At any rate, when '''b = 1''' we get:
x''n'' = x''n-1'' + x''n-2''
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
more commonly known as the Fibonacci sequence.
When '''b = 2''':
x''n'' = 2 * x''n-1'' + x''n-2''
1, 1, 3, 7, 17, 41, 99, 239, 577, 1393...
And so on.
To find the ratio by successive approximations, divide the ('''n+1''')th term by the
'''n'''th. As '''n''' grows larger, the ratio will approach the '''b''' metallic ratio.
For '''b = 1''' (Fibonacci sequence):
1/1 = 1
2/1 = 2
3/2 = 1.5
5/3 = 1.666667
8/5 = 1.6
13/8 = 1.625
21/13 = 1.615385
34/21 = 1.619048
55/34 = 1.617647
89/55 = 1.618182
etc.
It converges, but pretty slowly. In fact, the '''Golden ratio''' has the slowest
possible convergence for any irrational number.
;Task
For each of the first '''10 Metallic ratios'''; '''b''' = '''0''' through '''9''':
* Generate the corresponding "Lucas" sequence.
* Show here, on this page, at least the first '''15''' elements of the "Lucas" sequence.
* Using successive approximations, calculate the value of the ratio accurate to '''32''' decimal places.
* Show the '''value''' of the '''approximation''' at the required accuracy.
* Show the '''value''' of '''n''' when the approximation reaches the required accuracy (How many iterations did it take?).
Optional, stretch goal - Show the '''value''' and number of iterations '''n''', to approximate the '''Golden ratio''' to '''256''' decimal places.
You may assume that the approximation has been reached when the next iteration does not cause the value (to the desired places) to change.
;See also
* Wikipedia: Metallic mean
* Wikipedia: Lucas sequence
| import java.math.BigDecimal
import java.math.BigInteger
val names = listOf("Platinum", "Golden", "Silver", "Bronze", "Copper", "Nickel", "Aluminium", "Iron", "Tin", "Lead")
fun lucas(b: Long) {
println("Lucas sequence for ${names[b.toInt()]} ratio, where b = $b:")
print("First 15 elements: ")
var x0 = 1L
var x1 = 1L
print("$x0, $x1")
for (i in 1..13) {
val x2 = b * x1 + x0
print(", $x2")
x0 = x1
x1 = x2
}
println()
}
fun metallic(b: Long, dp:Int) {
var x0 = BigInteger.ONE
var x1 = BigInteger.ONE
var x2: BigInteger
val bb = BigInteger.valueOf(b)
val ratio = BigDecimal.ONE.setScale(dp)
var iters = 0
var prev = ratio.toString()
while (true) {
iters++
x2 = bb * x1 + x0
val thiz = (x2.toBigDecimal(dp) / x1.toBigDecimal(dp)).toString()
if (prev == thiz) {
var plural = "s"
if (iters == 1) {
plural = ""
}
println("Value after $iters iteration$plural: $thiz\n")
return
}
prev = thiz
x0 = x1
x1 = x2
}
}
fun main() {
for (b in 0L until 10L) {
lucas(b)
metallic(b, 32)
}
println("Golden ration, where b = 1:")
metallic(1, 256)
} |
Metaprogramming | Kotlin | {{omit from|BBC BASIC}}
Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.
For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.
| // version 1.0.6
infix fun Double.pwr(exp: Double) = Math.pow(this, exp)
fun main(args: Array<String>) {
val d = 2.0 pwr 8.0
println(d)
} |
Metronome | Kotlin | The task is to implement a metronome.
The metronome should be capable of producing high and low audio beats, accompanied by a visual beat indicator, and the beat pattern and tempo should be configurable.
For the purpose of this task, it is acceptable to play sound files for production of the beat notes, and an external player may be used.
However, the playing of the sounds should not interfere with the timing of the metronome.
The visual indicator can simply be a blinking red or green area of the screen (depending on whether a high or low beat is being produced), and the metronome can be implemented using a terminal display, or optionally, a graphical display, depending on the language capabilities.
If the language has no facility to output sound, then it is permissible for this to implemented using just the visual indicator.
| // version 1.1.2
fun metronome(bpm: Int, bpb: Int, maxBeats: Int = Int.MAX_VALUE) {
val delay = 60_000L / bpm
var beats = 0
do {
Thread.sleep(delay)
if (beats % bpb == 0) print("\nTICK ")
else print("tick ")
beats++
}
while (beats < maxBeats)
println()
}
fun main(args: Array<String>) = metronome(120, 4, 20) // limit to 20 beats |
Mian-Chowla sequence | Kotlin | The Mian-Chowla sequence is an integer sequence defined recursively.
Mian-Chowla is an infinite instance of a Sidon sequence, and belongs to the class known as B2 sequences.
The sequence starts with:
::a1 = 1
then for n > 1, an is the smallest positive integer such that every pairwise sum
::ai + aj
is distinct, for all i and j less than or equal to n.
;The Task:
:* Find and display, here, on this page the first 30 terms of the Mian-Chowla sequence.
:* Find and display, here, on this page the 91st through 100th terms of the Mian-Chowla sequence.
Demonstrating working through the first few terms longhand:
::a1 = 1
::1 + 1 = 2
Speculatively try a2 = 2
::1 + 1 = 2
::1 + 2 = 3
::2 + 2 = 4
There are no repeated sums so '''2''' is the next number in the sequence.
Speculatively try a3 = 3
::1 + 1 = 2
::1 + 2 = 3
::1 + 3 = 4
::2 + 2 = 4
::2 + 3 = 5
::3 + 3 = 6
Sum of '''4''' is repeated so '''3''' is rejected.
Speculatively try a3 = 4
::1 + 1 = 2
::1 + 2 = 3
::1 + 4 = 5
::2 + 2 = 4
::2 + 4 = 6
::4 + 4 = 8
There are no repeated sums so '''4''' is the next number in the sequence.
And so on...
;See also:
:* OEIS:A005282 Mian-Chowla sequence
| // Version 1.3.21
fun mianChowla(n: Int): List<Int> {
val mc = MutableList(n) { 0 }
mc[0] = 1
val hs = HashSet<Int>(n * (n + 1) / 2)
hs.add(2)
val hsx = mutableListOf<Int>()
for (i in 1 until n) {
hsx.clear()
var j = mc[i - 1]
outer@ while (true) {
j++
mc[i] = j
for (k in 0..i) {
val sum = mc[k] + j
if (hs.contains(sum)) {
hsx.clear()
continue@outer
}
hsx.add(sum)
}
hs.addAll(hsx)
break
}
}
return mc
}
fun main() {
val mc = mianChowla(100)
println("The first 30 terms of the Mian-Chowla sequence are:")
println(mc.subList(0, 30))
println("\nTerms 91 to 100 of the Mian-Chowla sequence are:")
println(mc.subList(90, 100))
} |
Middle three digits | Kotlin | Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible.
Note: The order of the middle digits should be preserved.
Your function should be tested with the following values; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| fun middleThree(x: Int): Int? {
val s = Math.abs(x).toString()
return when {
s.length < 3 -> null // throw Exception("too short!")
s.length % 2 == 0 -> null // throw Exception("even number of digits")
else -> ((s.length / 2) - 1).let { s.substring(it, it + 3) }.toInt()
}
}
fun main(args: Array<String>) {
println(middleThree(12345)) // 234
println(middleThree(1234)) // null
println(middleThree(1234567)) // 345
println(middleThree(123))// 123
println(middleThree(123555)) //null
} |
Mind boggling card trick | Kotlin from Go | Matt Parker of the "Stand Up Maths channel" has a YouTube video of a card trick that creates a semblance of order from chaos.
The task is to simulate the trick in a way that mimics the steps shown in the video.
; 1. Cards.
# Create a common deck of cards of 52 cards (which are half red, half black).
# Give the pack a good shuffle.
; 2. Deal from the shuffled deck, you'll be creating three piles.
# Assemble the cards face down.
## Turn up the ''top card'' and hold it in your hand.
### if the card is black, then add the ''next'' card (unseen) to the "black" pile.
### If the card is red, then add the ''next'' card (unseen) to the "red" pile.
## Add the ''top card'' that you're holding to the '''discard''' pile. (You might optionally show these discarded cards to get an idea of the randomness).
# Repeat the above for the rest of the shuffled deck.
; 3. Choose a random number (call it '''X''') that will be used to swap cards from the "red" and "black" piles.
# Randomly choose '''X''' cards from the "red" pile (unseen), let's call this the "red" bunch.
# Randomly choose '''X''' cards from the "black" pile (unseen), let's call this the "black" bunch.
# Put the "red" bunch into the "black" pile.
# Put the "black" bunch into the "red" pile.
# (The above two steps complete the swap of '''X''' cards of the "red" and "black" piles. (Without knowing what those cards are --- they could be red or black, nobody knows).
; 4. Order from randomness?
# Verify (or not) the mathematician's assertion that:
'''The number of black cards in the "black" pile equals the number of red cards in the "red" pile.'''
(Optionally, run this simulation a number of times, gathering more evidence of the truthfulness of the assertion.)
Show output on this page.
| // Version 1.2.61
import java.util.Random
fun main(args: Array<String>) {
// Create pack, half red, half black and shuffle it.
val pack = MutableList(52) { if (it < 26) 'R' else 'B' }
pack.shuffle()
// Deal from pack into 3 stacks.
val red = mutableListOf<Char>()
val black = mutableListOf<Char>()
val discard = mutableListOf<Char>()
for (i in 0 until 52 step 2) {
when (pack[i]) {
'B' -> black.add(pack[i + 1])
'R' -> red.add(pack[i + 1])
}
discard.add(pack[i])
}
val sr = red.size
val sb = black.size
val sd = discard.size
println("After dealing the cards the state of the stacks is:")
System.out.printf(" Red : %2d cards -> %s\n", sr, red)
System.out.printf(" Black : %2d cards -> %s\n", sb, black)
System.out.printf(" Discard: %2d cards -> %s\n", sd, discard)
// Swap the same, random, number of cards between the red and black stacks.
val rand = Random()
val min = minOf(sr, sb)
val n = 1 + rand.nextInt(min)
var rp = MutableList(sr) { it }.shuffled().subList(0, n)
var bp = MutableList(sb) { it }.shuffled().subList(0, n)
println("\n$n card(s) are to be swapped\n")
println("The respective zero-based indices of the cards(s) to be swapped are:")
println(" Red : $rp")
println(" Black : $bp")
for (i in 0 until n) {
val temp = red[rp[i]]
red[rp[i]] = black[bp[i]]
black[bp[i]] = temp
}
println("\nAfter swapping, the state of the red and black stacks is:")
println(" Red : $red")
println(" Black : $black")
// Check that the number of black cards in the black stack equals
// the number of red cards in the red stack.
var rcount = 0
var bcount = 0
for (c in red) if (c == 'R') rcount++
for (c in black) if (c == 'B') bcount++
println("\nThe number of red cards in the red stack = $rcount")
println("The number of black cards in the black stack = $bcount")
if (rcount == bcount) {
println("So the asssertion is correct!")
}
else {
println("So the asssertion is incorrect!")
}
} |
Minimum positive multiple in base 10 using only 0 and 1 | Kotlin from Java | Every positive integer has infinitely many base-10 multiples that only use the digits '''0''' and '''1'''. The goal of this task is to find and display the '''minimum''' multiple that has this property.
This is simple to do, but can be challenging to do efficiently.
To avoid repeating long, unwieldy phrases, the operation "minimum positive multiple of a positive integer n in base 10 that only uses the digits 0 and 1" will hereafter be referred to as "'''B10'''".
;Task:
Write a routine to find the B10 of a given integer.
E.G.
'''n''' '''B10''' '''n''' x '''multiplier'''
1 1 ( 1 x 1 )
2 10 ( 2 x 5 )
7 1001 ( 7 x 143 )
9 111111111 ( 9 x 12345679 )
10 10 ( 10 x 1 )
and so on.
Use the routine to find and display here, on this page, the '''B10''' value for:
1 through 10, 95 through 105, 297, 576, 594, 891, 909, 999
Optionally find '''B10''' for:
1998, 2079, 2251, 2277
Stretch goal; find '''B10''' for:
2439, 2997, 4878
There are many opportunities for optimizations, but avoid using magic numbers as much as possible. If you ''do'' use magic numbers, explain briefly why and what they do for your implementation.
;See also:
:* OEIS:A004290 Least positive multiple of n that when written in base 10 uses only 0's and 1's.
:* How to find Minimum Positive Multiple in base 10 using only 0 and 1
| import java.math.BigInteger
fun main() {
for (n in testCases) {
val result = getA004290(n)
println("A004290($n) = $result = $n * ${result / n.toBigInteger()}")
}
}
private val testCases: List<Int>
get() {
val testCases: MutableList<Int> = ArrayList()
for (i in 1..10) {
testCases.add(i)
}
for (i in 95..105) {
testCases.add(i)
}
for (i in intArrayOf(297, 576, 594, 891, 909, 999, 1998, 2079, 2251, 2277, 2439, 2997, 4878)) {
testCases.add(i)
}
return testCases
}
private fun getA004290(n: Int): BigInteger {
if (n == 1) {
return BigInteger.ONE
}
val arr = Array(n) { IntArray(n) }
for (i in 2 until n) {
arr[0][i] = 0
}
arr[0][0] = 1
arr[0][1] = 1
var m = 0
val ten = BigInteger.TEN
val nBi = n.toBigInteger()
while (true) {
m++
if (arr[m - 1][mod(-ten.pow(m), nBi).toInt()] == 1) {
break
}
arr[m][0] = 1
for (k in 1 until n) {
arr[m][k] = arr[m - 1][k].coerceAtLeast(arr[m - 1][mod(k.toBigInteger() - ten.pow(m), nBi).toInt()])
}
}
var r = ten.pow(m)
var k = mod(-r, nBi)
for (j in m - 1 downTo 1) {
if (arr[j - 1][k.toInt()] == 0) {
r += ten.pow(j)
k = mod(k - ten.pow(j), nBi)
}
}
if (k.compareTo(BigInteger.ONE) == 0) {
r += BigInteger.ONE
}
return r
}
private fun mod(m: BigInteger, n: BigInteger): BigInteger {
var result = m.mod(n)
if (result < BigInteger.ZERO) {
result += n
}
return result
} |
Modular arithmetic | Kotlin | equivalence relation called ''congruence''.
For any positive integer p called the ''congruence modulus'',
two numbers a and b are said to be ''congruent modulo p'' whenever there exists an integer k such that:
:a = b + k\,p
The corresponding set of multiplicative inverse for this task.
Addition and multiplication on this ring have the same algebraic structure as in usual arithmetic, so that a function such as a polynomial expression could receive a ring element as argument and give a consistent result.
The purpose of this task is to show, if your programming language allows it,
how to redefine operators so that they can be used transparently on modular integers.
You can do it either by using a dedicated library, or by implementing your own class.
You will use the following function for demonstration:
:f(x) = x^{100} + x + 1
You will use 13 as the congruence modulus and you will compute f(10).
It is important that the function f is agnostic about whether or not its argument is modular; it should behave the same way with normal and modular integers.
In other words, the function is an algebraic expression that could be used with any ring, not just integers.
| // version 1.1.3
interface Ring<T> {
operator fun plus(other: Ring<T>): Ring<T>
operator fun times(other: Ring<T>): Ring<T>
val value: Int
val one: Ring<T>
}
fun <T> Ring<T>.pow(p: Int): Ring<T> {
require(p >= 0)
var pp = p
var pwr = this.one
while (pp-- > 0) pwr *= this
return pwr
}
class ModInt(override val value: Int, val modulo: Int): Ring<ModInt> {
override operator fun plus(other: Ring<ModInt>): ModInt {
require(other is ModInt && modulo == other.modulo)
return ModInt((value + other.value) % modulo, modulo)
}
override operator fun times(other: Ring<ModInt>): ModInt {
require(other is ModInt && modulo == other.modulo)
return ModInt((value * other.value) % modulo, modulo)
}
override val one get() = ModInt(1, modulo)
override fun toString() = "ModInt($value, $modulo)"
}
fun <T> f(x: Ring<T>): Ring<T> = x.pow(100) + x + x.one
fun main(args: Array<String>) {
val x = ModInt(10, 13)
val y = f(x)
println("x ^ 100 + x + 1 for x == ModInt(10, 13) is $y")
} |
Modular exponentiation | Kotlin | Find the last '''40''' decimal digits of a^b, where
::* a = 2988348162058574136915891421498819466320163312926952423791023078876139
::* b = 2351399303373464486466122544523690094744975233415544072992656881240319
A computer is too slow to find the entire value of a^b.
Instead, the program must use a fast algorithm for modular exponentiation: a^b \mod m.
The algorithm must work for any integers a, b, m, where b \ge 0 and m > 0.
| // version 1.0.6
import java.math.BigInteger
fun main(args: Array<String>) {
val a = BigInteger("2988348162058574136915891421498819466320163312926952423791023078876139")
val b = BigInteger("2351399303373464486466122544523690094744975233415544072992656881240319")
val m = BigInteger.TEN.pow(40)
println(a.modPow(b, m))
} |
Modular inverse | Kotlin | From Wikipedia:
In modulo ''m'' is an integer ''x'' such that
::a\,x \equiv 1 \pmod{m}.
Or in other words, such that:
::\exists k \in\Z,\qquad a\, x = 1 + k\,m
It can be shown that such an inverse exists if and only if ''a'' and ''m'' are coprime, but we will ignore this for this task.
;Task:
Either by implementing the algorithm, by using a dedicated library or by using a built-in function in
your language, compute the modular inverse of 42 modulo 2017.
| // version 1.0.6
import java.math.BigInteger
fun main(args: Array<String>) {
val a = BigInteger.valueOf(42)
val m = BigInteger.valueOf(2017)
println(a.modInverse(m))
} |
Monads/List monad | Kotlin | A Monad is a combination of a data-type with two helper functions written for that type.
The data-type can be of any kind which can contain values of some other type - common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as '''eta''' and '''mu''', but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type.
The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure.
A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product.
The natural implementation of bind for the List monad is a composition of '''concat''' and '''map''', which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.
Demonstrate in your programming language the following:
#Construct a List Monad by writing the 'bind' function and the 'pure' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> List Int and Int -> List String
#Compose the two functions with bind
| // version 1.2.10
class MList<T : Any> private constructor(val value: List<T>) {
fun <U : Any> bind(f: (List<T>) -> MList<U>) = f(this.value)
companion object {
fun <T : Any> unit(lt: List<T>) = MList<T>(lt)
}
}
fun doubler(li: List<Int>) = MList.unit(li.map { 2 * it } )
fun letters(li: List<Int>) = MList.unit(li.map { "${('@' + it)}".repeat(it) } )
fun main(args: Array<String>) {
val iv = MList.unit(listOf(2, 3, 4))
val fv = iv.bind(::doubler).bind(::letters)
println(fv.value)
} |
Monads/Maybe monad | Kotlin | Demonstrate in your programming language the following:
#Construct a Maybe Monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that Monad (or just use what the language already has implemented)
#Make two functions, each which take a number and return a monadic number, e.g. Int -> Maybe Int and Int -> Maybe String
#Compose the two functions with bind
A Monad is a single type which encapsulates several other types, eliminating boilerplate code. In practice it acts like a dynamically typed computational sequence, though in many cases the type issues can be resolved at compile time.
A Maybe Monad is a monad which specifically encapsulates the type of an undefined value.
| // version 1.2.10
import java.util.Optional
/* doubles 'i' before wrapping it */
fun getOptionalInt(i: Int) = Optional.of(2 * i)
/* returns an 'A' repeated 'i' times wrapped in an Optional<String> */
fun getOptionalString(i: Int) = Optional.of("A".repeat(i))
/* does same as above if i > 0, otherwise returns an empty Optional<String> */
fun getOptionalString2(i: Int) =
Optional.ofNullable(if (i > 0) "A".repeat(i) else null)
fun main(args: Array<String>) {
/* prints 10 'A's */
println(getOptionalInt(5).flatMap(::getOptionalString).get())
/* prints 4 'A's */
println(getOptionalInt(2).flatMap(::getOptionalString2).get())
/* prints 'false' as there is no value present in the Optional<String> instance */
println(getOptionalInt(0).flatMap(::getOptionalString2).isPresent)
} |
Monads/Writer monad | Kotlin | The Writer monad is a programming design pattern which makes it possible to compose functions which return their result values paired with a log string. The final result of a composed function yields both a value, and a concatenation of the logs from each component function application.
Demonstrate in your programming language the following:
# Construct a Writer monad by writing the 'bind' function and the 'unit' (sometimes known as 'return') function for that monad (or just use what the language already provides)
# Write three simple functions: root, addOne, and half
# Derive Writer monad versions of each of these functions
# Apply a composition of the Writer versions of root, addOne, and half to the integer 5, deriving both a value for the Golden Ratio ph, and a concatenated log of the function applications (starting with the initial value, and followed by the application of root, etc.)
| // version 1.2.10
import kotlin.math.sqrt
class Writer<T : Any> private constructor(val value: T, s: String) {
var log = " ${s.padEnd(17)}: $value\n"
private set
fun bind(f: (T) -> Writer<T>): Writer<T> {
val new = f(this.value)
new.log = this.log + new.log
return new
}
companion object {
fun <T : Any> unit(t: T, s: String) = Writer<T>(t, s)
}
}
fun root(d: Double) = Writer.unit(sqrt(d), "Took square root")
fun addOne(d: Double) = Writer.unit(d + 1.0, "Added one")
fun half(d: Double) = Writer.unit(d / 2.0, "Divided by two")
fun main(args: Array<String>) {
val iv = Writer.unit(5.0, "Initial value")
val fv = iv.bind(::root).bind(::addOne).bind(::half)
println("The Golden Ratio is ${fv.value}")
println("\nThis was derived as follows:-\n${fv.log}")
} |
Move-to-front algorithm | Kotlin | Given a symbol table of a ''zero-indexed'' array of all possible input symbols
this algorithm reversibly transforms a sequence
of input symbols into an array of output numbers (indices).
The transform in many cases acts to give frequently repeated input symbols
lower indices which is useful in some compression algorithms.
;Encoding algorithm:
for each symbol of the input sequence:
output the index of the symbol in the symbol table
move that symbol to the front of the symbol table
;Decoding algorithm:
# Using the same starting symbol table
for each index of the input sequence:
output the symbol at that index of the symbol table
move that symbol to the front of the symbol table
;Example:
Encoding the string of character symbols 'broood' using a symbol table of the lowercase characters '''a'''-to-'''z'''
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''b'''roood
| 1
| 'abcdefghijklmnopqrstuvwxyz'
|-
| b'''r'''oood
| 1 17
| 'bacdefghijklmnopqrstuvwxyz'
|-
| br'''o'''ood
| 1 17 15
| 'rbacdefghijklmnopqstuvwxyz'
|-
| bro'''o'''od
| 1 17 15 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| broo'''o'''d
| 1 17 15 0 0
| 'orbacdefghijklmnpqstuvwxyz'
|-
| brooo'''d'''
| 1 17 15 0 0 5
| 'orbacdefghijklmnpqstuvwxyz'
|}
Decoding the indices back to the original symbol order:
:::::{| class="wikitable" border="1"
|-
! Input
! Output
! SymbolTable
|-
| '''1''' 17 15 0 0 5
| b
| 'abcdefghijklmnopqrstuvwxyz'
|-
| 1 '''17''' 15 0 0 5
| br
| 'bacdefghijklmnopqrstuvwxyz'
|-
| 1 17 '''15''' 0 0 5
| bro
| 'rbacdefghijklmnopqstuvwxyz'
|-
| 1 17 15 '''0''' 0 5
| broo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 '''0''' 5
| brooo
| 'orbacdefghijklmnpqstuvwxyz'
|-
| 1 17 15 0 0 '''5'''
| broood
| 'orbacdefghijklmnpqstuvwxyz'
|}
;Task:
:* Encode and decode the following three strings of characters using the symbol table of the lowercase characters '''a'''-to-'''z''' as above.
:* Show the strings and their encoding here.
:* Add a check to ensure that the decoded string is the same as the original.
The strings are:
broood
bananaaa
hiphophiphop
(Note the misspellings in the above strings.)
| // version 1.1.2
fun encode(s: String): IntArray {
if (s.isEmpty()) return intArrayOf()
val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
val result = IntArray(s.length)
for ((i, c) in s.withIndex()) {
val index = symbols.indexOf(c)
if (index == -1)
throw IllegalArgumentException("$s contains a non-alphabetic character")
result[i] = index
if (index == 0) continue
for (j in index - 1 downTo 0) symbols[j + 1] = symbols[j]
symbols[0] = c
}
return result
}
fun decode(a: IntArray): String {
if (a.isEmpty()) return ""
val symbols = "abcdefghijklmnopqrstuvwxyz".toCharArray()
val result = CharArray(a.size)
for ((i, n) in a.withIndex()) {
if (n !in 0..25)
throw IllegalArgumentException("${a.contentToString()} contains an invalid number")
result[i] = symbols[n]
if (n == 0) continue
for (j in n - 1 downTo 0) symbols[j + 1] = symbols[j]
symbols[0] = result[i]
}
return result.joinToString("")
}
fun main(args: Array<String>) {
val strings = arrayOf("broood", "bananaaa", "hiphophiphop")
val encoded = Array<IntArray?>(strings.size) { null }
for ((i, s) in strings.withIndex()) {
encoded[i] = encode(s)
println("${s.padEnd(12)} -> ${encoded[i]!!.contentToString()}")
}
println()
val decoded = Array<String?>(encoded.size) { null }
for ((i, a) in encoded.withIndex()) {
decoded[i] = decode(a!!)
print("${a.contentToString().padEnd(38)} -> ${decoded[i]!!.padEnd(12)}")
println(" -> ${if (decoded[i] == strings[i]) "correct" else "incorrect"}")
}
} |
Multi-dimensional array | Kotlin | For the purposes of this task, the actual memory layout or access method of this data structure is not mandated.
It is enough to:
# State the number and extent of each index to the array.
# Provide specific, ordered, integer indices for all dimensions of the array together with a new value to update the indexed value.
# Provide specific, ordered, numeric indices for all dimensions of the array to obtain the arrays value at that indexed position.
;Task:
* State if the language supports multi-dimensional arrays in its syntax and usual implementation.
* State whether the language uses row-major or column major order for multi-dimensional array storage, or any other relevant kind of storage.
* Show how to create a four dimensional array in your language and set, access, set to another value; and access the new value of an integer-indexed item of the array. The idiomatic method for the language is preferred.
:* The array should allow a range of five, four, three and two (or two three four five if convenient), in each of the indices, in order. (For example, ''if'' indexing starts at zero for the first index then a range of 0..4 inclusive would suffice).
* State if memory allocation is optimised for the array - especially if contiguous memory is likely to be allocated.
* If the language has exceptional native multi-dimensional array support such as optional bounds checking, reshaping, or being able to state both the lower and upper bounds of index ranges, then this is the task to mention them.
Show all output here, (but you may judiciously use ellipses to shorten repetitive output text).
| // version 1.1.2
fun main(args: Array<String>) {
// create a regular 4 dimensional array and initialize successive elements to the values 1 to 120
var m = 1
val a4 = Array<Array<Array<Array<Int>>>>(5) {
Array<Array<Array<Int>>>(4) {
Array<Array<Int>>(3) {
Array<Int>(2) { m++ }
}
}
}
println("First element = ${a4[0][0][0][0]}") // access and print value of first element
a4[0][0][0][0] = 121 // change value of first element
println()
// access and print values of all elements
val f = "%4d"
for (i in 0..4)
for (j in 0..3)
for (k in 0..2)
for (l in 0..1)
print(f.format(a4[i][j][k][l]))
} |
Multifactorial | Kotlin | The factorial of a number, written as n!, is defined as n! = n(n-1)(n-2)...(2)(1).
Multifactorials generalize factorials as follows:
: n! = n(n-1)(n-2)...(2)(1)
: n!! = n(n-2)(n-4)...
: n!! ! = n(n-3)(n-6)...
: n!! !! = n(n-4)(n-8)...
: n!! !! ! = n(n-5)(n-10)...
In all cases, the terms in the products are positive integers.
If we define the degree of the multifactorial as the difference in successive terms that are multiplied together for a multifactorial (the number of exclamation marks), then the task is twofold:
# Write a function that given n and the degree, calculates the multifactorial.
# Use the function to generate and display here a table of the first ten members (1 to 10) of the first five degrees of multifactorial.
'''Note:''' The wikipedia entry on multifactorials gives a different formula. This task uses the Wolfram mathworld definition.
| fun multifactorial(n: Long, d: Int) : Long {
val r = n % d
return (1..n).filter { it % d == r } .reduce { i, p -> i * p }
}
fun main(args: Array<String>) {
val m = 5
val r = 1..10L
for (d in 1..m) {
print("%${m}s:".format( "!".repeat(d)))
r.forEach { print(" " + multifactorial(it, d)) }
println()
}
} |
Multiple distinct objects | Kotlin | Create a [[sequence]] (array, list, whatever) consisting of n distinct, initialized items of the same type. n should be determined at runtime.
By ''distinct'' we mean that if they are mutable, changes to one do not affect all others; if there is an appropriate equality operator they are considered unequal; etc. The code need not specify a particular kind of distinction, but do not use e.g. a numeric-range generator which does not generalize.
By ''initialized'' we mean that each item must be in a well-defined state appropriate for its type, rather than e.g. arbitrary previous memory contents in an array allocation. Do not show only an initialization technique which initializes only to "zero" values (e.g. calloc() or int a[n] = {}; in C), unless user-defined types can provide definitions of "zero" for that type.
This task was inspired by the common error of intending to do this, but instead creating a sequence of n references to the ''same'' mutable object; it might be informative to show the way to do that as well, both as a negative example and as how to do it when that's all that's actually necessary.
This task is most relevant to languages operating in the pass-references-by-value style (most object-oriented, garbage-collected, and/or 'dynamic' languages).
See also: [[Closures/Value capture]]
| // version 1.1.2
class Foo {
val id: Int
init {
id = ++numCreated // creates a distict id for each object
}
companion object {
private var numCreated = 0
}
}
fun main(args: Array<String>) {
val n = 3 // say
/* correct approach - creates references to distinct objects */
val fooList = List(n) { Foo() }
for (foo in fooList) println(foo.id)
/* incorrect approach - creates references to same object */
val f = Foo()
val fooList2 = List(n) { f }
for (foo in fooList2) println(foo.id)
} |
Multisplit | Kotlin | It is often necessary to split a string into pieces
based on several different (potentially multi-character) separator strings,
while still retaining the information about which separators were present in the input.
This is particularly useful when doing small parsing tasks.
The task is to write code to demonstrate this.
The function (or procedure or method, as appropriate) should
take an input string and an ordered collection of separators.
The order of the separators is significant:
The delimiter order represents priority in matching, with the first defined delimiter having the highest priority.
In cases where there would be an ambiguity as to
which separator to use at a particular point
(e.g., because one separator is a prefix of another)
the separator with the highest priority should be used.
Delimiters can be reused and the output from the function should be an ordered sequence of substrings.
Test your code using the input string "a!===b=!=c" and the separators "==", "!=" and "=".
For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c".
Note that the quotation marks are shown for clarity and do not form part of the output.
'''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched.
| // version 1.0.6
fun main(args: Array<String>) {
val input = "a!===b=!=c"
val delimiters = arrayOf("==", "!=", "=")
val output = input.split(*delimiters).toMutableList()
for (i in 0 until output.size) {
if (output[i].isEmpty()) output[i] = "empty string"
else output[i] = "\"" + output[i] + "\""
}
println("The splits are:")
println(output)
// now find positions of matched delimiters
val matches = mutableListOf<Pair<String, Int>>()
var index = 0
while (index < input.length) {
var matched = false
for (d in delimiters) {
if (input.drop(index).take(d.length) == d) {
matches.add(d to index)
index += d.length
matched = true
break
}
}
if (!matched) index++
}
println("\nThe delimiters matched and the indices at which they occur are:")
println(matches)
} |
Munchausen numbers | Kotlin | A Munchausen number is a natural number ''n'' the sum of whose digits (in base 10), each raised to the power of itself, equals ''n''.
('''Munchausen''' is also spelled: '''Munchhausen'''.)
For instance: 3435 = 33 + 44 + 33 + 55
;Task
Find all Munchausen numbers between '''1''' and '''5000'''.
;Also see:
:* The OEIS entry: A046253
:* The Wikipedia entry: Perfect digit-to-digit invariant, redirected from ''Munchausen Number''
| // version 1.0.6
val powers = IntArray(10)
fun isMunchausen(n: Int): Boolean {
if (n < 0) return false
var sum = 0L
var nn = n
while (nn > 0) {
sum += powers[nn % 10]
if (sum > n.toLong()) return false
nn /= 10
}
return sum == n.toLong()
}
fun main(args: Array<String>) {
// cache n ^ n for n in 0..9, defining 0 ^ 0 = 0 for this purpose
for (i in 1..9) powers[i] = Math.pow(i.toDouble(), i.toDouble()).toInt()
// check numbers 0 to 500 million
println("The Munchausen numbers between 0 and 500 million are:")
for (i in 0..500000000) if (isMunchausen(i))print ("$i ")
println()
} |
Musical scale | Kotlin | Output the 8 notes of the C major diatonic scale to the default musical sound device on the system. Specifically, pitch must be tuned to 12-tone equal temperament (12TET) with the modern standard A=440Hz.
These are the notes "C, D, E, F, G, A, B, C(1 octave higher)", or "Do, Re, Mi, Fa, Sol, La, Si/Ti, Do(1 octave higher)" on Fixed do Solfege.
For the purpose of this task, Middle C (in the case of the above tuning, around 261.63 Hz) should be used as the starting note, and any note duration is allowed.
For languages that cannot utilize a sound device, it is permissible to output to a musical score sheet (or midi file), or the task can be omitted.
| // Kotlin Native v0.3
import kotlinx.cinterop.*
import win32.*
fun main(args: Array<String>) {
val freqs = intArrayOf(262, 294, 330, 349, 392, 440, 494, 523) // CDEFGABc
val dur = 500
repeat(5) { for (freq in freqs) Beep(freq, dur) }
} |
N-queens problem | Kotlin from FreeBASIC | right
Solve the eight queens puzzle.
You can extend the problem to solve the puzzle with a board of size '''N'''x'''N'''.
For the number of solutions for small values of '''N''', see OEIS: A000170.
;Related tasks:
* [[A* search algorithm]]
* [[Solve a Hidato puzzle]]
* [[Solve a Holy Knight's tour]]
* [[Knight's tour]]
* [[Peaceful chess queen armies]]
* [[Solve a Hopido puzzle]]
* [[Solve a Numbrix puzzle]]
* [[Solve the no connection puzzle]]
| // version 1.1.3
var count = 0
var c = IntArray(0)
var f = ""
fun nQueens(row: Int, n: Int) {
outer@ for (x in 1..n) {
for (y in 1..row - 1) {
if (c[y] == x) continue@outer
if (row - y == Math.abs(x - c[y])) continue@outer
}
c[row] = x
if (row < n) nQueens(row + 1, n)
else if (++count == 1) f = c.drop(1).map { it - 1 }.toString()
}
}
fun main(args: Array<String>) {
for (n in 1..14) {
count = 0
c = IntArray(n + 1)
f = ""
nQueens(1, n)
println("For a $n x $n board:")
println(" Solutions = $count")
if (count > 0) println(" First is $f")
println()
}
} |
Narcissist | Kotlin | Quoting from the Esolangs wiki page:
A '''narcissist''' (or '''Narcissus program''') is the decision-problem version of a [[quine]].
A quine, when run, takes no input, but produces a copy of its own source code at its output. In contrast, a narcissist reads a string of symbols from its input, and produces no output except a "1" or "accept" if that string matches its own source code, or a "0" or "reject" if it does not.
For concreteness, in this task we shall assume that symbol = character.
The narcissist should be able to cope with any finite input, whatever its length.
Any form of output is allowed, as long as the program always halts, and "accept", "reject" and "not yet finished" are distinguishable.
| // version 1.1.0 (run on Windows 10)
fun main(args: Array<String>) {
val text = java.io.File("narcissist.kt").readText()
println("Enter the number of lines to be input followed by those lines:\n")
val n = readLine()!!.toInt()
val lines = Array<String>(n) { readLine()!! }
if (lines.joinToString("\r\n") == text) println("\naccept") else println("\nreject")
} |
Narcissistic decimal number | Kotlin | A Narcissistic decimal number is a non-negative integer, n, that is equal to the sum of the m-th powers of each of the digits in the decimal representation of n, where m is the number of digits in the decimal representation of n.
Narcissistic (decimal) numbers are sometimes called '''Armstrong''' numbers, named after Michael F. Armstrong.
They are also known as '''Plus Perfect''' numbers.
;An example:
::::* if n is '''153'''
::::* then m, (the number of decimal digits) is '''3'''
::::* we have 13 + 53 + 33 = 1 + 125 + 27 = '''153'''
::::* and so '''153''' is a narcissistic decimal number
;Task:
Generate and show here the first '''25''' narcissistic decimal numbers.
Note: 0^1 = 0, the first in the series.
;See also:
* the OEIS entry: Armstrong (or Plus Perfect, or narcissistic) numbers.
* MathWorld entry: Narcissistic Number.
* Wikipedia entry: Narcissistic number.
| // version 1.1.0
fun isNarcissistic(n: Int): Boolean {
if (n < 0) throw IllegalArgumentException("Argument must be non-negative")
var nn = n
val digits = mutableListOf<Int>()
val powers = IntArray(10) { 1 }
while (nn > 0) {
digits.add(nn % 10)
for (i in 1..9) powers[i] *= i // no need to calculate powers[0]
nn /= 10
}
val sum = digits.filter { it > 0 }.map { powers[it] }.sum()
return n == sum
}
fun main(args: Array<String>) {
println("The first 25 narcissistic (or Armstrong) numbers are:")
var i = 0
var count = 0
do {
if (isNarcissistic(i)) {
print("$i ")
count++
}
i++
}
while (count < 25)
} |
Nautical bell | Kotlin from Java | Task
Write a small program that emulates a nautical bell producing a ringing bell pattern at certain times throughout the day.
The bell timing should be in accordance with Greenwich Mean Time, unless locale dictates otherwise.
It is permissible for the program to daemonize, or to slave off a scheduler, and it is permissible to use alternative notification methods (such as producing a written notice "Two Bells Gone"), if these are more usual for the system type.
;Related task:
* [[Sleep]]
| // version 1.1.3
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.TimeZone
class NauticalBell: Thread() {
override fun run() {
val sdf = SimpleDateFormat("HH:mm:ss")
sdf.timeZone = TimeZone.getTimeZone("UTC")
var numBells = 0
var time = System.currentTimeMillis()
var next = time - (time % (24 * 60 * 60 * 1000)) // midnight
while (next < time) {
next += 30 * 60 * 1000 // 30 minutes
numBells = 1 + (numBells % 8)
}
while (true) {
var wait = 100L
time = System.currentTimeMillis()
if ((time - next) >= 0) {
val bells = if (numBells == 1) "bell" else "bells"
val timeString = sdf.format(time)
println("%s : %d %s".format(timeString, numBells, bells))
next += 30 * 60 * 1000
wait = next - time
numBells = 1 + (numBells % 8)
}
try {
Thread.sleep(wait)
}
catch (ie: InterruptedException) {
return
}
}
}
}
fun main(args: Array<String>) {
val bells = NauticalBell()
with (bells) {
setDaemon(true)
start()
try {
join()
}
catch (ie: InterruptedException) {
println(ie.message)
}
}
} |
Negative base numbers | Kotlin | Negative base numbers are an alternate way to encode numbers without the need for a minus sign. Various negative bases may be used including negadecimal (base -10), negabinary (-2) and negaternary (-3).Negabinary on Wolfram MathworldNegative base on Wikipedia
;Task:
*Encode the decimal number 10 as negabinary (expect 11110)
*Encode the decimal number 146 as negaternary (expect 21102)
*Encode the decimal number 15 as negadecimal (expect 195)
*In each of the above cases, convert the encoded number back to decimal.
;extra credit:
* supply an integer, that when encoded to base -62 (or something "higher"), expresses the name of the language being used (with correct capitalization). If the computer language has non-alphanumeric characters, try to encode them into the negatory numerals, or use other characters instead.
| // version 1.1.2
const val DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
fun encodeNegBase(n: Long, b: Int): String {
require(b in -62 .. -1)
if (n == 0L) return "0"
val out = mutableListOf<Char>()
var nn = n
while (nn != 0L) {
var rem = (nn % b).toInt()
nn /= b
if (rem < 0) {
nn++
rem -= b
}
out.add(DIGITS[rem])
}
out.reverse()
return out.joinToString("")
}
fun decodeNegBase(ns: String, b: Int): Long {
require(b in -62 .. -1)
if (ns == "0") return 0
var total = 0L
var bb = 1L
for (c in ns.reversed()) {
total += DIGITS.indexOf(c) * bb
bb *= b
}
return total
}
fun main(args:Array<String>) {
val nbl = listOf(10L to -2, 146L to -3, 15L to -10, -17596769891 to -62)
for (p in nbl) {
val ns = encodeNegBase(p.first, p.second)
System.out.printf("%12d encoded in base %-3d = %s\n", p.first, p.second, ns)
val n = decodeNegBase(ns, p.second)
System.out.printf("%12s decoded in base %-3d = %d\n\n", ns, p.second, n)
}
} |
Nested function | Kotlin | In many languages, functions can be nested, resulting in outer functions and inner functions. The inner function can access variables from the outer function. In most languages, the inner function can also modify variables in the outer function.
;Task:
Write a program consisting of two nested functions that prints the following text.
1. first
2. second
3. third
The outer function (called MakeList or equivalent) is responsible for creating the list as a whole and is given the separator ". " as argument. It also defines a counter variable to keep track of the item number. This demonstrates how the inner function can influence the variables in the outer function.
The inner function (called MakeItem or equivalent) is responsible for creating a list item. It accesses the separator from the outer function and modifies the counter.
;References:
:* Nested function
| // version 1.0.6
fun makeList(sep: String): String {
var count = 0
fun makeItem(item: String): String {
count++
return "$count$sep$item\n"
}
return makeItem("first") + makeItem("second") + makeItem("third")
}
fun main(args: Array<String>) {
print(makeList(". "))
} |
Next highest int from digits | Kotlin from Java | Given a zero or positive integer, the task is to generate the next largest
integer using only the given digits*1.
* Numbers will not be padded to the left with zeroes.
* Use all given digits, with their given multiplicity. (If a digit appears twice in the input number, it should appear twice in the result).
* If there is no next highest integer return zero.
:*1 Alternatively phrased as: "Find the smallest integer larger than the (positive or zero) integer '''N'''
:: which can be obtained by reordering the (base ten) digits of '''N'''".
;Algorithm 1:
# Generate all the permutations of the digits and sort into numeric order.
# Find the number in the list.
# Return the next highest number from the list.
The above could prove slow and memory hungry for numbers with large numbers of
digits, but should be easy to reason about its correctness.
;Algorithm 2:
# Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
# Exchange that digit with the digit on the right that is ''both'' more than it, and closest to it.
# Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right. (I.e. so they form the lowest numerical representation)
'''E.g.:'''
n = 12453
12_4_53
12_5_43
12_5_34
return: 12534
This second algorithm is faster and more memory efficient, but implementations
may be harder to test.
One method of testing, (as used in developing the task), is to compare results from both
algorithms for random numbers generated from a range that the first algorithm can handle.
;Task requirements:
Calculate the next highest int from the digits of the following numbers:
:* 0
:* 9
:* 12
:* 21
:* 12453
:* 738440
:* 45072010
:* 95322020
;Optional stretch goal:
:* 9589776899767587796600
| import java.math.BigInteger
import java.text.NumberFormat
fun main() {
for (s in arrayOf(
"0",
"9",
"12",
"21",
"12453",
"738440",
"45072010",
"95322020",
"9589776899767587796600",
"3345333"
)) {
println("${format(s)} -> ${format(next(s))}")
}
testAll("12345")
testAll("11122")
}
private val FORMAT = NumberFormat.getNumberInstance()
private fun format(s: String): String {
return FORMAT.format(BigInteger(s))
}
private fun testAll(str: String) {
var s = str
println("Test all permutations of: $s")
val sOrig = s
var sPrev = s
var count = 1
// Check permutation order. Each is greater than the last
var orderOk = true
val uniqueMap: MutableMap<String, Int> = HashMap()
uniqueMap[s] = 1
while (next(s).also { s = it }.compareTo("0") != 0) {
count++
if (s.toLong() < sPrev.toLong()) {
orderOk = false
}
uniqueMap.merge(s, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
sPrev = s
}
println(" Order: OK = $orderOk")
// Test last permutation
val reverse = StringBuilder(sOrig).reverse().toString()
println(" Last permutation: Actual = $sPrev, Expected = $reverse, OK = ${sPrev.compareTo(reverse) == 0}")
// Check permutations unique
var unique = true
for (key in uniqueMap.keys) {
if (uniqueMap[key]!! > 1) {
unique = false
}
}
println(" Permutations unique: OK = $unique")
// Check expected count.
val charMap: MutableMap<Char, Int> = HashMap()
for (c in sOrig.toCharArray()) {
charMap.merge(c, 1) { a: Int?, b: Int? -> Integer.sum(a!!, b!!) }
}
var permCount = factorial(sOrig.length.toLong())
for (c in charMap.keys) {
permCount /= factorial(charMap[c]!!.toLong())
}
println(" Permutation count: Actual = $count, Expected = $permCount, OK = ${count.toLong() == permCount}")
}
private fun factorial(n: Long): Long {
var fact: Long = 1
for (num in 2..n) {
fact *= num
}
return fact
}
private fun next(s: String): String {
val sb = StringBuilder()
var index = s.length - 1
// Scan right-to-left through the digits of the number until you find a digit with a larger digit somewhere to the right of it.
while (index > 0 && s[index - 1] >= s[index]) {
index--
}
// Reached beginning. No next number.
if (index == 0) {
return "0"
}
// Find digit on the right that is both more than it, and closest to it.
var index2 = index
for (i in index + 1 until s.length) {
if (s[i] < s[index2] && s[i] > s[index - 1]) {
index2 = i
}
}
// Found data, now build string
// Beginning of String
if (index > 1) {
sb.append(s.subSequence(0, index - 1))
}
// Append found, place next
sb.append(s[index2])
// Get remaining characters
val chars: MutableList<Char> = ArrayList()
chars.add(s[index - 1])
for (i in index until s.length) {
if (i != index2) {
chars.add(s[i])
}
}
// Order the digits to the right of this position, after the swap; lowest-to-highest, left-to-right.
chars.sort()
for (c in chars) {
sb.append(c)
}
return sb.toString()
} |
Nim game | Kotlin from Go | Nim is a simple game where the second player-if they know the trick-will always win.
The game has only 3 rules:
::* start with '''12''' tokens
::* each player takes '''1, 2, or 3''' tokens in turn
::* the player who takes the last token wins.
To win every time, the second player simply takes 4 minus the number the first player took. So if the first player takes 1, the second takes 3; if the first player takes 2, the second should take 2; and if the first player takes 3, the second player will take 1.
;Task:
Design a simple Nim game where the human player goes first, and the computer always wins. The game should enforce the rules.
| // Version 1.3.21
fun showTokens(tokens: Int) {
println("Tokens remaining $tokens\n")
}
fun main() {
var tokens = 12
while (true) {
showTokens(tokens)
print(" How many tokens 1, 2 or 3? ")
var t = readLine()!!.toIntOrNull()
if (t == null || t < 1 || t > 3) {
println("\nMust be a number between 1 and 3, try again.\n")
} else {
var ct = 4 - t
var s = if (ct > 1) "s" else ""
println(" Computer takes $ct token$s\n")
tokens -= 4
}
if (tokens == 0) {
showTokens(0)
println(" Computer wins!")
return
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.