Anonymous user
Run-length encoding: Difference between revisions
→{{header|Mathematica}}/{{header|Wolfram Language}}
(Added solution for Action!) |
|||
Line 3,494:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
The function
<lang Mathematica>RunLengthEncode[input_String]:=StringJoin@@Sequence@@@({ToString @Length[#],First[#]}&/@Split[Characters[input]])▼
<lang Mathematica>mystring="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";▼
RunLengthEncode[mystring]▼
True</lang>▼
▲<lang Mathematica>RunLengthEncode[input_String]:=
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
<lang Mathematica>RunLengthDecode[input_List]:= ConstantArray @@@ input // Flatten // StringJoin</lang>
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}}==
|