Skip to content

Instantly share code, notes, and snippets.

View jacekkolodziejski's full-sized avatar

jacekkolodziejski

View GitHub Profile
@jacekkolodziejski
jacekkolodziejski / Scalania cheatsheet
Last active December 22, 2015 18:19
Powtórzenie przed scalania #3
//uruchamiać w scala REPL
1
1+2
//REPL tworzy własne zmienne
res0
res1
//Operacje na listach
1::Nil
def p9[T](list: Seq[T]): Seq[Seq[T]] = list match {
case Nil => Nil
case a :: tail => {
val tmp = list span (_ == a)
List(tmp._1) ++ p9(tmp._2)
}
} //> p9: [T](list: Seq[T])Seq[Seq[T]]
p9(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))
//> res0: Seq[Seq[Symbol]] = List(List('a, 'a, 'a, 'a), List('b), List('c, 'c),
//| List('a, 'a), List('d), List('e, 'e, 'e, 'e))
def p12a[T](list: Seq[(Int, T)]): Seq[T] =
list flatMap { e => List.fill(e._1)(e._2) } //> p12a: [T](list: Seq[(Int, T)])Seq[T]
def p12b[T](list: Seq[(Int, T)]): Seq[T] =
list.flatMap {
case (i, e) => List.fill(i)(e)
} //> p12b: [T](list: Seq[(Int, T)])Seq[T]
p12b(List((4, 'a), (1, 'b), (2, 'c), (2, 'a), (1, 'd), (4, 'e)))
//> res0: Seq[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e,
object tmp2 {
import annotation.tailrec
def p13[T](list: Seq[T]): Seq[(Int, T)] = {
if (list.isEmpty) Nil
else {
val (left, right) = list span (_ == list.head)
Seq((left.length, left.head)) ++ p13(right)
}
} //> p13: [T](list: Seq[T])Seq[(Int, T)]
object S99_P14 {
def duplicate[T](ts: Seq[T]): Seq[T] = ts.flatMap(e => List(e, e))
}
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_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
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_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
}
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)
}
}