Skip to content

Instantly share code, notes, and snippets.

@rkrzewski
Last active December 22, 2015 20:29
Show Gist options
  • Save rkrzewski/6526956 to your computer and use it in GitHub Desktop.
Save rkrzewski/6526956 to your computer and use it in GitHub Desktop.
scalania
def p8[T](list: Seq[T]): Seq[T] =
list.foldRight(Seq[T]())((e, l) =>
if (l.isEmpty || e != l.head) e +: l
else l)
def p9[T](list: Seq[T]): Seq[Seq[T]] =
list.foldRight(Seq[Seq[T]]())((e, l) =>
if (l.isEmpty || e != l.head.head) Seq(e) +: l
else (e +: l.head) +: l.tail)
def p10[T](list: Seq[T]): Seq[(Int, T)] =
p9(list).map(l => (l.length, l.head))
def p11[T](list: Seq[T]): Seq[Either[(Int, T), T]] =
p9(list).map { l =>
if (l.size > 1) Left(l.length, l.head)
else Right(l.head)
}
def p12[T](list: Seq[(Int, T)]): Seq[T] =
list.flatMap { case (n, e) => Seq.fill(n)(e) }
def p13[T](list: Seq[T]): Seq[(Int, T)] =
list.foldRight(Seq[(Int, T)]())((e, l) =>
if (l.isEmpty || e != l.head._2) (1, e) +: l
else (l.head._1 + 1, l.head._2) +: l.tail)
def p14[T](list: Seq[T]): Seq[T] = {
@tailrec
def go(list: Seq[T], acc: Seq[T]): Seq[T] = list match {
case Seq() => acc
case h :: t => go(t, h +: h +: acc)
}
go(list, Seq()).reverse
}
def p16[T](nr: Int, list: Seq[T]): Seq[T] =
list.zipWithIndex.filter(t => (t._2 + 1) % nr != 0).map(_._1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment