Skip to content

Instantly share code, notes, and snippets.

View bmarcot's full-sized avatar

Benoit Marcot bmarcot

  • Trondheim
View GitHub Profile
@bmarcot
bmarcot / tsort.scala
Created July 30, 2013 11:04
Topological sort in Scala.
def tsort(gs: List[(Int, List[Int])]): List[Int] = {
gs match {
case g :: gs => {
if (g._2.isEmpty) g._1 :: tsort(gs.diff(List(g)).map(x => (x._1, x._2.diff(List(g._1)))))
else tsort(gs :+ g)
}
case _ => List()
}
}
@bmarcot
bmarcot / problem_solving.scala
Last active December 20, 2015 07:08
Work in progress...
def tsort(gs: List[(Int, List[Int])]): List[Any] = {
if (gs.isEmpty) List()
else for {
g <- gs
if (g._2.isEmpty)
} yield g._1 :: tsort(gs.diff(List(g)).map(x => (x._1, x._2.diff(List(g._1)))))
} //> tsort: (gs: List[(Int, List[Int])])List[Any]
def tsort_aux(xs: List[Any]): List[List[Int]] = {
if (xs.isEmpty) List(List())
@bmarcot
bmarcot / knapsack_problem.scala
Last active June 28, 2017 13:41
The Knapsack Problem, in Scala -- Keywords: dynamic programming, recursion, scala.
def knapsack_aux(x: (Int, Int), is: List[Int]): List[Int] = {
for {
w <- is.zip(is.take(x._1) ::: is.take(is.size - x._1).map(_ + x._2))
} yield math.max(w._1, w._2)
}
def knapsack_rec(xs: List[(Int, Int)], is: List[Int]): List[List[Int]] = {
xs match {
case x :: xs => knapsack_aux(x, is) :: knapsack_rec(xs, knapsack_aux(x, is))
case _ => Nil
case class Order(val id: Int, val card: Int, val address: String)
// val m = (for (i <- 1 to 4) yield Order(i)) zip List(1, 1, 2, 3)
// m.groupBy(_._2)
val orders = (for {
order <- List(Order(1, 46459, "3, calle Brazil, Torremolinos"),
Order(2, 85475, "102, av JB Clement, Boulogne"),
Order(1, 78545, "1, Paradize Bvld., Palo Alto"))
} yield (order, order.id))
@bmarcot
bmarcot / for_comprehension.scala
Last active December 16, 2015 22:39
For-comprehension
def f(xs: List[Int]): List[List[(Int, Int)]] = {
xs match {
case Nil => List(List())
case x :: xs => for {
ns <- f(xs)
i <- 0 to x
} yield (x, i) :: ns
}
}
@bmarcot
bmarcot / epfl_wk_6_3.scala
Last active December 16, 2015 19:49
The ``N Queens'' problem in Scala.
def queens(n: Int): Set[List[Int]] = {
def isSafe(col: Int, queens: List[Int]): Boolean = {
val row = queens.length
val queensWithRow = queens zip (row - 1 to 0 by -1)
queensWithRow.forall {
case (c, r) => c != col && (math.abs(col - c) != row - r)
}
}
def ScalarProduct(xs: List[Double], ys: List[Double]): Double =
(for ((x, y) <- xs zip ys) yield x * y).sum
def isPrime(n: Int): Boolean = (2 to n - 1).forall(x => n % x != 0)
def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())(f(_) :: _)
def squareList(xs: List[Int]): List[Int] = xs match {
case Nil => Nil
case y :: ys => y * y :: squareList(ys)
}
def squareList(xs: List[Int]): List[Int] = xs map (y => y * y)