Jump to content

Kolakoski sequence: Difference between revisions

Added Kotlin
(Added Kotlin)
Line 51:
# Check the sequence againt its RLE.
(There are [[wp:Kolakoski_sequence#From_finite_integer_sets|rules]] on generating Kolakoski sequences from this method that are broken by the last example)
=={{header|Kotlin}}==
<lang scala>// 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")
}
}</lang>
 
{{output}}
<pre>
First 20 members of the sequence generated by [1, 2]:
[1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1]
Possible Kolakoski sequence? Yes
 
First 20 members of the sequence generated by [2, 1]:
[2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2]
Possible Kolakoski sequence? Yes
 
First 30 members of the sequence generated by [1, 3, 1, 2]:
[1, 3, 3, 3, 1, 1, 1, 2, 2, 2, 1, 3, 1, 2, 2, 1, 1, 3, 3, 1, 2, 2, 2, 1, 3, 3, 1, 1, 2, 1]
Possible Kolakoski sequence? Yes
 
First 30 members of the sequence generated by [1, 3, 2, 1]:
[1, 3, 3, 3, 2, 2, 2, 1, 1, 1, 1, 1, 3, 3, 2, 2, 1, 1, 3, 2, 1, 1, 1, 1, 3, 3, 3, 2, 2, 1]
Possible Kolakoski sequence? No
 
</pre>
 
=={{header|Python}}==
Python 3.6+
9,492

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.