-
Notifications
You must be signed in to change notification settings - Fork 2
/
RLE_Decoder.scala
34 lines (27 loc) · 913 Bytes
/
RLE_Decoder.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package cryptographyOperations.decoders
import utils.ExceptionMessages.EmptyInput
import utils.InputException
import scala.annotation.tailrec
/**
* Contains realisation of RLE decoder: https://en.wikipedia.org/wiki/Run-length_encoding
*
* Purity project by Daniil Tekunov.
*/
object RLE_Decoder {
/**
* Decoder itself, returns outcome List.
*/
@tailrec
private def makeList[A](countOfElements: Int, element: A, customList: List[A] = List()): List[A] =
countOfElements match {
case 0 => customList
case _ => makeList(countOfElements - 1, element, customList :+ element)
}
/**
* Sub-function for decoder, that checks input and flatmaps the List.
*/
def decode[A](input: List[(Int, A)]): List[A] = {
if (input.isEmpty) throw new InputException("\"getElement\" " + EmptyInput)
else input flatMap { element => makeList(element._1, element._2) }
}
}