-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathRLE_Encoder.scala
More file actions
39 lines (32 loc) · 993 Bytes
/
RLE_Encoder.scala
File metadata and controls
39 lines (32 loc) · 993 Bytes
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
35
36
37
38
39
package cryptographyOperations.encoders
import utils.InputException
import utils.ExceptionMessages.EmptyInput
/**
* Contains realisation of RLE encoder: https://en.wikipedia.org/wiki/Run-length_encoding
*
* Purity project by Daniil Tekunov.
*/
object RLE_Encoder {
/**
* Packs repeated elements in a list of lists
*/
private def pack[A](input: List[A]): List[List[A]] = {
if (input.isEmpty) List(List())
else {
val (packed, next) = input span { _ == input.head }
if (next == Nil) List(packed)
else packed :: pack(next)
}
}
/**
* Returns RLE-encoded sequence of tuples in (7, 'a) style
*/
def encode[A](input: List[A]): List[(Int, A)] = {
( if (input.isEmpty) throw new InputException("\"RLE encoding\" " + EmptyInput)
else {
val (packed, next) = input span { _ == input.head }
if (next == Nil) List(packed)
else packed :: pack(next)
}) map { element => (element.length, element.head) }
}
}