Skip to content

Instantly share code, notes, and snippets.

@rkrzewski
Last active December 27, 2015 00:19
Show Gist options
  • Save rkrzewski/7236933 to your computer and use it in GitHub Desktop.
Save rkrzewski/7236933 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object S99_P17 {
def split_1l[T](n: Int, ts: Seq[T]) = ts.splitAt(n)
def split_tr[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) = {
@tailrec
def go(n: Int, lists: (Seq[T], Seq[T])): (Seq[T], Seq[T]) = (n, lists) match {
case (n, (heads, e +: tails)) if (n > 0) => go(n - 1, (e +: heads, tails))
case (_, (heads, tails)) => (heads.reverse, tails)
}
go(n, (Nil, ts))
}
def split_f[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) = {
val (left, right, _) = ts.foldLeft((Seq[T](), Seq[T](), 0)) {
case ((left, right, i), e) =>
if (i < n) (e +: left, right, i + 1)
else (left, e +: right, i + 1)
}
(left.reverse, right.reverse)
}
}
object S99_P18 {
def slice_tr[T](from: Int, to: Int, ts: Seq[T]): Seq[T] = {
@tailrec
def go(from: Int, to: Int, ts: Seq[T], acc: Seq[T]): Seq[T] =
ts match {
case head :: tail if from > 0 => go(from - 1, to - 1, tail, acc)
case head :: tail if to > 0 => go(0, to - 1, tail, head +: acc)
case _ => acc.reverse
}
go(from, to, ts, Nil)
}
}
object S99_P19 {
def rotate[T](n: Int, ts: Seq[T]): Seq[T] = {
@tailrec
def go(n: Int, ts: Seq[T], acc: Seq[T]): Seq[T] = (n, ts) match {
case (n, h +: t) if n > 0 => go(n - 1, t, h +: acc)
case _ => ts ++ acc.reverse
}
if (n >= 0) go(n % ts.length, ts, Nil)
else go(-n % ts.length, ts.reverse, Nil).reverse
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment