This solves the n-Queens puzzle in 1 line of code.
def nQueens(n: Int) = (0 until n).permutations filter {p =>
p.zipWithIndex.flatMap{case (c, d) => Seq(n + c + d, c - d)}.distinct.size == 2*n
}
// Pretty print all 92 solutions for n=8
nQueens(8).zipWithIndex foreach {case (solution, num) =>
println(s"Solution #${num + 1}:")
val rows = solution.map(col => solution.indices.map(i => if (i == col) 'Q' else '-').mkString)
rows foreach println
}
See: https://gist.github.com/pathikrit/6fa878fe87c6160a52c4c27dabbfa6df
This is a Sudoku solver in Scala: https://gist.github.com/pathikrit/a32e17832296befd6b94
val n = 9
val s = Math.sqrt(n).toInt
type Board = IndexedSeq[IndexedSeq[Int]]
def solve(board: Board, cell: Int = 0): Option[Board] = (cell%n, cell/n) match {
case (r, `n`) => Some(board)
case (r, c) if board(r)(c) > 0 => solve(board, cell + 1)
case (r, c) =>
def cells(i: Int) = Seq(board(r)(i), board(i)(c), board(s*(r/s) + i/s)(s*(c/s) + i%s))
def guess(x: Int) = solve(board.updated(r, board(r).updated(c, x)), cell + 1)
val used = board.indices flatMap cells
1 to n diff used collectFirst Function.unlift(guess)
}
//////////////////////////////////////////////////////////////////
import scala.collection.{IndexedSeq => $}
val board = $( //0s denote empty cells
$(1, 0, 0, 0, 0, 7, 0, 9, 0),
$(0, 3, 0, 0, 2, 0, 0, 0, 8),
$(0, 0, 9, 6, 0, 0, 5, 0, 0),
$(0, 0, 5, 3, 0, 0, 9, 0, 0),
$(0, 1, 0, 0, 8, 0, 0, 0, 2),
$(6, 0, 0, 0, 0, 4, 0, 0, 0),
$(3, 0, 0, 0, 0, 0, 0, 1, 0),
$(0, 4, 0, 0, 0, 0, 0, 0, 7),
$(0, 0, 7, 0, 0, 0, 3, 0, 0)
)
println(solve(board).get.map(_ mkString " ") mkString "\n")
Something short and sweet: https://gist.github.com/pathikrit/6d1917174e8278bada65
def isPalindrome[A](x: Vector[A]): Boolean = x match {
case start +: middle :+ end => start == end && isPalindrome(middle)
case _ => true
}
Finally, Peter Norvig’s spell checker in Scala https://gist.github.com/pathikrit/d5b26fe1c166a97e2162:
class AutoSuggest(corpus: String, alphabet: Seq[Char] = 'a' to 'z', depth: Int = 2) {
val words = s"[${alphabet.head}-${alphabet.last}]+".r
.findAllIn(corpus.toLowerCase).toSeq
.groupBy(_.toSeq).mapValues(_.size)
.par withDefaultValue 0
def editDistance(a: Seq[Char], b: Seq[Char]) = {
lazy val d: Stream[Stream[Int]] = Stream.tabulate(a.length + 1, b.length + 1) {
case (i, j) if (i - j).abs > depth => Int.MaxValue
case (i, 0) => i
case (0, j) => j
case (i, j) if a(i-1) == b(j-1) => d(i-1)(j-1)
case (i, j) => 1 + (d(i)(j-1) min d(i-1)(j) min d(i-1)(j-1))
}
d(a.length)(b.length)
}
def apply(word: String) = words maxBy {case (i, frequency) => -editDistance(i, word) -> frequency}
}
// Demo:
object AutoSuggest extends App {
val suggest = new AutoSuggest(io.Source.fromFile("big.txt").mkString) // curl http://norvig.com/big.txt > big.txt
Seq("speling", "korrecter", "corrected", "xyz") foreach {w => println(s"$w: ${suggest(w)}")}
}```