Created
October 29, 2012 22:20
-
-
Save martintrojer/3976925 to your computer and use it in GitHub Desktop.
Scala comb search
This file contains 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
import scala.io.Source | |
object mnem { | |
val in = Source.fromURL("http://lamp.epfl.ch/files/content/sites/lamp/files/teaching/progfun/linuxwords.txt") | |
val words = in.getLines.toList filter (word => word forall (c => c.isLetter)) | |
val mnem = Map( | |
'2' -> "ABC", '3' -> "DEF", 4 -> "GHI", '5' -> "JKL", | |
'6' -> "MNO", '7' -> "PQRS", '8' -> "TUV", 9 -> "WXYZ") | |
val charCode: Map[Char, Char] = | |
for { | |
(digit:Char, str) <- mnem | |
ltr <- str | |
} yield ltr -> digit | |
def wordCode(word: String) = | |
word.toUpperCase map charCode | |
val wordsForNum: Map[String, Seq[String]] = | |
words groupBy wordCode withDefaultValue Seq() | |
def encode(number: String): Set[List[String]] = | |
if (number.isEmpty) Set(List()) | |
else { | |
for { | |
split <- 1 to number.length | |
word <- wordsForNum(number take split) | |
rest <- encode(number drop split) | |
} yield word :: rest | |
}.toSet | |
def translate(number: String): Set[String] = | |
encode(number) map (_ mkString " ") | |
translate("7225247386") | |
} |
This file contains 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
object nqueens { | |
def queens(n: Int): Set[List[Int]] = { | |
def placeQueens(k: Int): Set[List[Int]] = { | |
if (k == 0) Set(List()) | |
else | |
for { | |
queens <- placeQueens(k - 1) | |
col <- 0 until n | |
if isSafe(col, queens) | |
} yield col :: queens | |
} | |
placeQueens(n) | |
} | |
def isSafe(col: Int, queens: List[Int]): Boolean = { | |
val row = queens.length | |
val queensWithRow = (row - 1 to 0 by -1) zip queens | |
queensWithRow forall { | |
case (r,c) => col != c && math.abs(col - c) != row - r | |
} | |
} | |
queens(4) //> res0: Set[List[Int]] = Set(List(1, 3, 0, 2), List(2, 0, 3, 1)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment