tasks a-s

This commit is contained in:
Ingy döt Net 2013-04-10 23:57:08 -07:00
parent 47bf37c096
commit b83f433714
12433 changed files with 156208 additions and 123 deletions

View file

@ -0,0 +1,30 @@
import scala.io.Source
object MarkovAlgorithm {
val RulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r
val CommentPattern = """#.*|\s*""".r
def rule(line: String) = line match {
case CommentPattern() => None
case RulePattern(pattern, terminal, replacement) => Some(pattern, replacement, terminal == ".")
case _ => error("Syntax error on line "+line)
}
def main(args: Array[String]) {
if (args.size != 2 ) {
println("Syntax: MarkovAlgorithm inputFile inputPattern")
exit(1)
}
val rules = (Source fromPath args(0) getLines () map rule).toList.flatten
def algorithm(input: String): String = rules find (input contains _._1) match {
case Some((pattern, replacement, true)) => input replaceFirst ("\\Q"+pattern+"\\E", replacement)
case Some((pattern, replacement, false)) => algorithm(input replaceFirst ("\\Q"+pattern+"\\E", replacement))
case None => input
}
println(args(1))
println(algorithm(args(1)))
}
}

View file

@ -0,0 +1,16 @@
import scala.io.Source
if (argv.size != 2 ) error("Syntax: MarkovAlgorithm inputFile inputPattern")
val rulePattern = """(.*?)\s+->\s+(\.?)(.*)""".r
val isComment = (_: String) matches "#.*|\\s*"
val rules = Source fromPath args(0) getLines () filterNot isComment map (rulePattern unapplySeq _ get) toList;
def algorithm(input: String): String = rules find (input contains _.head) match {
case Some(Seq(pattern, ".", replacement)) => input replaceFirst ("\\Q"+pattern+"\\E", replacement)
case Some(Seq(pattern, "", replacement)) => algorithm(input replaceFirst ("\\Q"+pattern+"\\E", replacement))
case None => input
}
println(argv(1))
println(algorithm(argv(1)))