Run-length encoding: Difference between revisions
Content added Content deleted
(Added solution for Action!) |
|||
Line 3,494: | Line 3,494: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
The function |
|||
Custom functions using Map, Apply, pure functions, replacing using pattern matching, delayed rules and other functions: |
|||
⚫ | |||
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: |
|||
⚫ | |||
⚫ | |||
RunLengthDecode[%] |
|||
%==mystring</lang> |
|||
gives back: |
|||
<lang Mathematica>12W1B12W3B24W1B14W |
|||
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
|||
⚫ | |||
An alternate solution: |
|||
<lang Mathematica>RunLengthEncode[s_String] := StringJoin[ |
|||
{ToString[Length[#]] <> First[#]} & /@ Split[StringSplit[s, ""]] |
|||
] |
|||
⚫ | |||
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 |
|||
⚫ | |||
here is the run-length encoding: |
|||
⚫ | |||
{{"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] |
|||
⚫ | |||
=={{header|Maxima}}== |
=={{header|Maxima}}== |