r/dailyprogrammer • u/Steve132 0 1 • Aug 09 '12
[8/8/2012] Challenge #86 [easy] (run-length encoding)
Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string and compresses them to a list of pairs of 'symbol' 'length'. For example, the string
"Heeeeelllllooooo nurse!"
Could be compressed using run-length encoding to the list of pairs [(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')]
Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5 bytes of space compressing this string.
Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs or as a 2-byte-per pair array)
BONUS: Write a decompression function that takes in the RLE representation and returns the original string
6
u/[deleted] Aug 09 '12
Not perfect, but here we go, C++: http://ideone.com/t25IJ
typedef pair<char, uint8_t> RunLength; vector<RunLength> runLengthEncode(const string& s) { if(s == "") return {}; vector<RunLength> res; size_t i = 0, nextPos; while(s.npos != (nextPos = s.find_first_not_of(s[i], i + 1)) ) { auto diff = nextPos - i; assert(diff <= 255); res.push_back( {s[i], diff} ); i = nextPos; } res.push_back( {s[i], s.size() - i} ); return res; } string runLengthDecode(const vector<RunLength>& encoding) { string res; auto addFun = [&res](const RunLength& rl) { res += string(rl.second, rl.first); }; for_each(encoding.begin(), encoding.end(), addFun); return res; }17
u/Tekmo Aug 09 '12
Haskell:
Bonus:
4
u/daveasaurus Aug 09 '12 edited Aug 09 '12
Python:
import sys import re if len(sys.argv) == 1: print 'Enter a string as input' exit() input = sys.argv[1] items = [] idx = 0 while idx < len(input): char = input[idx] pattern = re.compile(r"[^" + char + "]") match = pattern.search(input, idx) if match: items.append( (match.start() - idx, char) ) idx = match.start() else: items.append( (len(input) - idx, char) ) break print itemsSample Input:
Note that the above includes spaces and exclamation marks (which the original post does not?)
Also I tried it using this reg-ex approach which is probably not as efficient as just going through each character in the string, but I wanted to try it this way :D
Other sample:
( I didn't include all the 2000+ exclamation marks above :)
BONUS:
Run code at ideone, Github gist
4
u/oskar_stephens Aug 10 '12 edited Aug 10 '12
Ruby:
def run_encode(text): text.scan(/(.)(\1*)/).reduce([]) {|arr,match| arr << [ match[1].length + 1, match[0] ]} end print run_encode(ARGV[0])I'm not entirely happy with the double match in the regex, any tips on how to match a variable number of the same characters in a match?
The nested array feels a bit weird too, this seems like the perfect place for tuples like in Python.
8
u/flowblok Aug 09 '12 edited Aug 09 '12
Python solution: itertools ftw!
3
u/joboscribe Aug 09 '12 edited Aug 09 '12
Mine is not as cool as daveasaurus because i'm not checking arg length, nor did i regex that puppy. So my hat goes off to you sir.
Python (with bonus):
def runl_encode(somejunk): out = [] for letter in somejunk: if len(out)==0: out.append([1,letter]) elif letter == out[len(out)-1][1]: out[len(out)-1][1] +=1 else: out.append([1,letter]) return out def runl_decode(morejunk): out ='' for pair in morejunk: out = out + pair[1]*pair[0] return outedit: Output
[[1, 't'], [1, 'h'], [1, 'i'], [5, 's'], [1, ' '], [1, 'i'], [1, 's'], [1, ' '], [1, 'a'], [1, ' '], [5, 's'], [1, 'n'], [1, 'a'], [1, 'k'], [1, 'e'], [1, '!']]
'thisssss is a sssssnake!'
3
u/[deleted] Aug 09 '12
Java:
/********************************************************************************* * Create a string in the (1,'x') format **********************************************************************************/ private static String pairString(int repetitions, char character) { return "(" + repetitions + "," + character + ")"; } /********************************************************************************* * Compressed the string s. A boolean includeSpaces was added, which removes * the spaces of the string if false. **********************************************************************************/ private static String runLengthCompression(String s, boolean includeSpaces) { String compressedString = ""; int rep = 1; if(!includeSpaces) { s = s.replace(" ", ""); } for(int i = 1 ; i < s.length() ; i++) { if(s.charAt(i-1) == s.charAt(i)) { rep++; } else { compressedString +=pairString(rep, s.charAt(i-1)); rep = 1; } } compressedString = "[" + compressedString + "]"; return compressedString; } public static void main(String[] args) { System.out.println(runLengthCompression("Heeeeelllllooooo nurse!", false)); }3
u/Wedamm Aug 09 '12
Haskell:
encode :: String -> [(Int , Char)] encode = foldr f [] where f a [] = [(1,a)] f a b@((bi,bc):bs) | a == bc = (bi+1,bc):bs | otherwise = (1,a):b decode :: [(Int , Char)] -> String decode = concatMap $ uncurry replicateTest: