Skip to content

Instantly share code, notes, and snippets.

View bmarcot's full-sized avatar

Benoit Marcot bmarcot

  • Trondheim
View GitHub Profile
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# ensure that that e1 occurs before e2.
# page.body is the entire content of the page as a string.
assert page.body.index(e1) < page.body.index(e2)
end
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# another strategy with regex (see Hints part of the assignments)
page.body.scan(/.*"#{e1}".*"#{e2}".*/).length.should == 1
end
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)
def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())(f(_) :: _)
def isPrime(n: Int): Boolean = (2 to n - 1).forall(x => n % x != 0)
def ScalarProduct(xs: List[Double], ys: List[Double]): Double =
(for ((x, y) <- xs zip ys) yield x * y).sum
@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)
}
}
@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
}
}
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 / 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())
def split[A](chars: List[A], n: Int): List[List[A]] = {
if (chars.isEmpty) List()
else chars.take(n) :: split[A](chars.drop(n), n)
}
def encrypt_rec(chars: List[List[Char]]): List[List[Char]] = {
if (chars.isEmpty) Nil
else {
val cs = chars.filter(_.isEmpty == false)
cs.map(_.head) :: encrypt_rec(cs.map(_.tail))