Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

HASKELL HOMEWORK 1. Data compression is very useful because it helps reduce reso

ID: 3683932 • Letter: H

Question

HASKELL HOMEWORK

1. Data compression is very useful because it helps reduce resources usage, such as data storage

space or transmission capacity. For this task, you can assume that the input strings consist

only of letters of the English alphabet.

(a) Run-length encoding (RLE) is a very simple form of data compression in which runs of data are stored as a single data value and a count, rather than as the original run.

Define a function rle that applied RLE to a the given string.

rle :: String -> String

rle "aaabbbbbc" --> "3a 5b 1c"

rle "banana" -> "1b 1a 1n 1a 1n 1a"

(b) Dene rleInverse that applies the inverse RLE operation (RLE decoding) on a given string.

Explanation / Answer

public static String encode(String source) {
StringBuffer dest = new StringBuffer();
for (int i = 0; i < source.length(); i++) {
int runLength = 1;
while (i + 1 < source.length()
&& source.charAt(i) == source.charAt(i + 1)) {
runLength++;
i++;
}
dest.append(runLength);
dest.append(source.charAt(i));
}
return dest.toString();
}

public static String decode(String source) {
StringBuffer dest = new StringBuffer();
Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z]");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
int number = Integer.parseInt(matcher.group());
matcher.find();
while (number-- != 0) {
dest.append(matcher.group());
}
}
return dest.toString();
}

public static void main(String[] args) {
String example = "aaaaabbbbbcccccr";
System.out.println(encode(example));
System.out.println(decode(encode(example)));
}
}

public static String decode(String st)

{

    if (st == "" || st == null) return "";

    char[] stArr = st.toCharArray();

    char lastseen = 0;

    StringBuffer sb = new StringBuffer();

    for (char s:stArr){

        if (!Character.isDigit(s)){

            lastseen = s;

            sb.append(s);

        }

        else{

            int n = Integer.parseInt(String.valueOf(s));

            for (int i=0;i<n-1;i++){

                sb.append(lastseen);

            }          

        }

    }

    return sb.toString();

}

public static String decode(String st)

{

    if (st == "" || st == null) return "";

    char[] stArr = st.toCharArray();

    char lastseen = 0;

    StringBuffer sb = new StringBuffer();

    for (char s:stArr){

        if (!Character.isDigit(s)){

            lastseen = s;

            sb.append(s);

        }

        else{

            int n = Integer.parseInt(String.valueOf(s));

            for (int i=0;i<n-1;i++){

                sb.append(lastseen);

            }          

        }

    }

    return sb.toString();

}