Skip to content

Instantly share code, notes, and snippets.

def isSorted[A](as: Array[A])(gt: (A, A) => Boolean): Boolean = {
@annotation.tailrec
def go(index: Int, lastResult: java.lang.Boolean): Boolean = {
if (as.length < index + 1) {
true
} else {
val curr = gt(as(index - 1), as(index))
if (lastResult == null) {
go(index + 1, curr)
} else
def range(from: Int, to: Int): Seq[Int] = {
def fromN(n: Int): Stream[Int] = n #:: fromN(n + 1)
fromN(from).take(to - from + 1).toList
}
@ajozwik
ajozwik / P21.scala
Last active December 29, 2015 13:59
def insertAt[T](el: T, n: Int, ts: Seq[T]): Seq[T] = {
def insertToAcc: ((Seq[T], Int), T) => (Seq[T], Int) = {
(acc, current) => {
val (seq, index) = acc
if (index == 0) {
(current +: el +: seq, index - 1)
} else {
(current +: seq, index - 1)
}
}
def removeAt[T](n: Int, ts: Seq[T]): (Seq[T], T) = {
val (l, _, t) = ts.foldLeft[(Seq[T], Int, Option[T])]((Seq[T](), n, None))((acc, el) => {
if (acc._2 == 0) {
(acc._1, acc._2 - 1, Some(el))
} else {
(el +: acc._1, acc._2 - 1, acc._3)
}
}
)
(l.reverse, t.get)
@ajozwik
ajozwik / P19.scala
Last active December 27, 2015 00:29
def rotateN[T](n: Int, ts: Seq[T]): Seq[T] = {
def operation[T](triple: (Int, Seq[T], Seq[T]), t: T) = {
val (n, left, right) = triple
if (n > 0) (n - 1, left, t +: right) else (n, t +: left, right)
}
val size = ts.size
val rotate =
if (n >= 0) {
n % size
@ajozwik
ajozwik / P18.scala
Last active December 27, 2015 00:29
def slice[T](from: Int, to: Int, ts: Seq[T]): Seq[T] = {
def operation[T](triple: (Seq[T], Int, Int), t: T): (Seq[T], Int, Int) = {
val (acc, from, to) = triple
if (from > 0) {
(acc, from - 1, to - 1)
} else if (to > 0) {
(t +: acc, from, to - 1)
} else {
(acc, from, to)
@ajozwik
ajozwik / P17.scala
Last active December 27, 2015 00:19
def split[T](n: Int, ts: Seq[T]): (Seq[T], Seq[T]) = {
val (_, left, right) = ts.foldLeft(n, Seq[T](), Seq[T]())(operation)
(left.reverse, right.reverse)
}
def operation[T](triple: (Int, Seq[T], Seq[T]), el: T) = {
val (index, left, right) = triple
if (index <= 0) {
(0, left, el +: right)
} else {
@ajozwik
ajozwik / P16.scala
Last active December 25, 2015 17:19
def drop[T](n: Int, ts: Seq[T]): Seq[T] =
ts.foldLeft((n, Seq[T]()))((acc, t) => {
val (x, ts) = acc
if (x == 1) (n, ts) else (x - 1, ts :+ t)
})._2
def p16[T](nr: Int, list: Seq[T]): Seq[T] = {
def p16( list: Seq[T], index: Int, acc: Seq[T]): Seq[T] = list match {
case Nil => acc
case h :: t if (nr == index) => p16( t, 1, acc)
def p14[T](ts: Seq[T]): Seq[T] = p15(2,ts)
def p15[T](n:Int,ts: Seq[T]): Seq[T] = {
def p15( ts: Seq[T], acc: Seq[T]): Seq[T] = ts match {
case Nil => acc.reverse
case h :: t => p15(t, Seq.fill(n)(h) ++ acc)
}
p15( ts, Nil)
}
@tailrec
final def pack[T, R](list: Seq[T], result: Seq[R])(f: Seq[T] => R): Seq[R] = list match {
case Nil => result
case h :: t => list span {
_ == h
} match {
case (packed, next) => {
pack(next, result :+ f(packed))(f)
}
}