Skip to content

Instantly share code, notes, and snippets.

@honnix
Created June 10, 2013 15:12
Show Gist options
  • Save honnix/5749533 to your computer and use it in GitHub Desktop.
Save honnix/5749533 to your computer and use it in GitHub Desktop.
genetic algorithm experiment
import scala.language.postfixOps
import scala.util.Random
class Guess {
class GeneticSolver {
def getBest(toMatch: String) = {
def random: Stream[Char] = toMatch(Random.nextInt(toMatch.length)) #:: random
def iterate(parent: Seq[Char], score: Int, generation: Int): Seq[Char] = if (score != toMatch.length) {
def mutate = parent.updated(Random.nextInt(toMatch.length), toMatch(Random.nextInt(toMatch.length)))
val child = mutate
val childScore = getFitness(child)
if (childScore > score) {
println(s"generation\t${generation + 1}\tfitness\t${childScore}\t${child.mkString}")
iterate(child, childScore, generation + 1)
} else iterate(parent, score, generation + 1)
} else parent
def getFitness(seq: Seq[Char]) = (0 until toMatch.length) count { i =>
toMatch(i) == seq(i)
}
val init = random take toMatch.length
val score = getFitness(init)
println(s"generation\t1\tfitness\t${score}\t${init.mkString}")
iterate(init, score, 1)
}
}
class StringDuplicator {
def duplicate(toMatch: String) = new GeneticSolver().getBest(toMatch)
}
println(new StringDuplicator().duplicate("hello world!") mkString)
}
new Guess()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment