Skip to content

Instantly share code, notes, and snippets.

@mnd999
Last active January 3, 2016 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mnd999/8442445 to your computer and use it in GitHub Desktop.
Save mnd999/8442445 to your computer and use it in GitHub Desktop.
West London Hack Night 14/1/14
package wlhacknight
import scala.io.Source
import java.io.File
import java.util.Arrays
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.HashMap
/**
* Alice in Markov Chains for West London Hack Night
*
* Developed in 1.5 hours by Scala team.
*/
object HackNight extends Application {
val map = HashMap[String, Node]()
val filename = new File("/home/mark/workspace/wlhacknight/src/wlhacknight/lyrics.txt")
val lines = Source.fromFile(filename).getLines.map(line => line.split(" "))
val regex = "[^a-z]".r
val words = lines.foldLeft(new ArrayBuffer[String]())((acc, line) => acc ++ line)
.map(word => regex.replaceAllIn(word.toLowerCase(), "")).toList
val whoknows = somekindofparsingfunction(words, map)
println(whoknows)
val len = whoknows.size
val startPos = Math.floor(Math.random() * len).toInt
val startNode = whoknows.toList(startPos)
val startWord = startNode._1
val realStartNode: Node = startNode._2
print(startWord + " ")
findNext(realStartNode, 100)
def somekindofparsingfunction(list: List[String], nodemap: Map[String, Node]): Map[String, Node] = {
list match {
case h :: Nil => nodemap
case token :: t => {
nodemap get token match {
case None => somekindofparsingfunction(t, nodemap + (token -> Node(token, Map(t.head -> 1))))
case Some(x) => {
x.incr(t.head)
somekindofparsingfunction(t, nodemap)
}
}
}
}
}
def findNext(node: Node, remaining: Int) {
if (remaining == 0) return
val len = node.meta.foldLeft(0)((acc, x) => acc + x._2)
val pos = Math.floor(Math.random() * len).toInt
val newStr = node.findNext
val newNode = whoknows(newStr)
print(newStr + " ")
findNext(newNode, remaining - 1)
}
}
case class Node(value: String, var meta: Map[String, Int]) {
def incr(str: String) = {
meta += (str -> (meta.getOrElse(str, 0) + 1))
}
def findNext(): String = {
val len = meta.size
val startPos = Math.floor(Math.random() * len).toInt
val startNode = meta.toList(startPos)
val startWord = startNode._1
startNode._1
}
}
@pljones
Copy link

pljones commented Jan 16, 2014

I've added a feature (verses!) and removed a lot of code in a fork:
https://gist.github.com/pljones/8462061

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment