Run-length encoding: Difference between revisions

(Added solution for Action!)
Line 3,494:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The function
Custom functions using Map, Apply, pure functions, replacing using pattern matching, delayed rules and other functions:
<lang Mathematica>RunLengthEncode[input_String]:=StringJoin@@Sequence@@@({ToString @Length[#],First[#]}&/@Split[Characters[input]])
RunLengthDecode[input_String]:=StringJoin@@ConstantArray@@@Reverse/@Partition[(Characters[input]/.(ToString[#]->#&/@Range[0,9]))//.{x___,i_Integer,j_Integer,y___}:>{x,10i+j,y},2]</lang>
Example:
<lang Mathematica>mystring="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
RunLengthEncode[mystring]
RunLengthDecode[%]
%==mystring</lang>
gives back:
<lang Mathematica>12W1B12W3B24W1B14W
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
True</lang>
An alternate solution:
<lang Mathematica>RunLengthEncode[s_String] := StringJoin[
{ToString[Length[#]] <> First[#]} & /@ Split[StringSplit[s, ""]]
]
 
<lang Mathematica>RunLengthEncode[input_String]:=StringJoin@@Sequence@@@ ({ToStringl |-> {First@Length[#]l,First[#] Length@l}&) /@ (Split[@Characters[@input]])</lang>
RunLengthDecode[s_String] := StringJoin[
 
Table[#[[2]], {ToExpression[#[[1]]]}] & /@
takes as input an arbitrary string of characters and returns a list of {c, n} pairs, where c is the character and n is the number of repeats. The function
Partition[StringSplit[s, x : _?LetterQ :> x], 2]
 
]</lang>
<lang Mathematica>RunLengthDecode[input_List]:= ConstantArray @@@ input // Flatten // StringJoin</lang>
This second encode function is adapted from the MathWorld example.
 
recreates the string.
 
Example: For the string
 
<lang Mathematica>mystring="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";</lang>
 
here is the run-length encoding:
 
<lang Mathematica>rle = RunLengthEncode[mystring]
{{"W", 12}, {"B", 1}, {"W", 12}, {"B", 3}, {"W", 24}, {"B", 1}, {"W", 14}}</lang>
 
Check that the input string is recreated:
 
<lang Mathematica>mystring == RunLengthEncode[rle]
True</lang>
 
=={{header|Maxima}}==