In: Computer Science
Q, Haskell.
I need to define function encode and decode. Details about the functions are provided in code.
-- | encode -- -- Given a string, return a list of encoded values of type (Int,Char) -- -- >>> encode ['a','a','a','a','b','c','c','a','a','d','e','e','e','e'] -- [(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')] -- -- >>> encode "hello" -- [(1,'h'),(1,'e'),(2,'l'),(1,'o')] -- -- >>> encode [] -- [] -- encode :: String -> [(Int,Char)] encode = undefined -- | decode -- -- Given a list of encoded values of type (Int,Char), generate a string corresponding to -- this encoding. -- -- If the first element of any pair in the list is equal to zero or negative, -- skip the corresponding character in the output string, -- while still providing decodings for the remaining characters. -- -- -- >>> decode [(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')] -- "aaaabccaadeeee" -- -- >>> decode [] -- "" -- -- >>> decode [(-4,'a')] -- "" -- -- >>> decode [(3,'c'),(-4,'a'),(5,'b')] -- "cccbbbbb" -- -- >>>decode [(3,'c'),(0,'a'),(5,'b')] -- "cccbbbbb" -- -- prop> \x -> x == decode (encode x) -- decode :: [(Int,Char)] -> String decode = undefined
import java.util.*;
public class EncodeDecode {
static class Result
{
int freq;
char data;
public Result(int freq, char
data)
{
this.freq =
freq;
this.data =
data;
}
public String toString()
{
return "(" +
freq + ", " + "'" + data + "'" + ")";
}
}
public static List<Result> encode(String
str)
{
if(str == null)
return
null;
List<Result> list = new
ArrayList<>();
if(str.length() < 1)
return
list;
int freq = 1;
char ch = str.charAt(0);
EncodeDecode.Result
node;
for(int i = 1; i <=
str.length();i++)
{
while(i <
str.length() && str.charAt(i) == ch)
{
freq++;
i++;
}
node = new
EncodeDecode.Result(freq, ch);
list.add(node);
if(i <
str.length())
{
ch = str.charAt(i);
freq = 1;
}
}
return list;
}
public static String decode(List<Result>
list)
{
if(list == null)
return
null;
StringBuilder str = new
StringBuilder();
if(list.size() < 1)
return
str.toString();
for(Result res : list)
{
if(res.freq <
1)
continue;
while(res.freq--
> 0)
{
str.append(res.data);
}
}
return str.toString();
}
public static void main(String[] args) {
// Driver Method
List<Result> ans =
encode("aabccaadeeee");
System.out.println(ans);
System.out.println(decode(ans));
}
}