Last active
January 3, 2016 09:19
-
-
Save mnd999/8442445 to your computer and use it in GitHub Desktop.
West London Hack Night 14/1/14
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've added a feature (verses!) and removed a lot of code in a fork:
https://gist.github.com/pljones/8462061