Skip to content

Instantly share code, notes, and snippets.

View jacekkolodziejski's full-sized avatar

jacekkolodziejski

View GitHub Profile
def length[T](ts: Seq[T]): Int = (0 /: ts)((x, _) => x + 1)
import annotation.tailrec
def encode[T](ts: Seq[T]): Seq[(Int, T)] = {
@tailrec
def go(acc: Seq[(Int, T)], ts: Seq[T]): Seq[(Int, T)] = ts match {
case Nil => acc
case _ => {
val (left, right) = ts.span(_ == ts.head)
go(acc :+ (left.size, left.head), right)
}
}
def isSorted[A](as: Array[A])(gt: (A, A) => Boolean): Boolean = as.size match {
case 0 => true
case 1 => true
case _ =>
val (h2, tail) = as.splitAt(2)
gt(h2(0), h2(1)) && isSorted(tail)(gt)
}
package pl.japila.scalania.s99
object S99_P20 {
def removeAt[T](n: Int, ts: Seq[T]): (Seq[T], T) =
(ts.take(n) ++ ts.drop(n + 1), ts(n))
}
object S99_P19 {
def rotate[T](n: Int, ts: Seq[T]): Seq[T] = {
val ammount = if (n > 0) n else (n + ts.length)
ts.drop(ammount) ++ ts.take(ammount)
}
}
object S99_P18 {
import S99_P17.split
def slice[T](from: Int, to: Int, ts: Seq[T]): Seq[T] =
split(ts.length - to, split(from, ts)._2.reverse)._2.reverse
}
import annotation.tailrec
object S99_P17 {
def split[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) =
ts.splitAt(n)
def split[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) =
(ts.take(n), ts.drop(n))
def split[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) = {
object S99_P16 {
def drop[T](n: Int, ts: Seq[T]): Seq[T] = {
var iter = 0;
def op(el: T): Boolean = { iter = iter + 1; (iter % n != 0) }
ts filter op
}
def drop[T](n: Int, ts: Seq[T]): Seq[T] =
for (e <- ts.zipWithIndex if (e._2 + 1) % n != 0) yield e._1
object S99_P15 {
def duplicateN[T](n: Int, ts: Seq[T]): Seq[T] =
ts flatMap { List.fill(n)(_) }
def duplicateN[T](n: Int, ts: Seq[T]): Seq[T] = ts match{
case Nil => Nil
case head::tail => List.fill(n)(head) ++ duplicateN(n,tail)
}
object S99_P14 {
def duplicate[T](ts: Seq[T]): Seq[T] = ts.flatMap(e => List(e, e))
}