Skip to content

Instantly share code, notes, and snippets.

@VizGhar
Last active March 8, 2022 07:14
Show Gist options
  • Save VizGhar/42dcc3142edd84c00d42bec37d61f8aa to your computer and use it in GitHub Desktop.
Save VizGhar/42dcc3142edd84c00d42bec37d61f8aa to your computer and use it in GitHub Desktop.
"Hello World!"Simplistic Hill Climbing Algorithm.This sample is meant to be readable and is not efficient at all, so!!! Do not use in production !!!
import kotlin.math.abs
const val target = "Hello World!"
const val possibilities = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789 .,!?"
val String.fitness: Int get() = // lower fitness better (for this case) fitness of 0 = solution
indices.sumOf { index ->
val indexFirst = possibilities.indexOf(target[index])
val indexSecond = possibilities.indexOf(this[index])
val high = maxOf(indexFirst, indexSecond)
val low = minOf(indexFirst, indexSecond)
if ((high - low) > possibilities.length / 2) {
abs(high - possibilities.length - low)
} else {
high - low
}
}
var current = (target.indices).map { possibilities.random() }.joinToString("")
fun main() {
val startAt = System.currentTimeMillis()
var iterations = 0
for (i in target.indices) {
while (true) {
iterations++
val posIndex = possibilities.indexOf(current[i])
var testPos1 = posIndex + 1
var testPos2 = posIndex - 1
if (testPos2 < 0) testPos2 = possibilities.length - 1
if (testPos1 >= possibilities.length) testPos1 = 0
val new1 = current.replaceRange(i, i + 1, possibilities[testPos2].toString())
val new2 = current.replaceRange(i, i + 1, possibilities[testPos1].toString())
current = when {
new1.fitness < current.fitness -> new1
new2.fitness < current.fitness -> new2
else -> break
}
}
}
println("Solution \"$current\" found in $iterations iterations and ${System.currentTimeMillis() - startAt}ms")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment