Run-length encoding: Difference between revisions
Content added Content deleted
(added Ol) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 21: | Line 21: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F encode(input_string) |
||
V count = 1 |
V count = 1 |
||
V prev = Char("\0") |
V prev = Char("\0") |
||
Line 44: | Line 44: | ||
V value = encode(‘aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa’) |
V value = encode(‘aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa’) |
||
print(‘Encoded value is ’value.map(v -> String(v[1])‘’v[0])) |
print(‘Encoded value is ’value.map(v -> String(v[1])‘’v[0])) |
||
print(‘Decoded value is ’decode(value))</ |
print(‘Decoded value is ’decode(value))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 55: | Line 55: | ||
Output is in hexadecimal but is otherwise correct. |
Output is in hexadecimal but is otherwise correct. |
||
< |
<syntaxhighlight lang="asm"> .model small ; 128k .exe file |
||
.stack 1024 ; load SP with 0400h |
.stack 1024 ; load SP with 0400h |
||
.data ; no data segment needed |
.data ; no data segment needed |
||
Line 118: | Line 118: | ||
OutputRam byte 256 dup (0) |
OutputRam byte 256 dup (0) |
||
end start</ |
end start</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 131: | Line 131: | ||
=={{header|Action!}}== |
=={{header|Action!}}== |
||
< |
<syntaxhighlight lang="action!">BYTE FUNC GetLength(CHAR ARRAY s BYTE pos) |
||
CHAR c |
CHAR c |
||
BYTE len |
BYTE len |
||
Line 230: | Line 230: | ||
PrintE("decoded:") |
PrintE("decoded:") |
||
PrintE(decoded) |
PrintE(decoded) |
||
RETURN</ |
RETURN</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Run-length_encoding.png Screenshot from Atari 8-bit computer] |
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Run-length_encoding.png Screenshot from Atari 8-bit computer] |
||
Line 245: | Line 245: | ||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO; |
||
with Ada.Strings.Fixed; use Ada.Strings.Fixed; |
with Ada.Strings.Fixed; use Ada.Strings.Fixed; |
||
procedure Test_Run_Length_Encoding is |
procedure Test_Run_Length_Encoding is |
||
Line 292: | Line 292: | ||
Put_Line (Encode ("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); |
Put_Line (Encode ("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); |
||
Put_Line (Decode ("12W1B12W3B24W1B14W")); |
Put_Line (Decode ("12W1B12W3B24W1B14W")); |
||
end Test_Run_Length_Encoding;</ |
end Test_Run_Length_Encoding;</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre> |
<pre> |
||
Line 307: | Line 307: | ||
Note: The following uses iterators, eliminating the need of declaring arbitrarily large CHAR arrays for caching. |
Note: The following uses iterators, eliminating the need of declaring arbitrarily large CHAR arrays for caching. |
||
< |
<syntaxhighlight lang="algol68">STRING input := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
||
STRING output := "12W1B12W3B24W1B14W"; |
STRING output := "12W1B12W3B24W1B14W"; |
||
Line 378: | Line 378: | ||
print(c) |
print(c) |
||
# OD # ); |
# OD # ); |
||
print(new line)</ |
print(new line)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 386: | Line 386: | ||
=={{header|APL}}== |
=={{header|APL}}== |
||
< |
<syntaxhighlight lang="apl"> ∇ ret←RLL rll;count |
||
[1] count←∣2-/((1,(2≠/rll),1)×⍳1+⍴rll)~0 |
[1] count←∣2-/((1,(2≠/rll),1)×⍳1+⍴rll)~0 |
||
[2] ret←(⍕count,¨(1,2≠/rll)/rll)~' ' |
[2] ret←(⍕count,¨(1,2≠/rll)/rll)~' ' |
||
∇ |
∇ |
||
</syntaxhighlight> |
|||
</lang> |
|||
Sample Output: |
Sample Output: |
||
<pre> |
<pre> |
||
Line 398: | Line 398: | ||
=={{header|AppleScript}}== |
=={{header|AppleScript}}== |
||
< |
<syntaxhighlight lang="applescript">------------------ RUN-LENGTH ENCODING ----------------- |
||
-- encode :: String -> String |
-- encode :: String -> String |
||
Line 556: | Line 556: | ||
end repeat |
end repeat |
||
v |
v |
||
end |until|</ |
end |until|</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>W12B1W12B3W24B1W14 |
<pre>W12B1W12B3W24B1W14 |
||
Line 564: | Line 564: | ||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
< |
<syntaxhighlight lang="rebol">runlengthEncode: function [s][ |
||
join map chunk split s => [&] 'x -> |
join map chunk split s => [&] 'x -> |
||
(to :string size x) ++ first x |
(to :string size x) ++ first x |
||
Line 584: | Line 584: | ||
print ["decoded:" decoded] |
print ["decoded:" decoded] |
||
if decoded=str -> print "\nSuccess!"</ |
if decoded=str -> print "\nSuccess!"</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 594: | Line 594: | ||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">MsgBox % key := rle_encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
MsgBox % rle_decode(key) |
MsgBox % rle_decode(key) |
||
Line 628: | Line 628: | ||
} |
} |
||
Return output |
Return output |
||
}</ |
}</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
Line 637: | Line 637: | ||
'''Encoding''' |
'''Encoding''' |
||
< |
<syntaxhighlight lang="awk">BEGIN { |
||
FS="" |
FS="" |
||
} |
} |
||
Line 652: | Line 652: | ||
} |
} |
||
printf("%d%c", j, cp) |
printf("%d%c", j, cp) |
||
}</ |
}</syntaxhighlight> |
||
'''Decoding''' |
'''Decoding''' |
||
< |
<syntaxhighlight lang="awk">BEGIN { |
||
RS="[0-9]+[^0-9]" |
RS="[0-9]+[^0-9]" |
||
final = ""; |
final = ""; |
||
Line 668: | Line 668: | ||
END { |
END { |
||
print final |
print final |
||
}</ |
}</syntaxhighlight> |
||
=={{header|BaCon}}== |
=={{header|BaCon}}== |
||
< |
<syntaxhighlight lang="qbasic">FUNCTION Rle_Encode$(txt$) |
||
LOCAL result$, c$ = LEFT$(txt$, 1) |
LOCAL result$, c$ = LEFT$(txt$, 1) |
||
Line 712: | Line 712: | ||
encoded$ = Rle_Encode$(rle_data$) |
encoded$ = Rle_Encode$(rle_data$) |
||
PRINT "Encoded: ", encoded$ |
PRINT "Encoded: ", encoded$ |
||
PRINT "Decoded: ", Rle_Decode$(encoded$)</ |
PRINT "Decoded: ", Rle_Decode$(encoded$)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>RLEData: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>RLEData: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 725: | Line 725: | ||
{{trans|PowerBASIC}} |
{{trans|PowerBASIC}} |
||
< |
<syntaxhighlight lang="qbasic">DECLARE FUNCTION RLDecode$ (i AS STRING) |
||
DECLARE FUNCTION RLEncode$ (i AS STRING) |
DECLARE FUNCTION RLEncode$ (i AS STRING) |
||
Line 779: | Line 779: | ||
outP = outP + tmp2 |
outP = outP + tmp2 |
||
RLEncode$ = outP |
RLEncode$ = outP |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
Sample output (last one shows errors from using numbers in input string): |
Sample output (last one shows errors from using numbers in input string): |
||
Line 799: | Line 799: | ||
=={{header|BASIC256}}== |
=={{header|BASIC256}}== |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
function FBString(lon, cad$) |
function FBString(lon, cad$) |
||
# Definimos la función String en BASIC256 |
# Definimos la función String en BASIC256 |
||
Line 877: | Line 877: | ||
print decoded$ |
print decoded$ |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
La salida es similar a la de [[#BASIC|BASIC]], mostrada arriba. |
La salida es similar a la de [[#BASIC|BASIC]], mostrada arriba. |
||
Line 883: | Line 883: | ||
=={{header|BBC BASIC}}== |
=={{header|BBC BASIC}}== |
||
The run counts are indicated by means of character codes in the range 131 to 255. |
The run counts are indicated by means of character codes in the range 131 to 255. |
||
< |
<syntaxhighlight lang="bbcbasic"> input$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
PRINT "Input: " input$ |
PRINT "Input: " input$ |
||
rle$ = FNencodeRLE(input$) |
rle$ = FNencodeRLE(input$) |
||
Line 918: | Line 918: | ||
ENDIF |
ENDIF |
||
ENDWHILE |
ENDWHILE |
||
= o$</ |
= o$</syntaxhighlight> |
||
=={{header|Befunge}}== |
=={{header|Befunge}}== |
||
Line 924: | Line 924: | ||
Pipe the output of the program-it's more reliable. |
Pipe the output of the program-it's more reliable. |
||
{{works with|CCBI|2.1}} |
{{works with|CCBI|2.1}} |
||
< |
<syntaxhighlight lang="befunge"> ~"y"- ~$ v |
||
<temp var for when char changes |
<temp var for when char changes |
||
format: |
format: |
||
Line 949: | Line 949: | ||
the validity of this program is NOT affected p- |
the validity of this program is NOT affected p- |
||
>^ |
>^ |
||
--written by Gamemanj,for Rosettacode</ |
--written by Gamemanj,for Rosettacode</syntaxhighlight> |
||
=={{header|Bracmat}}== |
=={{header|Bracmat}}== |
||
< |
<syntaxhighlight lang="bracmat"> ( run-length |
||
= character otherCharacter acc begin end |
= character otherCharacter acc begin end |
||
. :?acc |
. :?acc |
||
Line 973: | Line 973: | ||
) |
) |
||
& run-length$WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
& run-length$WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
</syntaxhighlight> |
|||
</lang> |
|||
<pre> 12W1B12W3B24W1B14W</pre> |
<pre> 12W1B12W3B24W1B14W</pre> |
||
=={{header|Burlesque}}== |
=={{header|Burlesque}}== |
||
< |
<syntaxhighlight lang="burlesque"> |
||
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
=[{^^[~\/L[Sh}\m |
=[{^^[~\/L[Sh}\m |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
Encoder that can deal with byte streams. Can encode/decode any byte values and any length with reasonable efficiency. Also showing OO and polymophism with structs. |
Encoder that can deal with byte streams. Can encode/decode any byte values and any length with reasonable efficiency. Also showing OO and polymophism with structs. |
||
< |
<syntaxhighlight lang="c">#include <stdio.h> |
||
#include <stdlib.h> |
#include <stdlib.h> |
||
Line 1,130: | Line 1,130: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
See [[Run-length encoding/C]] |
See [[Run-length encoding/C]] |
||
Line 1,137: | Line 1,137: | ||
=== Linq === |
=== Linq === |
||
<!--Martin Freedman 22/02/2018--> |
<!--Martin Freedman 22/02/2018--> |
||
< |
<syntaxhighlight lang="csharp">using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
using static System.Console; |
using static System.Console; |
||
Line 1,173: | Line 1,173: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 1,183: | Line 1,183: | ||
Many solutions do not follow the suggested output guideline in the challenge (not helped by its wording), instead producing a list of tuples or equivalent. This is much simpler (especially for decode) and the following provides an equivalent of those (IMHO deficient) solutions, to make comparisons easier. |
Many solutions do not follow the suggested output guideline in the challenge (not helped by its wording), instead producing a list of tuples or equivalent. This is much simpler (especially for decode) and the following provides an equivalent of those (IMHO deficient) solutions, to make comparisons easier. |
||
< |
<syntaxhighlight lang="csharp">using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
using static System.Console; |
using static System.Console; |
||
Line 1,212: | Line 1,212: | ||
string.Join(",", list.Select(t => $"[{t.i},{t.c}]")); |
string.Join(",", list.Select(t => $"[{t.i},{t.c}]")); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 1,221: | Line 1,221: | ||
Stringbuilder version. Might be more performant but mixes output formatting with encoding/decoding logic. |
Stringbuilder version. Might be more performant but mixes output formatting with encoding/decoding logic. |
||
<!--Martin Freedman 22/02/2018--> |
<!--Martin Freedman 22/02/2018--> |
||
< |
<syntaxhighlight lang="csharp">using System.Collections.Generic; |
||
using System.Linq; |
using System.Linq; |
||
using static System.Console; |
using static System.Console; |
||
Line 1,256: | Line 1,256: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>raw = WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 1,268: | Line 1,268: | ||
This example only works if there are no digits in the string to be encoded and then decoded. |
This example only works if there are no digits in the string to be encoded and then decoded. |
||
< |
<syntaxhighlight lang="csharp"> public static void Main(string[] args) |
||
{ |
{ |
||
string input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
string input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
||
Line 1,316: | Line 1,316: | ||
} |
} |
||
return sb.ToString(); |
return sb.ToString(); |
||
}</ |
}</syntaxhighlight> |
||
=== RegEx === |
=== RegEx === |
||
Somewhat shorter, using Regex.Replace with MatchEvaluator (using C#2 syntax only): |
Somewhat shorter, using Regex.Replace with MatchEvaluator (using C#2 syntax only): |
||
< |
<syntaxhighlight lang="csharp">using System; |
||
using System.Text.RegularExpressions; |
using System.Text.RegularExpressions; |
||
Line 1,356: | Line 1,356: | ||
}); |
}); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <algorithm> |
||
#include <array> |
#include <array> |
||
#include <iterator> |
#include <iterator> |
||
Line 1,520: | Line 1,520: | ||
std::cout.setf(std::cout.boolalpha); |
std::cout.setf(std::cout.boolalpha); |
||
std::cout << "Round trip works: " << (test_string == decoded_str) << '\n'; |
std::cout << "Round trip works: " << (test_string == decoded_str) << '\n'; |
||
}</ |
}</syntaxhighlight> |
||
{{libheader|boost}} |
{{libheader|boost}} |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <string> |
#include <string> |
||
#include <sstream> |
#include <sstream> |
||
Line 1,575: | Line 1,575: | ||
} |
} |
||
return oss.str( ) ; |
return oss.str( ) ; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Ceylon}}== |
=={{header|Ceylon}}== |
||
< |
<syntaxhighlight lang="ceylon">shared void run() { |
||
"Takes a string such as aaaabbbbbbcc and returns 4a6b2c" |
"Takes a string such as aaaabbbbbbcc and returns 4a6b2c" |
||
Line 1,608: | Line 1,608: | ||
assert (compress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") == "12W1B12W3B24W1B14W"); |
assert (compress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") == "12W1B12W3B24W1B14W"); |
||
assert (decompress("24a") == "aaaaaaaaaaaaaaaaaaaaaaaa"); |
assert (decompress("24a") == "aaaaaaaaaaaaaaaaaaaaaaaa"); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
< |
<syntaxhighlight lang="clojure">(defn compress [s] |
||
(->> (partition-by identity s) (mapcat (juxt count first)) (apply str))) |
(->> (partition-by identity s) (mapcat (juxt count first)) (apply str))) |
||
Line 1,617: | Line 1,617: | ||
(->> (re-seq #"(\d+)([A-Z])" s) |
(->> (re-seq #"(\d+)([A-Z])" s) |
||
(mapcat (fn [[_ n ch]] (repeat (Integer/parseInt n) ch))) |
(mapcat (fn [[_ n ch]] (repeat (Integer/parseInt n) ch))) |
||
(apply str)))</ |
(apply str)))</syntaxhighlight> |
||
=={{header|COBOL}}== |
=={{header|COBOL}}== |
||
{{works with|GNU Cobol|2.0}} |
{{works with|GNU Cobol|2.0}} |
||
< |
<syntaxhighlight lang="cobol"> >>SOURCE FREE |
||
IDENTIFICATION DIVISION. |
IDENTIFICATION DIVISION. |
||
PROGRAM-ID. run-length-encoding. |
PROGRAM-ID. run-length-encoding. |
||
Line 1,744: | Line 1,744: | ||
END-PERFORM |
END-PERFORM |
||
. |
. |
||
END FUNCTION decode.</ |
END FUNCTION decode.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,755: | Line 1,755: | ||
=={{header|CoffeeScript}}== |
=={{header|CoffeeScript}}== |
||
< |
<syntaxhighlight lang="coffeescript">encode = (str) -> |
||
str.replace /(.)\1*/g, (w) -> |
str.replace /(.)\1*/g, (w) -> |
||
w[0] + w.length |
w[0] + w.length |
||
Line 1,765: | Line 1,765: | ||
console.log s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
console.log s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
console.log encode s |
console.log encode s |
||
console.log decode encode s</ |
console.log decode encode s</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,775: | Line 1,775: | ||
The following version encodes the number of ocurrences as an unicode character. You can change the way it looks by rotating the offset. |
The following version encodes the number of ocurrences as an unicode character. You can change the way it looks by rotating the offset. |
||
< |
<syntaxhighlight lang="coffeescript">encode = (str, offset = 75) -> |
||
str.replace /(.)\1*/g, (w) -> |
str.replace /(.)\1*/g, (w) -> |
||
w[0] + String.fromCharCode(offset+w.length) |
w[0] + String.fromCharCode(offset+w.length) |
||
Line 1,782: | Line 1,782: | ||
str.split('').map((w,i) -> |
str.split('').map((w,i) -> |
||
if not (i%2) then w else new Array(+w.charCodeAt(0)-offset).join(str[i-1]) |
if not (i%2) then w else new Array(+w.charCodeAt(0)-offset).join(str[i-1]) |
||
).join('')</ |
).join('')</syntaxhighlight> |
||
<pre> |
<pre> |
||
Line 1,794: | Line 1,794: | ||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun group-similar (sequence &key (test 'eql)) |
||
(loop for x in (rest sequence) |
(loop for x in (rest sequence) |
||
with temp = (subseq sequence 0 1) |
with temp = (subseq sequence 0 1) |
||
Line 1,816: | Line 1,816: | ||
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
(run-length-encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
(run-length-decode '((#\W 12) (#\B 1) (#\W 12) (#\B 3) (#\W 24) (#\B 1)))</ |
(run-length-decode '((#\W 12) (#\B 1) (#\W 12) (#\B 3) (#\W 24) (#\B 1)))</syntaxhighlight> |
||
=={{header|D}}== |
=={{header|D}}== |
||
===Short Functional Version=== |
===Short Functional Version=== |
||
< |
<syntaxhighlight lang="d">import std.algorithm, std.array; |
||
alias encode = group; |
alias encode = group; |
||
Line 1,832: | Line 1,832: | ||
"WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
"WWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
||
assert(s.encode.decode.equal(s)); |
assert(s.encode.decode.equal(s)); |
||
}</ |
}</syntaxhighlight> |
||
===Basic Imperative Version=== |
===Basic Imperative Version=== |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.array, std.conv; |
||
// Similar to the 'look and say' function. |
// Similar to the 'look and say' function. |
||
Line 1,887: | Line 1,887: | ||
writeln("Encoded: ", encoded); |
writeln("Encoded: ", encoded); |
||
assert(txt == encoded.decode); |
assert(txt == encoded.decode); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 1,895: | Line 1,895: | ||
D's native string is utf-encoded. This version works for utf string, and uses a [[Variable-length_quantity|Variable-length Quantity]] [[Variable-length_quantity#D|module]]. |
D's native string is utf-encoded. This version works for utf string, and uses a [[Variable-length_quantity|Variable-length Quantity]] [[Variable-length_quantity#D|module]]. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.conv, std.utf, std.array; |
||
import vlq; |
import vlq; |
||
Line 1,973: | Line 1,973: | ||
auto sEncoded = RLE.init.encode(s).encoded ; |
auto sEncoded = RLE.init.encode(s).encoded ; |
||
assert(s == RLE(sEncoded).decode(), "Not work"); |
assert(s == RLE(sEncoded).decode(), "Not work"); |
||
}</ |
}</syntaxhighlight> |
||
output from "display.txt": |
output from "display.txt": |
||
Line 1,994: | Line 1,994: | ||
The code looks more complex than the third Python version because this also handles digits by escaping them with #. |
The code looks more complex than the third Python version because this also handles digits by escaping them with #. |
||
< |
<syntaxhighlight lang="d">import std.stdio, std.conv, std.array, std.regex, std.utf, |
||
std.algorithm; |
std.algorithm; |
||
Line 2,025: | Line 2,025: | ||
"11#222##333"; |
"11#222##333"; |
||
assert(s == reDecode(reEncode(s))); |
assert(s == reDecode(reEncode(s))); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Déjà Vu}}== |
=={{header|Déjà Vu}}== |
||
< |
<syntaxhighlight lang="dejavu">rle: |
||
if not dup: |
if not dup: |
||
drop |
drop |
||
Line 2,056: | Line 2,056: | ||
rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
!. dup |
!. dup |
||
!. rld</ |
!. rld</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[ & 12 "W" & 1 "B" & 12 "W" & 3 "B" & 24 "W" & 1 "B" & 14 "W" ] |
<pre>[ & 12 "W" & 1 "B" & 12 "W" & 3 "B" & 24 "W" & 1 "B" & 14 "W" ] |
||
Line 2,062: | Line 2,062: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.SysUtils}} |
{{libheader| System.SysUtils}} |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program RunLengthTest; |
program RunLengthTest; |
||
Line 2,158: | Line 2,158: | ||
writeln(Data.Decode); |
writeln(Data.Decode); |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,167: | Line 2,167: | ||
=={{header|E}}== |
=={{header|E}}== |
||
< |
<syntaxhighlight lang="e">def rle(string) { |
||
var seen := null |
var seen := null |
||
var count := 0 |
var count := 0 |
||
Line 2,194: | Line 2,194: | ||
} |
} |
||
return result |
return result |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="e">? rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
# value: [[12, 'W'], [1, 'B'], [12, 'W'], [3, 'B'], [24, 'W'], [1, 'B'], [14, 'W']] |
# value: [[12, 'W'], [1, 'B'], [12, 'W'], [3, 'B'], [24, 'W'], [1, 'B'], [14, 'W']] |
||
? unrle(rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")) |
? unrle(rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")) |
||
# value: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</ |
# value: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</syntaxhighlight> |
||
=={{header|Elena}}== |
=={{header|Elena}}== |
||
ELENA 4.x : |
ELENA 4.x : |
||
< |
<syntaxhighlight lang="elena">import system'text; |
||
import system'routines; |
import system'routines; |
||
import extensions; |
import extensions; |
||
Line 2,269: | Line 2,269: | ||
s := compressor.decompress(s); |
s := compressor.decompress(s); |
||
console.printLine(s) |
console.printLine(s) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,277: | Line 2,277: | ||
=={{header|Elixir}}== |
=={{header|Elixir}}== |
||
< |
<syntaxhighlight lang="elixir">defmodule Run_length do |
||
def encode(str) when is_bitstring(str) do |
def encode(str) when is_bitstring(str) do |
||
to_char_list(str) |> encode |> to_string |
to_char_list(str) |> encode |> to_string |
||
Line 2,303: | Line 2,303: | ||
|> Run_length.encode |> IO.inspect |
|> Run_length.encode |> IO.inspect |
||
|> Run_length.decode |> IO.inspect |
|> Run_length.decode |> IO.inspect |
||
end)</ |
end)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 2,317: | Line 2,317: | ||
=={{header|Emacs Lisp}}== |
=={{header|Emacs Lisp}}== |
||
< |
<syntaxhighlight lang="lisp">(defun run-length-encode (str) |
||
(let (output) |
(let (output) |
||
(with-temp-buffer |
(with-temp-buffer |
||
Line 2,326: | Line 2,326: | ||
(count (skip-chars-forward (string char)))) |
(count (skip-chars-forward (string char)))) |
||
(push (format "%d%c" count char) output)))) |
(push (format "%d%c" count char) output)))) |
||
(mapconcat #'identity (nreverse output) "")))</ |
(mapconcat #'identity (nreverse output) "")))</syntaxhighlight> |
||
{{libheader|seq.el}} |
{{libheader|seq.el}} |
||
< |
<syntaxhighlight lang="lisp">(require 'seq) |
||
(defun run-length-encode (str) |
(defun run-length-encode (str) |
||
Line 2,335: | Line 2,335: | ||
(apply #'concat (mapcar (lambda (items) |
(apply #'concat (mapcar (lambda (items) |
||
(format "%d%c" (length items) (car items))) |
(format "%d%c" (length items) (car items))) |
||
grouped))))</ |
grouped))))</syntaxhighlight> |
||
=={{header|Erlang}}== |
=={{header|Erlang}}== |
||
Line 2,341: | Line 2,341: | ||
A single-threaded/process version with a simple set of unit test. |
A single-threaded/process version with a simple set of unit test. |
||
< |
<syntaxhighlight lang="erlang">-module(rle). |
||
-export([encode/1,decode/1]). |
-export([encode/1,decode/1]). |
||
Line 2,386: | Line 2,386: | ||
?_assert(decode(Expected) =:= PreEncoded), |
?_assert(decode(Expected) =:= PreEncoded), |
||
?_assert(decode(encode(PreEncoded)) =:= PreEncoded) |
?_assert(decode(encode(PreEncoded)) =:= PreEncoded) |
||
].</ |
].</syntaxhighlight> |
||
A version that works on character lists: |
A version that works on character lists: |
||
< |
<syntaxhighlight lang="erlang"> |
||
-module(rle). |
-module(rle). |
||
Line 2,411: | Line 2,411: | ||
decode([{Count, Char}|T], Acc) -> |
decode([{Count, Char}|T], Acc) -> |
||
decode(T, [[Char || _ <- lists:seq(1, Count)]|Acc]). |
decode(T, [[Char || _ <- lists:seq(1, Count)]|Acc]). |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">include misc.e |
||
function encode(sequence s) |
function encode(sequence s) |
||
Line 2,451: | Line 2,451: | ||
pretty_print(1,s,{3}) |
pretty_print(1,s,{3}) |
||
puts(1,'\n') |
puts(1,'\n') |
||
puts(1,decode(s))</ |
puts(1,decode(s))</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,458: | Line 2,458: | ||
=={{header|F Sharp|F#}}== |
=={{header|F Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
open System |
open System |
||
open System.Text.RegularExpressions |
open System.Text.RegularExpressions |
||
Line 2,477: | Line 2,477: | ||
|> List.map (fun m -> Int32.Parse(m.Groups.[1].Value), m.Groups.[2].Value) |
|> List.map (fun m -> Int32.Parse(m.Groups.[1].Value), m.Groups.[2].Value) |
||
|> List.fold (fun acc (len, s) -> acc + String.replicate len s) "" |
|> List.fold (fun acc (len, s) -> acc + String.replicate len s) "" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
< |
<syntaxhighlight lang="factor">USING: io kernel literals math.parser math.ranges sequences |
||
sequences.extras sequences.repeating splitting.extras |
sequences.extras sequences.repeating splitting.extras |
||
splitting.monotonic strings ; |
splitting.monotonic strings ; |
||
Line 2,497: | Line 2,497: | ||
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
"12W1B12W3B24W1B14W" |
"12W1B12W3B24W1B14W" |
||
[ encode ] [ decode ] bi* [ print ] bi@</ |
[ encode ] [ decode ] bi* [ print ] bi@</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 2,505: | Line 2,505: | ||
=={{header|FALSE}}== |
=={{header|FALSE}}== |
||
< |
<syntaxhighlight lang="false">1^[^$~][$@$@=$[%%\1+\$0~]?~[@.,1\$]?%]#%\., {encode}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="false">[0[^$$'9>'0@>|~]['0-\10*+]#]n: |
||
[n;!$~][[\$][1-\$,]#%%]#%% {decode}</ |
[n;!$~][[\$][1-\$,]#%%]#%% {decode}</syntaxhighlight> |
||
=={{header|Fan}}== |
=={{header|Fan}}== |
||
<syntaxhighlight lang="fan">** |
|||
<lang Fan>** |
|||
** Generates a run-length encoding for a string |
** Generates a run-length encoding for a string |
||
** |
** |
||
Line 2,556: | Line 2,556: | ||
override Str toStr() { return "${count}${char.toChar}" } |
override Str toStr() { return "${count}${char.toChar}" } |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">variable a |
||
: n>a (.) tuck a @ swap move a +! ; |
: n>a (.) tuck a @ swap move a +! ; |
||
: >a a @ c! 1 a +! ; |
: >a a @ c! 1 a +! ; |
||
Line 2,573: | Line 2,573: | ||
i c@ digit? if 10 * i c@ [char] 0 - + else |
i c@ digit? if 10 * i c@ [char] 0 - + else |
||
a @ over i c@ fill a +! 0 then |
a @ over i c@ fill a +! 0 then |
||
loop drop a @ over - ;</ |
loop drop a @ over - ;</syntaxhighlight> |
||
Example: |
Example: |
||
< |
<syntaxhighlight lang="forth">s" WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
here 1000 + encode here 2000 + decode cr 3 spaces type |
here 1000 + encode here 2000 + decode cr 3 spaces type |
||
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</ |
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
{{works with|Fortran|95 and later}} |
{{works with|Fortran|95 and later}} |
||
< |
<syntaxhighlight lang="fortran">program RLE |
||
implicit none |
implicit none |
||
Line 2,641: | Line 2,641: | ||
end do |
end do |
||
end subroutine |
end subroutine |
||
end program</ |
end program</syntaxhighlight> |
||
Output: |
Output: |
||
Line 2,650: | Line 2,650: | ||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
Dim As String initial, encoded, decoded |
Dim As String initial, encoded, decoded |
||
Line 2,705: | Line 2,705: | ||
Print decoded |
Print decoded |
||
End |
End |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
La salida es similar a la de [[#BASIC|BASIC]], mostrada arriba. |
La salida es similar a la de [[#BASIC|BASIC]], mostrada arriba. |
||
Line 2,711: | Line 2,711: | ||
=={{header|Gambas}}== |
=={{header|Gambas}}== |
||
'''[https://gambas-playground.proko.eu/?gist=b30707043cb64effba91a2edc4d4be94 Click this link to run this code]''' |
'''[https://gambas-playground.proko.eu/?gist=b30707043cb64effba91a2edc4d4be94 Click this link to run this code]''' |
||
< |
<syntaxhighlight lang="gambas">Public Sub Main() |
||
Dim sString As String = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
Dim sString As String = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Dim siCount As Short = 1 |
Dim siCount As Short = 1 |
||
Line 2,733: | Line 2,733: | ||
Print sString & gb.NewLine & sHold.Join(", ") |
Print sString & gb.NewLine & sHold.Join(", ") |
||
End</ |
End</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,742: | Line 2,742: | ||
=={{header|Go}}== |
=={{header|Go}}== |
||
Decoder kind of necessary to demonstrate task requirement that I can recreate the input. |
Decoder kind of necessary to demonstrate task requirement that I can recreate the input. |
||
< |
<syntaxhighlight lang="go">package main |
||
import "fmt" |
import "fmt" |
||
Line 2,812: | Line 2,812: | ||
} |
} |
||
return string(d) |
return string(d) |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 2,822: | Line 2,822: | ||
=={{header|Groovy}}== |
=={{header|Groovy}}== |
||
< |
<syntaxhighlight lang="groovy">def rleEncode(text) { |
||
def encoded = new StringBuilder() |
def encoded = new StringBuilder() |
||
(text =~ /(([A-Z])\2*)/).each { matcher -> |
(text =~ /(([A-Z])\2*)/).each { matcher -> |
||
Line 2,836: | Line 2,836: | ||
} |
} |
||
decoded.toString() |
decoded.toString() |
||
}</ |
}</syntaxhighlight> |
||
Test code |
Test code |
||
< |
<syntaxhighlight lang="groovy">def text = 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
def rleEncoded = rleEncode(text) |
def rleEncoded = rleEncode(text) |
||
assert rleEncoded == '12W1B12W3B24W1B14W' |
assert rleEncoded == '12W1B12W3B24W1B14W' |
||
Line 2,844: | Line 2,844: | ||
println "Original Text: $text" |
println "Original Text: $text" |
||
println "Encoded Text: $rleEncoded"</ |
println "Encoded Text: $rleEncoded"</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Original Text: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>Original Text: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 2,851: | Line 2,851: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
===In terms of group=== |
===In terms of group=== |
||
< |
<syntaxhighlight lang="haskell">import Data.List (group) |
||
-- Datatypes |
-- Datatypes |
||
Line 2,872: | Line 2,872: | ||
encoded = rlencode input |
encoded = rlencode input |
||
decoded = rldecode encoded |
decoded = rldecode encoded |
||
putStrLn $ "Encoded: " <> show encoded <> "\nDecoded: " <> show decoded</ |
putStrLn $ "Encoded: " <> show encoded <> "\nDecoded: " <> show decoded</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>Encoded: [(12,'W'),(1,'B'),(12,'W'),(3,'B'),(24,'W'),(1,'B'),(14,'W')] |
<pre>Encoded: [(12,'W'),(1,'B'),(12,'W'),(3,'B'),(24,'W'),(1,'B'),(14,'W')] |
||
Line 2,878: | Line 2,878: | ||
Or: |
Or: |
||
< |
<syntaxhighlight lang="haskell">import Data.Char (isDigit) |
||
import Data.List (group, groupBy) |
import Data.List (group, groupBy) |
||
Line 2,903: | Line 2,903: | ||
decode = runLengthDecode encode |
decode = runLengthDecode encode |
||
mapM_ putStrLn [text, encode, decode] |
mapM_ putStrLn [text, encode, decode] |
||
putStrLn $ "test: text == decode => " <> show (text == decode)</ |
putStrLn $ "test: text == decode => " <> show (text == decode)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 2,911: | Line 2,911: | ||
===In terms of span=== |
===In terms of span=== |
||
< |
<syntaxhighlight lang="haskell">import Data.Char (isDigit) |
||
import Data.List (span) |
import Data.List (span) |
||
Line 2,935: | Line 2,935: | ||
src = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
src = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
encoded = encode src |
encoded = encode src |
||
decoded = decode encoded</ |
decoded = decode encoded</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>W12B1W12B3W24B1W14 |
<pre>W12B1W12B3W24B1W14 |
||
Line 2,942: | Line 2,942: | ||
===As a fold=== |
===As a fold=== |
||
< |
<syntaxhighlight lang="haskell">----------------------- RUN LENGTHS ---------------------- |
||
runLengths :: String -> [(Int, Char)] |
runLengths :: String -> [(Int, Char)] |
||
Line 2,967: | Line 2,967: | ||
showLengths :: [(Int, Char)] -> String |
showLengths :: [(Int, Char)] -> String |
||
showLengths [] = [] |
showLengths [] = [] |
||
showLengths ((n, c) : xs) = show n <> [c] <> showLengths xs</ |
showLengths ((n, c) : xs) = show n <> [c] <> showLengths xs</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>12W1B12W3B24W1B14W |
<pre>12W1B12W3B24W1B14W |
||
Line 2,973: | Line 2,973: | ||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
< |
<syntaxhighlight lang="icon">procedure main(arglist) |
||
s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
s := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Line 2,999: | Line 2,999: | ||
procedure Repl(n, c) |
procedure Repl(n, c) |
||
return repl(c,n) |
return repl(c,n) |
||
end</ |
end</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
Line 3,009: | Line 3,009: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solution:''' |
'''Solution:''' |
||
< |
<syntaxhighlight lang="j">rle=: ;@(<@(":@(#-.1:),{.);.1~ 1, 2 ~:/\ ]) |
||
rld=: ;@(-.@e.&'0123456789' <@({:#~1{.@,~".@}:);.2 ])</ |
rld=: ;@(-.@e.&'0123456789' <@({:#~1{.@,~".@}:);.2 ])</syntaxhighlight> |
||
'''Example:''' |
'''Example:''' |
||
< |
<syntaxhighlight lang="j"> rle 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
12W1B12W3B24W1B14W |
12W1B12W3B24W1B14W |
||
rld '12W1B12W3B24W1B14W' |
rld '12W1B12W3B24W1B14W' |
||
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</ |
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</syntaxhighlight> |
||
Note that this implementation fails for the empty case. Here's a version that fixes that: |
Note that this implementation fails for the empty case. Here's a version that fixes that: |
||
< |
<syntaxhighlight lang="j">rle=: ;@(<@(":@#,{.);.1~ 2 ~:/\ (a.{.@-.{.),])</syntaxhighlight> |
||
Other approaches include using <nowiki>rle ::(''"_)</nowiki> or <nowiki>rle^:(*@#)</nowiki> or equivalent variations on the original sentence. |
Other approaches include using <nowiki>rle ::(''"_)</nowiki> or <nowiki>rle^:(*@#)</nowiki> or equivalent variations on the original sentence. |
||
Line 3,029: | Line 3,029: | ||
A numeric approach, based on a discussion in the J forums (primarily [http://jsoftware.com/pipermail/programming/2015-June/042139.html Pascal Jasmin] and [http://jsoftware.com/pipermail/programming/2015-June/042141.html Marshall Lochbaum]): |
A numeric approach, based on a discussion in the J forums (primarily [http://jsoftware.com/pipermail/programming/2015-June/042139.html Pascal Jasmin] and [http://jsoftware.com/pipermail/programming/2015-June/042141.html Marshall Lochbaum]): |
||
< |
<syntaxhighlight lang="j"> torle=: (#, {.);.1~ 1,2 ~:/\ ] |
||
frle=: #/@|:</ |
frle=: #/@|:</syntaxhighlight> |
||
Task example: |
Task example: |
||
< |
<syntaxhighlight lang="j"> torle a.i.'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
12 87 |
12 87 |
||
1 66 |
1 66 |
||
Line 3,043: | Line 3,043: | ||
14 87 |
14 87 |
||
u: frle torle a.i.'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
u: frle torle a.i.'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</ |
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</syntaxhighlight> |
||
Note that this approach also fails on the empty case. |
Note that this approach also fails on the empty case. |
||
=={{header|Java}}== |
=={{header|Java}}== |
||
< |
<syntaxhighlight lang="java">import java.util.regex.Matcher; |
||
import java.util.regex.Pattern; |
import java.util.regex.Pattern; |
||
public class RunLengthEncoding { |
public class RunLengthEncoding { |
||
Line 3,085: | Line 3,085: | ||
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B")); |
System.out.println(decode("1W1B1W1B1W1B1W1B1W1B1W1B1W1B")); |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
Tests: |
Tests: |
||
{{libheader|JUnit}} |
{{libheader|JUnit}} |
||
< |
<syntaxhighlight lang="java">import static org.junit.Assert.assertEquals; |
||
import org.junit.Test; |
import org.junit.Test; |
||
Line 3,120: | Line 3,120: | ||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
===ES5=== |
===ES5=== |
||
Here's an encoding method that walks the input string character by character |
Here's an encoding method that walks the input string character by character |
||
< |
<syntaxhighlight lang="javascript">function encode(input) { |
||
var encoding = []; |
var encoding = []; |
||
var prev, count, i; |
var prev, count, i; |
||
Line 3,139: | Line 3,139: | ||
encoding.push([count, prev]); |
encoding.push([count, prev]); |
||
return encoding; |
return encoding; |
||
}</ |
}</syntaxhighlight> |
||
Here's an encoding method that uses a regular expression to grab the character runs ({{works with|JavaScript|1.6}} for the <code>forEach</code> method) |
Here's an encoding method that uses a regular expression to grab the character runs ({{works with|JavaScript|1.6}} for the <code>forEach</code> method) |
||
< |
<syntaxhighlight lang="javascript">function encode_re(input) { |
||
var encoding = []; |
var encoding = []; |
||
input.match(/(.)\1*/g).forEach(function(substr){ encoding.push([substr.length, substr[0]]) }); |
input.match(/(.)\1*/g).forEach(function(substr){ encoding.push([substr.length, substr[0]]) }); |
||
return encoding; |
return encoding; |
||
}</ |
}</syntaxhighlight> |
||
And to decode (see [[Repeating a string#JavaScript|Repeating a string]]) |
And to decode (see [[Repeating a string#JavaScript|Repeating a string]]) |
||
< |
<syntaxhighlight lang="javascript">function decode(encoded) { |
||
var output = ""; |
var output = ""; |
||
encoded.forEach(function(pair){ output += new Array(1+pair[0]).join(pair[1]) }) |
encoded.forEach(function(pair){ output += new Array(1+pair[0]).join(pair[1]) }) |
||
return output; |
return output; |
||
}</ |
}</syntaxhighlight> |
||
===ES6=== |
===ES6=== |
||
By defining a generic ''group'' function: |
By defining a generic ''group'' function: |
||
< |
<syntaxhighlight lang="javascript">(() => { |
||
'use strict'; |
'use strict'; |
||
Line 3,207: | Line 3,207: | ||
// MAIN --- |
// MAIN --- |
||
return main(); |
return main(); |
||
})();</ |
})();</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
<pre>From: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
<pre>From: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Line 3,214: | Line 3,214: | ||
A <code>.reduce()</code> based one-liner |
A <code>.reduce()</code> based one-liner |
||
< |
<syntaxhighlight lang="javascript"> |
||
const rlEncode = (s: string) => s.match(/(.)\1*/g).reduce((result,char) => result+char.length+char[0],"") |
const rlEncode = (s: string) => s.match(/(.)\1*/g).reduce((result,char) => result+char.length+char[0],"") |
||
const rlValidate = (s: string) => /^(\d+\D)+$/.test(s) |
const rlValidate = (s: string) => /^(\d+\D)+$/.test(s) |
||
const rlDecode = (s: string) => rlValidate(s) ? s.match(/(\d[a-z\s])\1*/ig).reduce((res,p) => res+p[p.length-1].repeat(parseInt(p)),"") : Error("Invalid rl") |
const rlDecode = (s: string) => rlValidate(s) ? s.match(/(\d[a-z\s])\1*/ig).reduce((res,p) => res+p[p.length-1].repeat(parseInt(p)),"") : Error("Invalid rl") |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|jq}}== |
=={{header|jq}}== |
||
Line 3,224: | Line 3,224: | ||
'''Utility function:''' |
'''Utility function:''' |
||
< |
<syntaxhighlight lang="jq">def runs: |
||
reduce .[] as $item |
reduce .[] as $item |
||
( []; |
( []; |
||
Line 3,232: | Line 3,232: | ||
else . + [[$item, 1]] |
else . + [[$item, 1]] |
||
end |
end |
||
end ) ;</ |
end ) ;</syntaxhighlight> |
||
'''Run-length encoding and decoding''': |
'''Run-length encoding and decoding''': |
||
< |
<syntaxhighlight lang="jq">def run_length_encode: |
||
explode | runs | reduce .[] as $x (""; . + "\($x[1])\([$x[0]]|implode)"); |
explode | runs | reduce .[] as $x (""; . + "\($x[1])\([$x[0]]|implode)"); |
||
Line 3,242: | Line 3,242: | ||
($pair[0:-1] | tonumber) as $n |
($pair[0:-1] | tonumber) as $n |
||
| $pair[-1:] as $letter |
| $pair[-1:] as $letter |
||
| . + ($n * $letter)) ;</ |
| . + ($n * $letter)) ;</syntaxhighlight> |
||
'''Example''': |
'''Example''': |
||
< |
<syntaxhighlight lang="jq">"ABBCCC" | run_length_encode | run_length_decode</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
< |
<syntaxhighlight lang="sh">$ jq -n -f Run_length_encoding.jq |
||
"ABBCCC"</ |
"ABBCCC"</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
{{works with|Julia|0.6}} |
{{works with|Julia|0.6}} |
||
< |
<syntaxhighlight lang="julia">using IterTools |
||
encode(str::String) = collect((length(g), first(g)) for g in groupby(first, str)) |
encode(str::String) = collect((length(g), first(g)) for g in groupby(first, str)) |
||
Line 3,261: | Line 3,261: | ||
decoded = decode(encoded) |
decoded = decode(encoded) |
||
println("Original: $original\n -> encoded: $encoded\n -> decoded: $decoded") |
println("Original: $original\n -> encoded: $encoded\n -> decoded: $decoded") |
||
end</ |
end</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,273: | Line 3,273: | ||
=={{header|K}}== |
=={{header|K}}== |
||
< |
<syntaxhighlight lang="k">rle: {,/($-':i,#x),'x@i:&1,~=':x}</syntaxhighlight> |
||
{{trans|J}} |
{{trans|J}} |
||
< |
<syntaxhighlight lang="k">rld: {d:"0123456789"; ,/(.(d," ")@d?/:x)#'x _dvl d}</syntaxhighlight> |
||
'''Example:''' |
'''Example:''' |
||
< |
<syntaxhighlight lang="k"> rle "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
"12W1B12W3B24W1B14W" |
"12W1B12W3B24W1B14W" |
||
rld "12W1B12W3B24W1B14W" |
rld "12W1B12W3B24W1B14W" |
||
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</ |
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</syntaxhighlight> |
||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
Tail recursive implementation of Run Length Encoding |
Tail recursive implementation of Run Length Encoding |
||
< |
<syntaxhighlight lang="scala">tailrec fun runLengthEncoding(text:String,prev:String=""):String { |
||
if (text.isEmpty()){ |
if (text.isEmpty()){ |
||
return prev |
return prev |
||
Line 3,301: | Line 3,301: | ||
assert(runLengthEncoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
assert(runLengthEncoding("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
== "12W1B12W3B24W1B14W") |
== "12W1B12W3B24W1B14W") |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Lasso}}== |
=={{header|Lasso}}== |
||
< |
<syntaxhighlight lang="lasso">define rle(str::string)::string => { |
||
local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string) |
local(orig = #str->values->asCopy,newi=array, newc=array, compiled=string) |
||
while(#orig->size) => { |
while(#orig->size) => { |
||
Line 3,350: | Line 3,350: | ||
rlde('12W1B12W3B24W1B14W') |
rlde('12W1B12W3B24W1B14W') |
||
rlde('1d1s1f1k1j2h1k1d1s1j1f1h1d1s1k1h1s1h1d2j1f2h1d1l1s2l1w')</ |
rlde('1d1s1f1k1j2h1k1d1s1j1f1h1d1s1k1h1s1h1d2j1f2h1d1l1s2l1w')</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,361: | Line 3,361: | ||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
< |
<syntaxhighlight lang="lb">mainwin 100 20 |
||
'In$ ="aaaaaaaaaaaaaaaaaccbbbbbbbbbbbbbbba" ' testing... |
'In$ ="aaaaaaaaaaaaaaaaaccbbbbbbbbbbbbbbba" ' testing... |
||
Line 3,408: | Line 3,408: | ||
next i |
next i |
||
Decoded$ =r$ |
Decoded$ =r$ |
||
end function</ |
end function</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
< |
<syntaxhighlight lang="livecode">function rlEncode str |
||
local charCount |
local charCount |
||
put 1 into charCount |
put 1 into charCount |
||
Line 3,453: | Line 3,453: | ||
end repeat |
end repeat |
||
return repStr |
return repStr |
||
end repeatString</ |
end repeatString</syntaxhighlight> |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to encode :str [:out "||] [:count 0] [:last first :str] |
||
if empty? :str [output (word :out :count :last)] |
if empty? :str [output (word :out :count :last)] |
||
if equal? first :str :last [output (encode bf :str :out :count+1 :last)] |
if equal? first :str :last [output (encode bf :str :out :count+1 :last)] |
||
Line 3,473: | Line 3,473: | ||
make "foo "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
make "foo "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
make "rle encode :foo |
make "rle encode :foo |
||
show equal? :foo decode :rle</ |
show equal? :foo decode :rle</syntaxhighlight> |
||
=={{header|Lua}}== |
=={{header|Lua}}== |
||
< |
<syntaxhighlight lang="lua">local C, Ct, R, Cf, Cc = lpeg.C, lpeg.Ct, lpeg.R, lpeg.Cf, lpeg.Cc |
||
astable = Ct(C(1)^0) |
astable = Ct(C(1)^0) |
||
Line 3,507: | Line 3,507: | ||
end |
end |
||
return ret |
return ret |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module RLE_example { |
Module RLE_example { |
||
inp$="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
inp$="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Line 3,544: | Line 3,544: | ||
} |
} |
||
RLE_example |
RLE_example |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 3,557: | Line 3,557: | ||
The function |
The function |
||
< |
<syntaxhighlight lang="mathematica">RunLengthEncode[input_String]:= (l |-> {First@l, Length@l}) /@ (Split@Characters@input)</syntaxhighlight> |
||
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 |
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 |
||
< |
<syntaxhighlight lang="mathematica">RunLengthDecode[input_List]:= ConstantArray @@@ input // Flatten // StringJoin</syntaxhighlight> |
||
recreates the string. |
recreates the string. |
||
Line 3,567: | Line 3,567: | ||
Example: For the string |
Example: For the string |
||
< |
<syntaxhighlight lang="mathematica">mystring="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";</syntaxhighlight> |
||
here is the run-length encoding: |
here is the run-length encoding: |
||
< |
<syntaxhighlight lang="mathematica">rle = RunLengthEncode[mystring] |
||
{{"W", 12}, {"B", 1}, {"W", 12}, {"B", 3}, {"W", 24}, {"B", 1}, {"W", 14}}</ |
{{"W", 12}, {"B", 1}, {"W", 12}, {"B", 3}, {"W", 24}, {"B", 1}, {"W", 14}}</syntaxhighlight> |
||
Check that the input string is recreated: |
Check that the input string is recreated: |
||
< |
<syntaxhighlight lang="mathematica">mystring == RunLengthDecode[rle] |
||
True</ |
True</syntaxhighlight> |
||
=={{header|Maxima}}== |
=={{header|Maxima}}== |
||
< |
<syntaxhighlight lang="maxima">rle(a) := block( |
||
[n: slength(a), b: "", c: charat(a, 1), k: 1], |
[n: slength(a), b: "", c: charat(a, 1), k: 1], |
||
for i from 2 thru n do |
for i from 2 thru n do |
||
Line 3,590: | Line 3,590: | ||
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); |
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); |
||
"12W1B12W3B24W1B14W"</ |
"12W1B12W3B24W1B14W"</syntaxhighlight> |
||
=={{header|MMIX}}== |
=={{header|MMIX}}== |
||
< |
<syntaxhighlight lang="mmix"> LOC Data_Segment |
||
GREG @ |
GREG @ |
||
Buf OCTA 0,0,0,0 integer print buffer |
Buf OCTA 0,0,0,0 integer print buffer |
||
Line 3,702: | Line 3,702: | ||
2H SET $4,#a print NL |
2H SET $4,#a print NL |
||
GO $127,PChar |
GO $127,PChar |
||
TRAP 0,Halt,0 EXIT</ |
TRAP 0,Halt,0 EXIT</syntaxhighlight> |
||
Example run encode --> decode: |
Example run encode --> decode: |
||
<pre>~/MIX/MMIX/Rosetta> mmix rle |
<pre>~/MIX/MMIX/Rosetta> mmix rle |
||
Line 3,710: | Line 3,710: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="nim">import parseutils, strutils |
||
proc compress(input: string): string = |
proc compress(input: string): string = |
||
Line 3,745: | Line 3,745: | ||
let compressed = Text.compress() |
let compressed = Text.compress() |
||
echo "Compressed: ", compressed |
echo "Compressed: ", compressed |
||
echo "Uncompressed: ", compressed.uncompress()</ |
echo "Uncompressed: ", compressed.uncompress()</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,753: | Line 3,753: | ||
=={{header|Objeck}}== |
=={{header|Objeck}}== |
||
< |
<syntaxhighlight lang="objeck">use RegEx; |
||
class RunLengthEncoding { |
class RunLengthEncoding { |
||
Line 3,804: | Line 3,804: | ||
return output; |
return output; |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
<pre>encoding: 12W1B12W3B24W1B14W |
<pre>encoding: 12W1B12W3B24W1B14W |
||
Line 3,814: | Line 3,814: | ||
=={{header|OCaml}}== |
=={{header|OCaml}}== |
||
< |
<syntaxhighlight lang="ocaml">let encode str = |
||
let len = String.length str in |
let len = String.length str in |
||
let rec aux i acc = |
let rec aux i acc = |
||
Line 3,836: | Line 3,836: | ||
let decode lst = |
let decode lst = |
||
let l = List.map (fun (c,n) -> String.make n c) lst in |
let l = List.map (fun (c,n) -> String.make n c) lst in |
||
(String.concat "" l)</ |
(String.concat "" l)</syntaxhighlight> |
||
< |
<syntaxhighlight lang="ocaml">let () = |
||
let e = encode "aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa" in |
let e = encode "aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa" in |
||
List.iter (fun (c,n) -> |
List.iter (fun (c,n) -> |
||
Line 3,844: | Line 3,844: | ||
) e; |
) e; |
||
print_endline (decode [('a', 5); ('h', 6); ('m', 7); ('u', 1); ('i', 7); ('a', 6)]); |
print_endline (decode [('a', 5); ('h', 6); ('m', 7); ('u', 1); ('i', 7); ('a', 6)]); |
||
;;</ |
;;</syntaxhighlight> |
||
;Using regular expressions |
;Using regular expressions |
||
< |
<syntaxhighlight lang="ocaml">#load "str.cma";; |
||
open Str |
open Str |
||
Line 3,863: | Line 3,863: | ||
let () = |
let () = |
||
print_endline (encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); |
print_endline (encode "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"); |
||
print_endline (decode "12W1B12W3B24W1B14W");</ |
print_endline (decode "12W1B12W3B24W1B14W");</syntaxhighlight> |
||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">: encode(s) |
||
StringBuffer new |
StringBuffer new |
||
s group apply(#[ tuck size asString << swap first <<c ]) ; |
s group apply(#[ tuck size asString << swap first <<c ]) ; |
||
Line 3,878: | Line 3,878: | ||
loop: i [ c <<c ] 0 |
loop: i [ c <<c ] 0 |
||
] |
] |
||
drop ;</ |
drop ;</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 3,891: | Line 3,891: | ||
=={{header|Ol}}== |
=={{header|Ol}}== |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define (RLE str) |
(define (RLE str) |
||
(define iter (string->list str)) |
(define iter (string->list str)) |
||
Line 3,906: | Line 3,906: | ||
(apply string-append (map (lambda (p) |
(apply string-append (map (lambda (p) |
||
(make-string (car p) (cdr p))) rle))) |
(make-string (car p) (cdr p))) rle))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Test: |
Test: |
||
< |
<syntaxhighlight lang="scheme"> |
||
(define str "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
(define str "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
(print str) |
(print str) |
||
Line 3,917: | Line 3,917: | ||
rle) |
rle) |
||
(print (decode rle)) |
(print (decode rle)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre> |
<pre> |
||
Line 3,931: | Line 3,931: | ||
</pre> |
</pre> |
||
=={{header|Oz}}== |
=={{header|Oz}}== |
||
< |
<syntaxhighlight lang="oz">declare |
||
fun {RLEncode Xs} |
fun {RLEncode Xs} |
||
for G in {Group Xs} collect:C do |
for G in {Group Xs} collect:C do |
||
Line 3,967: | Line 3,967: | ||
{System.showInfo Data} |
{System.showInfo Data} |
||
{Show Enc} |
{Show Enc} |
||
{System.showInfo {RLDecode Enc}}</ |
{System.showInfo {RLDecode Enc}}</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
< |
<syntaxhighlight lang="parigp">rle(s)={ |
||
if(s=="", return(s)); |
if(s=="", return(s)); |
||
my(v=Vec(s),cur=v[1],ct=1,out=""); |
my(v=Vec(s),cur=v[1],ct=1,out=""); |
||
Line 4,000: | Line 4,000: | ||
}; |
}; |
||
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
elr(%)</ |
elr(%)</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>%1 = "12W1B12W3B24W1B14W" |
<pre>%1 = "12W1B12W3B24W1B14W" |
||
Line 4,007: | Line 4,007: | ||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
< |
<syntaxhighlight lang="pascal">Program RunLengthEncoding(output); |
||
procedure encode(s: string; var counts: array of integer; var letters: string); |
procedure encode(s: string; var counts: array of integer; var letters: string); |
||
Line 4,057: | Line 4,057: | ||
decode(s, counts, letters); |
decode(s, counts, letters); |
||
writeln(s); |
writeln(s); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>:> ./RunLengthEncoding |
<pre>:> ./RunLengthEncoding |
||
Line 4,069: | Line 4,069: | ||
Simple version using ASCII numerals as length markers, like the example in the task description (won't work correctly on input strings that already contain digits): |
Simple version using ASCII numerals as length markers, like the example in the task description (won't work correctly on input strings that already contain digits): |
||
< |
<syntaxhighlight lang="perl">sub encode { |
||
shift =~ s/(.)\1*/length($&).$1/grse; |
shift =~ s/(.)\1*/length($&).$1/grse; |
||
} |
} |
||
Line 4,075: | Line 4,075: | ||
sub decode { |
sub decode { |
||
shift =~ s/(\d+)(.)/$2 x $1/grse; |
shift =~ s/(\d+)(.)/$2 x $1/grse; |
||
}</ |
}</syntaxhighlight> |
||
Modified version that can take arbitrary byte strings as input (produces encoded byte strings that are compatible with the [[#C|C solution]]): |
Modified version that can take arbitrary byte strings as input (produces encoded byte strings that are compatible with the [[#C|C solution]]): |
||
< |
<syntaxhighlight lang="perl">sub encode { |
||
shift =~ s/(.)\1{0,254}/pack("C", length($&)).$1/grse; |
shift =~ s/(.)\1{0,254}/pack("C", length($&)).$1/grse; |
||
} |
} |
||
Line 4,085: | Line 4,085: | ||
sub decode { |
sub decode { |
||
shift =~ s/(.)(.)/$2 x unpack("C", $1)/grse; |
shift =~ s/(.)(.)/$2 x unpack("C", $1)/grse; |
||
}</ |
}</syntaxhighlight> |
||
Further modified version that supports compact representation of longer non-repeating substrings, just like the [[#C|C solution]] (so should be fully compatible with that solution for both encoding and decoding): |
Further modified version that supports compact representation of longer non-repeating substrings, just like the [[#C|C solution]] (so should be fully compatible with that solution for both encoding and decoding): |
||
< |
<syntaxhighlight lang="perl">sub encode { |
||
my $str = shift; |
my $str = shift; |
||
my $ret = ""; |
my $ret = ""; |
||
Line 4,120: | Line 4,120: | ||
} |
} |
||
return $ret; |
return $ret; |
||
}</ |
}</syntaxhighlight> |
||
Demonstration of the third version: |
Demonstration of the third version: |
||
< |
<syntaxhighlight lang="perl">use Data::Dump qw(dd); |
||
dd my $str = "XXXXXABCDEFGHIoooooooooooooooooooooooooAAAAAA"; |
dd my $str = "XXXXXABCDEFGHIoooooooooooooooooooooooooAAAAAA"; |
||
dd my $enc = encode($str); |
dd my $enc = encode($str); |
||
dd decode($enc);</ |
dd decode($enc);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,138: | Line 4,138: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
Based on [[Run-length_encoding#Euphoria|Euphoria]], but uses a few string in place of sequence. |
Based on [[Run-length_encoding#Euphoria|Euphoria]], but uses a few string in place of sequence. |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span> |
||
<span style="color: #008080;">function</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #008080;">function</span> <span style="color: #000000;">encode</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
Line 4,170: | Line 4,170: | ||
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> |
<span style="color: #0000FF;">?</span><span style="color: #000000;">s</span> |
||
<span style="color: #0000FF;">?</span><span style="color: #000000;">decode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
<span style="color: #0000FF;">?</span><span style="color: #000000;">decode</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
Note the character hints are desktop/Phix only and don't appear under p2js. |
Note the character hints are desktop/Phix only and don't appear under p2js. |
||
Line 4,179: | Line 4,179: | ||
=={{header|PHP}}== |
=={{header|PHP}}== |
||
< |
<syntaxhighlight lang="php"><?php |
||
function encode($str) |
function encode($str) |
||
{ |
{ |
||
Line 4,196: | Line 4,196: | ||
echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL; |
echo encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'), PHP_EOL; |
||
echo decode('12W1B12W3B24W1B14W'), PHP_EOL; |
echo decode('12W1B12W3B24W1B14W'), PHP_EOL; |
||
?></ |
?></syntaxhighlight> |
||
=={{header|Picat}}== |
=={{header|Picat}}== |
||
===While loop=== |
===While loop=== |
||
Quite slow. |
Quite slow. |
||
< |
<syntaxhighlight lang="picat">rle(S) = RLE => |
||
RLE = "", |
RLE = "", |
||
Char = S[1], |
Char = S[1], |
||
Line 4,216: | Line 4,216: | ||
I := I + 1 |
I := I + 1 |
||
end, |
end, |
||
RLE := RLE ++ Count.to_string() ++ Char.to_string().</ |
RLE := RLE ++ Count.to_string() ++ Char.to_string().</syntaxhighlight> |
||
===Using positions of different chars=== |
===Using positions of different chars=== |
||
Much faster than <code>rle/1</code>. |
Much faster than <code>rle/1</code>. |
||
< |
<syntaxhighlight lang="picat">rle2(S) = RLE => |
||
Ix = [1] ++ [I : I in 2..S.len, S[I] != S[I-1]] ++ [S.len+1], |
Ix = [1] ++ [I : I in 2..S.len, S[I] != S[I-1]] ++ [S.len+1], |
||
Diffs = diff(Ix), |
Diffs = diff(Ix), |
||
RLE = [Diffs[I].to_string() ++ S[Ix[I]].to_string() : I in 1..Diffs.len].join('').</ |
RLE = [Diffs[I].to_string() ++ S[Ix[I]].to_string() : I in 1..Diffs.len].join('').</syntaxhighlight> |
||
===Recursive approach=== |
===Recursive approach=== |
||
The fastest version. |
The fastest version. |
||
< |
<syntaxhighlight lang="picat">rle3(S) = RLE => |
||
rle3(S.tail(),S[1],1,[],RLE). |
rle3(S.tail(),S[1],1,[],RLE). |
||
Line 4,237: | Line 4,237: | ||
rle3(T,C,Count+1,RLE1,RLE) |
rle3(T,C,Count+1,RLE1,RLE) |
||
; |
; |
||
rle3(T,C,1,RLE1++[Count.to_string()++LastChar.to_string()],RLE).</ |
rle3(T,C,1,RLE1++[Count.to_string()++LastChar.to_string()],RLE).</syntaxhighlight> |
||
===Test=== |
===Test=== |
||
Encode and decode (only using <code>rle3/1</code>): |
Encode and decode (only using <code>rle3/1</code>): |
||
< |
<syntaxhighlight lang="picat">go => |
||
S = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWA", |
S = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWWA", |
||
println(S), |
println(S), |
||
Line 4,253: | Line 4,253: | ||
println(not_ok) |
println(not_ok) |
||
end, |
end, |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,263: | Line 4,263: | ||
===Benchmark on larger string=== |
===Benchmark on larger string=== |
||
A benchmark on a larger string (30_000) clearly shows that rle3/1 is the fastest. |
A benchmark on a larger string (30_000) clearly shows that rle3/1 is the fastest. |
||
< |
<syntaxhighlight lang="picat">go2 => |
||
_ = random2(), |
_ = random2(), |
||
Alpha = "AB", |
Alpha = "AB", |
||
Line 4,276: | Line 4,276: | ||
println("rle3/1:"), |
println("rle3/1:"), |
||
time(_=rle3(S)), |
time(_=rle3(S)), |
||
nl.</ |
nl.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,292: | Line 4,292: | ||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de encode (Str) |
||
(pack |
(pack |
||
(make |
(make |
||
Line 4,314: | Line 4,314: | ||
(prinl "Data: " "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
(prinl "Data: " "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW") |
||
(prinl "Encoded: " (encode @)) |
(prinl "Encoded: " (encode @)) |
||
(prinl "Decoded: " (decode @)) )</ |
(prinl "Decoded: " (decode @)) )</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>Data: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>Data: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 4,321: | Line 4,321: | ||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli">declare (c1, c2) character (1); |
||
declare run_length fixed binary; |
declare run_length fixed binary; |
||
declare input file; |
declare input file; |
||
Line 4,358: | Line 4,358: | ||
end; |
end; |
||
put edit ((c do i = 1 to run_length)) (a); |
put edit ((c do i = 1 to run_length)) (a); |
||
end;</ |
end;</syntaxhighlight> |
||
=={{header|PowerBASIC}}== |
=={{header|PowerBASIC}}== |
||
Line 4,364: | Line 4,364: | ||
This version can handle any arbitrary string that doesn't contain numbers (not just letters). (A flag value could be added which would allow the inclusion of ''any'' character, but such a flag isn't in this example.) |
This version can handle any arbitrary string that doesn't contain numbers (not just letters). (A flag value could be added which would allow the inclusion of ''any'' character, but such a flag isn't in this example.) |
||
< |
<syntaxhighlight lang="powerbasic">FUNCTION RLDecode (i AS STRING) AS STRING |
||
DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING |
DIM Loop0 AS LONG, rCount AS STRING, outP AS STRING, m AS STRING |
||
Line 4,415: | Line 4,415: | ||
'in PB/Win, "?" = MSGBOX; in PB/DOS & PB/CC. "?" = PRINT |
'in PB/Win, "?" = MSGBOX; in PB/DOS & PB/CC. "?" = PRINT |
||
? initial & $CRLF & encoded & $CRLF & decoded |
? initial & $CRLF & encoded & $CRLF & decoded |
||
END FUNCTION</ |
END FUNCTION</syntaxhighlight> |
||
Outputs are similar to those in [[#BASIC|BASIC]], above. |
Outputs are similar to those in [[#BASIC|BASIC]], above. |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
< |
<syntaxhighlight lang="powershell">function Compress-RLE ($s) { |
||
$re = [regex] '(.)\1*' |
$re = [regex] '(.)\1*' |
||
$ret = "" |
$ret = "" |
||
Line 4,437: | Line 4,437: | ||
} |
} |
||
return $ret |
return $ret |
||
}</ |
}</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>PS> Compress-RLE "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
<pre>PS> Compress-RLE "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Line 4,447: | Line 4,447: | ||
Works with SWI-Prolog.<br> |
Works with SWI-Prolog.<br> |
||
This code is inspired from a code found here : http://groups.google.com/group/comp.lang.prolog/browse_thread/thread/b053ea2512e8b350 (author : Pascal J. Bourguignon). |
This code is inspired from a code found here : http://groups.google.com/group/comp.lang.prolog/browse_thread/thread/b053ea2512e8b350 (author : Pascal J. Bourguignon). |
||
< |
<syntaxhighlight lang="prolog">% the test |
||
run_length :- |
run_length :- |
||
L = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", |
L = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW", |
||
Line 4,554: | Line 4,554: | ||
run(Var,[Other|RRest], [1,Var],[Other|RRest]):- |
run(Var,[Other|RRest], [1,Var],[Other|RRest]):- |
||
dif(Var,Other).</ |
dif(Var,Other).</syntaxhighlight> |
||
Output : |
Output : |
||
<pre> ?- run_length. |
<pre> ?- run_length. |
||
Line 4,566: | Line 4,566: | ||
=={{header|Pure}}== |
=={{header|Pure}}== |
||
< |
<syntaxhighlight lang="pure">using system; |
||
encode s = strcat $ map (sprintf "%d%s") $ encode $ chars s with |
encode s = strcat $ map (sprintf "%d%s") $ encode $ chars s with |
||
Line 4,580: | Line 4,580: | ||
let s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
let s = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
||
let r = encode s; // "12W1B12W3B24W1B14W" |
let r = encode s; // "12W1B12W3B24W1B14W" |
||
decode r;</ |
decode r;</syntaxhighlight> |
||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
{{trans|PowerBasic}} with some optimations to use pointers instead of string functions. According to the task description it works with uppercase A - Z. In this implementation it also functions with all characters that are non-digits and whose value is non-zero. |
{{trans|PowerBasic}} with some optimations to use pointers instead of string functions. According to the task description it works with uppercase A - Z. In this implementation it also functions with all characters that are non-digits and whose value is non-zero. |
||
< |
<syntaxhighlight lang="purebasic">Procedure.s RLDecode(toDecode.s) |
||
Protected.s repCount, output, currChar, tmp |
Protected.s repCount, output, currChar, tmp |
||
Protected *c.Character = @toDecode |
Protected *c.Character = @toDecode |
||
Line 4,649: | Line 4,649: | ||
Input() |
Input() |
||
CloseConsole() |
CloseConsole() |
||
EndIf</ |
EndIf</syntaxhighlight> |
||
Sample output: |
Sample output: |
||
<pre>Type something: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWW |
<pre>Type something: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWW |
||
Line 4,658: | Line 4,658: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">def encode(input_string): |
||
count = 1 |
count = 1 |
||
prev = None |
prev = None |
||
Line 4,690: | Line 4,690: | ||
if value[1] == 0: |
if value[1] == 0: |
||
print("Encoded value is {}".format(value[0])) |
print("Encoded value is {}".format(value[0])) |
||
decode(value[0])</ |
decode(value[0])</syntaxhighlight> |
||
Functional |
Functional |
||
{{works with|Python|2.4}} |
{{works with|Python|2.4}} |
||
< |
<syntaxhighlight lang="python">from itertools import groupby |
||
def encode(input_string): |
def encode(input_string): |
||
return [(len(list(g)), k) for k,g in groupby(input_string)] |
return [(len(list(g)), k) for k,g in groupby(input_string)] |
||
Line 4,702: | Line 4,702: | ||
encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa") |
encode("aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa") |
||
decode([(5, 'a'), (6, 'h'), (7, 'm'), (1, 'u'), (7, 'i'), (6, 'a')])</ |
decode([(5, 'a'), (6, 'h'), (7, 'm'), (1, 'u'), (7, 'i'), (6, 'a')])</syntaxhighlight> |
||
<br>'''By regular expression'''<br> |
<br>'''By regular expression'''<br> |
||
The simplified input range of only uppercase characters allows a simple regular expression to be applied repeatedly for encoding, and another for decoding: |
The simplified input range of only uppercase characters allows a simple regular expression to be applied repeatedly for encoding, and another for decoding: |
||
< |
<syntaxhighlight lang="python">from re import sub |
||
def encode(text): |
def encode(text): |
||
Line 4,727: | Line 4,727: | ||
textin = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
textin = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
assert decode(encode(textin)) == textin</ |
assert decode(encode(textin)) == textin</syntaxhighlight> |
||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
Line 4,733: | Line 4,733: | ||
<code>lookandsay</code> is defined at [[Look-and-say sequence#Quackery]]. |
<code>lookandsay</code> is defined at [[Look-and-say sequence#Quackery]]. |
||
< |
<syntaxhighlight lang="quackery"> [ lookandsay ] is encode ( $ --> $ ) |
||
[ $ "" 0 rot |
[ $ "" 0 rot |
||
Line 4,752: | Line 4,752: | ||
dup echo$ cr |
dup echo$ cr |
||
decode |
decode |
||
echo$ cr</ |
echo$ cr</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 4,763: | Line 4,763: | ||
=={{header|R}}== |
=={{header|R}}== |
||
R has a built-in function, rle, for run length encoding. This modification allows input and output in the forms specified above. |
R has a built-in function, rle, for run length encoding. This modification allows input and output in the forms specified above. |
||
< |
<syntaxhighlight lang="rsplus">runlengthencoding <- function(x) |
||
{ |
{ |
||
splitx <- unlist(strsplit(input, "")) |
splitx <- unlist(strsplit(input, "")) |
||
Line 4,771: | Line 4,771: | ||
input <- "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
input <- "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
runlengthencoding(input)</ |
runlengthencoding(input)</syntaxhighlight> |
||
Similarly, inverse.rle provides decompression after a run length encoding. |
Similarly, inverse.rle provides decompression after a run length encoding. |
||
< |
<syntaxhighlight lang="rsplus">inverserunlengthencoding <- function(x) |
||
{ |
{ |
||
lengths <- as.numeric(unlist(strsplit(output, "[[:alpha:]]"))) |
lengths <- as.numeric(unlist(strsplit(output, "[[:alpha:]]"))) |
||
Line 4,783: | Line 4,783: | ||
output <- "12W1B12W3B24W1B14W" |
output <- "12W1B12W3B24W1B14W" |
||
inverserunlengthencoding(output)</ |
inverserunlengthencoding(output)</syntaxhighlight> |
||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
(define (encode str) |
(define (encode str) |
||
Line 4,793: | Line 4,793: | ||
(define (decode str) |
(define (decode str) |
||
(regexp-replace* #px"([0-9]+)(.)" str (λ (m n c) (make-string (string->number n) (string-ref c 0))))) |
(regexp-replace* #px"([0-9]+)(.)" str (λ (m n c) (make-string (string->number n) (string-ref c 0))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
Line 4,800: | Line 4,800: | ||
count from 0, not from 1. |
count from 0, not from 1. |
||
<lang |
<syntaxhighlight lang="raku" line>sub encode($str) { $str.subst(/(.) $0*/, { $/.chars ~ $0 }, :g) } |
||
sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) } |
sub decode($str) { $str.subst(/(\d+) (.)/, { $1 x $0 }, :g) } |
||
Line 4,806: | Line 4,806: | ||
my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'); |
my $e = encode('WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'); |
||
say $e; |
say $e; |
||
say decode($e);</ |
say decode($e);</syntaxhighlight> |
||
Output: |
Output: |
||
Line 4,823: | Line 4,823: | ||
Note that this REXX version (for encoding and decoding) uses a ''replication'' count, not the ''count'' of characters, |
Note that this REXX version (for encoding and decoding) uses a ''replication'' count, not the ''count'' of characters, |
||
<br>so a replication count of '''11''' represents a count of '''12''' characters. |
<br>so a replication count of '''11''' represents a count of '''12''' characters. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program encodes and displays a string by using a run─length encoding scheme. */ |
||
parse arg input . /*normally, input would be in a file. */ |
parse arg input . /*normally, input would be in a file. */ |
||
default= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
default= 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
Line 4,860: | Line 4,860: | ||
$= $ || copies( substr(x, k, 1), n) /*N: is now the number of characters. */ |
$= $ || copies( substr(x, k, 1), n) /*N: is now the number of characters. */ |
||
j= j + # + 1 /*increment the DO loop index by D+1. */ |
j= j + # + 1 /*increment the DO loop index by D+1. */ |
||
end /*j*/; return $ /*return the decoded string to caller. */</ |
end /*j*/; return $ /*return the decoded string to caller. */</syntaxhighlight> |
||
{{out|output|text= when using the default input:}} |
{{out|output|text= when using the default input:}} |
||
<pre> |
<pre> |
||
Line 4,869: | Line 4,869: | ||
===version 2=== |
===version 2=== |
||
< |
<syntaxhighlight lang="rexx"> |
||
/*REXX*/ |
/*REXX*/ |
||
s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
Line 4,909: | Line 4,909: | ||
o: ol=ol||arg(1) |
o: ol=ol||arg(1) |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> s=WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre> s=WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 4,918: | Line 4,918: | ||
===version 3=== |
===version 3=== |
||
No need to output counts that are 1 |
No need to output counts that are 1 |
||
< |
<syntaxhighlight lang="rexx"> |
||
/*REXX*/ |
/*REXX*/ |
||
s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
s='WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
Line 4,967: | Line 4,967: | ||
o: ol=ol||arg(1) |
o: ol=ol||arg(1) |
||
Return</ |
Return</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> s=WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre> s=WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 4,975: | Line 4,975: | ||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
# Project : Run-length encoding |
# Project : Run-length encoding |
||
Line 5,003: | Line 5,003: | ||
see dec |
see dec |
||
next |
next |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,016: | Line 5,016: | ||
Ruby has built-in run-length encoding in the form of <code>chunk</code>, here I provide a thin wrapper around it: |
Ruby has built-in run-length encoding in the form of <code>chunk</code>, here I provide a thin wrapper around it: |
||
< |
<syntaxhighlight lang="ruby"> |
||
# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]] |
# run_encode("aaabbbbc") #=> [["a", 3], ["b", 4], ["c", 1]] |
||
def run_encode(string) |
def run_encode(string) |
||
Line 5,032: | Line 5,032: | ||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="ruby">def encode(string) |
||
string.scan(/(.)(\1*)/).collect do |char, repeat| |
string.scan(/(.)(\1*)/).collect do |char, repeat| |
||
[1 + repeat.length, char] |
[1 + repeat.length, char] |
||
Line 5,042: | Line 5,042: | ||
def decode(string) |
def decode(string) |
||
string.scan(/(\d+)(\D)/).collect {|length, char| char * length.to_i}.join |
string.scan(/(\d+)(\D)/).collect {|length, char| char * length.to_i}.join |
||
end</ |
end</syntaxhighlight> |
||
This usage also seems to be idiomatic, and perhaps less cryptic: |
This usage also seems to be idiomatic, and perhaps less cryptic: |
||
< |
<syntaxhighlight lang="ruby">def encode(string) |
||
string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)| |
string.scan(/(.)(\1*)/).inject("") do |encoding, (char, repeat)| |
||
encoding << (1 + repeat.length).to_s << char |
encoding << (1 + repeat.length).to_s << char |
||
Line 5,055: | Line 5,055: | ||
decoding << char * length.to_i |
decoding << char * length.to_i |
||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
<br>'''By regular expression'''<br> |
<br>'''By regular expression'''<br> |
||
The simplified input range of only uppercase characters allows a simple regular expression to be applied repeatedly for encoding, and another for decoding: |
The simplified input range of only uppercase characters allows a simple regular expression to be applied repeatedly for encoding, and another for decoding: |
||
< |
<syntaxhighlight lang="ruby">def encode(str) |
||
str.gsub(/(.)\1*/) {$&.length.to_s + $1} |
str.gsub(/(.)\1*/) {$&.length.to_s + $1} |
||
end |
end |
||
Line 5,065: | Line 5,065: | ||
def decode(str) |
def decode(str) |
||
str.gsub(/(\d+)(\D)/) {$2 * $1.to_i} |
str.gsub(/(\d+)(\D)/) {$2 * $1.to_i} |
||
end</ |
end</syntaxhighlight> |
||
'''Test:''' |
'''Test:''' |
||
< |
<syntaxhighlight lang="ruby">orig = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
p enc = encode(orig) |
p enc = encode(orig) |
||
p dec = decode(enc) |
p dec = decode(enc) |
||
puts "success!" if dec == orig</ |
puts "success!" if dec == orig</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 5,081: | Line 5,081: | ||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">string$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
beg = 1 |
beg = 1 |
||
i = 1 |
i = 1 |
||
Line 5,106: | Line 5,106: | ||
beg = i |
beg = i |
||
if i < len(press$) then goto [expand] |
if i < len(press$) then goto [expand] |
||
print " Expanded:";expand$</ |
print " Expanded:";expand$</syntaxhighlight>Output: |
||
<pre>Compressed:12W1B12W3B24W1B14W |
<pre>Compressed:12W1B12W3B24W1B14W |
||
Expanded:WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</pre> |
Expanded:WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</pre> |
||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
< |
<syntaxhighlight lang="rust">fn encode(s: &str) -> String { |
||
s.chars() |
s.chars() |
||
// wrap all values in Option::Some |
// wrap all values in Option::Some |
||
Line 5,166: | Line 5,166: | ||
assert_eq!(text, decoded); |
assert_eq!(text, decoded); |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>original: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
<pre>original: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW |
||
Line 5,176: | Line 5,176: | ||
Care is taken to use StringBuilder for performance reasons. |
Care is taken to use StringBuilder for performance reasons. |
||
< |
<syntaxhighlight lang="scala">def encode(s: String) = (1 until s.size).foldLeft((1, s(0), new StringBuilder)) { |
||
case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb) |
case ((len, c, sb), index) if c != s(index) => sb.append(len); sb.append(c); (1, s(index), sb) |
||
case ((len, c, sb), _) => (len + 1, c, sb) |
case ((len, c, sb), _) => (len + 1, c, sb) |
||
Line 5,188: | Line 5,188: | ||
for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt) |
for (Code(len, c) <- Code findAllIn s) sb.append(c * len.toInt) |
||
sb.toString |
sb.toString |
||
}</ |
}</syntaxhighlight> |
||
A simpler (?) encoder: |
A simpler (?) encoder: |
||
< |
<syntaxhighlight lang="scala">def encode(s:String) = { |
||
s.foldLeft((0,s(0),""))( (t,c) => t match {case (i,p,s) => if (p==c) (i+1,p,s) else (1,c,s+i+p)}) |
s.foldLeft((0,s(0),""))( (t,c) => t match {case (i,p,s) => if (p==c) (i+1,p,s) else (1,c,s+i+p)}) |
||
match {case (i,p,s) => s+i+p} |
match {case (i,p,s) => s+i+p} |
||
}</ |
}</syntaxhighlight> |
||
To make it faster (it's also faster than the longer implementation above) just replace '''""''' with '''new StringBuilder''' and '''s+i+p''' with '''{s.append(i);s.append(p)}''' |
To make it faster (it's also faster than the longer implementation above) just replace '''""''' with '''new StringBuilder''' and '''s+i+p''' with '''{s.append(i);s.append(p)}''' |
||
A simpler (?) decoder (that can handle a string like "2AB", producing "AAB"): |
A simpler (?) decoder (that can handle a string like "2AB", producing "AAB"): |
||
< |
<syntaxhighlight lang="scala">def decode(s: String, Code: scala.util.matching.Regex = """(\d+)?([a-zA-Z])""".r) = |
||
Code.findAllIn(s).foldLeft("") { case (acc, Code(len, c)) => |
Code.findAllIn(s).foldLeft("") { case (acc, Code(len, c)) => |
||
acc + c * Option(len).map(_.toInt).getOrElse(1) |
acc + c * Option(len).map(_.toInt).getOrElse(1) |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scheme}}== |
=={{header|Scheme}}== |
||
< |
<syntaxhighlight lang="scheme">(define (run-length-decode v) |
||
(apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v))) |
(apply string-append (map (lambda (p) (make-string (car p) (cdr p))) v))) |
||
Line 5,219: | Line 5,219: | ||
; ((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W)) |
; ((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W)) |
||
(run-length-decode '((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W))) |
(run-length-decode '((12 . #\W) (1 . #\B) (12 . #\W) (3 . #\B) (24 . #\W) (1 . #\B) (14 . #\W))) |
||
; "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</ |
; "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</syntaxhighlight> |
||
=={{header|sed}}== |
=={{header|sed}}== |
||
The encode script: |
The encode script: |
||
< |
<syntaxhighlight lang="sed"> |
||
/^$/ b |
/^$/ b |
||
:start |
:start |
||
Line 5,250: | Line 5,250: | ||
s/^([0-9]+.)(.*)/\2\1/ |
s/^([0-9]+.)(.*)/\2\1/ |
||
b start |
b start |
||
</syntaxhighlight> |
|||
</lang> |
|||
The decode script: |
The decode script: |
||
< |
<syntaxhighlight lang="sed"> |
||
/^$/ b |
/^$/ b |
||
:start |
:start |
||
Line 5,275: | Line 5,275: | ||
s/^0+// |
s/^0+// |
||
b loop } |
b loop } |
||
</syntaxhighlight> |
|||
</lang> |
|||
Example (assuming the scripts reside in the files <code>encode.sed</code> and <code>decode.sed</code>): |
Example (assuming the scripts reside in the files <code>encode.sed</code> and <code>decode.sed</code>): |
||
< |
<syntaxhighlight lang="bash"> |
||
sed -rf encode.sed <<< "foo oops" |
sed -rf encode.sed <<< "foo oops" |
||
# 1f2o1 2o1p1s |
# 1f2o1 2o1p1s |
||
Line 5,287: | Line 5,287: | ||
(sed -rf decode.sed | sed -rf encode.sed) <<< 1000. |
(sed -rf decode.sed | sed -rf encode.sed) <<< 1000. |
||
# 1000. |
# 1000. |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "scanstri.s7i"; |
include "scanstri.s7i"; |
||
Line 5,325: | Line 5,325: | ||
writeln(letterRleEncode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); |
writeln(letterRleEncode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW")); |
||
writeln(letterRleDecode("12W1B12W3B24W1B14W")); |
writeln(letterRleDecode("12W1B12W3B24W1B14W")); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
First solution: |
First solution: |
||
< |
<syntaxhighlight lang="ruby">func encode(str) { |
||
str.gsub(/((.)(\2*))/, {|a,b| "#{a.len}#{b}" }); |
str.gsub(/((.)(\2*))/, {|a,b| "#{a.len}#{b}" }); |
||
} |
} |
||
Line 5,335: | Line 5,335: | ||
func decode(str) { |
func decode(str) { |
||
str.gsub(/(\d+)(.)/, {|a,b| b * a.to_i }); |
str.gsub(/(\d+)(.)/, {|a,b| b * a.to_i }); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>12W1B12W3B24W1B14W</pre> |
<pre>12W1B12W3B24W1B14W</pre> |
||
Second solution, encoding the length into a byte: |
Second solution, encoding the length into a byte: |
||
< |
<syntaxhighlight lang="ruby">func encode(str) { |
||
str.gsub(/(.)(\1{0,254})/, {|a,b| b.len+1 -> chr + a}); |
str.gsub(/(.)(\1{0,254})/, {|a,b| b.len+1 -> chr + a}); |
||
} |
} |
||
Line 5,351: | Line 5,351: | ||
} |
} |
||
return r; |
return r; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>"\fW\1B\fW\3B\30W\1B\16W"</pre> |
<pre>"\fW\1B\fW\3B\30W\1B\16W"</pre> |
||
Line 5,361: | Line 5,361: | ||
{{works with|Smalltalk/X}} (and others) |
{{works with|Smalltalk/X}} (and others) |
||
< |
<syntaxhighlight lang="smalltalk">|compress decompress| |
||
compress := [:string | |
compress := [:string | |
||
String streamContents:[:out | |
String streamContents:[:out | |
||
Line 5,394: | Line 5,394: | ||
] |
] |
||
]. |
]. |
||
].</ |
].</syntaxhighlight> |
||
< |
<syntaxhighlight lang="smalltalk">compress value:'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW' |
||
-> '12W1B12W3B24W1B14W' |
-> '12W1B12W3B24W1B14W' |
||
decompress value:'12W1B12W3B24W1B14W' |
decompress value:'12W1B12W3B24W1B14W' |
||
-> 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'</ |
-> 'WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW'</syntaxhighlight> |
||
Most Smalltalk dialects include a class named "RunArray", which can be used as: |
Most Smalltalk dialects include a class named "RunArray", which can be used as: |
||
{{works with|Smalltalk/X}} |
{{works with|Smalltalk/X}} |
||
{{works with|VisualWorks}} |
{{works with|VisualWorks}} |
||
< |
<syntaxhighlight lang="smalltalk">compress := [:string | |
||
String streamContents:[:out | |
String streamContents:[:out | |
||
string asRunArray runsDo:[:count :char | |
string asRunArray runsDo:[:count :char | |
||
count printOn:out. out nextPut:char]]].</ |
count printOn:out. out nextPut:char]]].</syntaxhighlight> |
||
=={{header|SNOBOL4}}== |
=={{header|SNOBOL4}}== |
||
Line 5,416: | Line 5,416: | ||
{{works with|CSnobol}} |
{{works with|CSnobol}} |
||
< |
<syntaxhighlight lang="snobol4">* # Encode RLE |
||
define('rle(str)c,n') :(rle_end) |
define('rle(str)c,n') :(rle_end) |
||
rle str len(1) . c :f(return) |
rle str len(1) . c :f(return) |
||
Line 5,434: | Line 5,434: | ||
str = rle(str); output = str |
str = rle(str); output = str |
||
str = elr(str); output = str |
str = elr(str); output = str |
||
end</ |
end</syntaxhighlight> |
||
Output: |
Output: |
||
Line 5,445: | Line 5,445: | ||
<br> |
<br> |
||
* RLE encoding |
* RLE encoding |
||
<syntaxhighlight lang="sql"> |
|||
<lang SQL> |
|||
-- variable table |
-- variable table |
||
drop table if exists var; |
drop table if exists var; |
||
Line 5,493: | Line 5,493: | ||
where noWithinGroup = 1 |
where noWithinGroup = 1 |
||
) Rle_Compressed |
) Rle_Compressed |
||
</syntaxhighlight> |
|||
</lang> |
|||
* RLE decoding |
* RLE decoding |
||
<syntaxhighlight lang="sql"> |
|||
<lang SQL> |
|||
-- variable table |
-- variable table |
||
DROP TABLE IF EXISTS var; |
DROP TABLE IF EXISTS var; |
||
Line 5,559: | Line 5,559: | ||
string_agg(replicated_Letter, '' ORDER BY group_no) decoded_string |
string_agg(replicated_Letter, '' ORDER BY group_no) decoded_string |
||
FROM lettersReplicated |
FROM lettersReplicated |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Standard ML}}== |
=={{header|Standard ML}}== |
||
< |
<syntaxhighlight lang="sml">fun encode str = |
||
let |
let |
||
fun aux (sub, acc) = |
fun aux (sub, acc) = |
||
Line 5,578: | Line 5,578: | ||
fun decode lst = |
fun decode lst = |
||
concat (map (fn (c,n) => implode (List.tabulate (n, fn _ => c))) lst)</ |
concat (map (fn (c,n) => implode (List.tabulate (n, fn _ => c))) lst)</syntaxhighlight> |
||
Example: |
Example: |
||
<pre> |
<pre> |
||
Line 5,590: | Line 5,590: | ||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
Using array as the internal representation of the encoded input: |
Using array as the internal representation of the encoded input: |
||
< |
<syntaxhighlight lang="swift">import Foundation |
||
// "WWWBWW" -> [(3, W), (1, B), (2, W)] |
// "WWWBWW" -> [(3, W), (1, B), (2, W)] |
||
Line 5,604: | Line 5,604: | ||
return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) } |
return encoded.reduce("") { $0 + String(count: $1.0, repeatedValue: $1.1) } |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
'''Usage:''' |
'''Usage:''' |
||
< |
<syntaxhighlight lang="swift"> |
||
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
let input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
let output = decode(encode(input)) |
let output = decode(encode(input)) |
||
print(output == input) |
print(output == input) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 5,620: | Line 5,620: | ||
Converting encoded array into the string and then decoding it using NSScanner: |
Converting encoded array into the string and then decoding it using NSScanner: |
||
< |
<syntaxhighlight lang="swift">// "3W1B2W" -> "WWWBWW" |
||
func decode(encoded: String) -> String { |
func decode(encoded: String) -> String { |
||
let scanner = NSScanner(string: encoded) |
let scanner = NSScanner(string: encoded) |
||
Line 5,635: | Line 5,635: | ||
return out |
return out |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
< |
<syntaxhighlight lang="swift">let encodedString = encode(input).reduce("") { $0 + "\($1.0)\($1.1)" } |
||
print(encodedString) |
print(encodedString) |
||
let outputString = decode(encodedString) |
let outputString = decode(encodedString) |
||
print(outputString == input) |
print(outputString == input) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
Line 5,651: | Line 5,651: | ||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
The encoding is an even-length list with elements <tt>{count char ...}</tt> |
The encoding is an even-length list with elements <tt>{count char ...}</tt> |
||
< |
<syntaxhighlight lang="tcl">proc encode {string} { |
||
set encoding {} |
set encoding {} |
||
# use a regular expression to match runs of one character |
# use a regular expression to match runs of one character |
||
Line 5,665: | Line 5,665: | ||
} |
} |
||
return $decoded |
return $decoded |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="tcl">set str "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
set enc [encode $str] ;# ==> {12 W 1 B 12 W 3 B 24 W 1 B 14 W} |
set enc [encode $str] ;# ==> {12 W 1 B 12 W 3 B 24 W 1 B 14 W} |
||
set dec [decode $enc] |
set dec [decode $enc] |
||
if {$str eq $dec} { |
if {$str eq $dec} { |
||
puts "success" |
puts "success" |
||
}</ |
}</syntaxhighlight> |
||
=={{header|TMG}}== |
=={{header|TMG}}== |
||
Line 5,678: | Line 5,678: | ||
Encoding: |
Encoding: |
||
< |
<syntaxhighlight lang="unixtmg">loop: ordcop [lch?]\loop; |
||
ordcop: ord/copy; |
ordcop: ord/copy; |
||
ord: char(ch)/last [ch!=lch?]\new [cnt++] fail; |
ord: char(ch)/last [ch!=lch?]\new [cnt++] fail; |
||
Line 5,688: | Line 5,688: | ||
ch: 0; |
ch: 0; |
||
lch: 0; |
lch: 0; |
||
cnt: 0;</ |
cnt: 0;</syntaxhighlight> |
||
Decoding: |
Decoding: |
||
< |
<syntaxhighlight lang="unixtmg">loop: readint(n) copy\loop; |
||
copy: smark any(!<<>>) |
copy: smark any(!<<>>) |
||
repeat: [n?] parse(( scopy )) [--n>0?]\repeat; |
repeat: [n?] parse(( scopy )) [--n>0?]\repeat; |
||
Line 5,701: | Line 5,701: | ||
i: 0; |
i: 0; |
||
n: 0;</ |
n: 0;</syntaxhighlight> |
||
=={{header|TSE SAL}}== |
=={{header|TSE SAL}}== |
||
<syntaxhighlight lang="tsesal"> |
|||
<lang TSESAL> |
|||
STRING PROC FNStringGetDecodeStringCharacterEqualCountS( STRING inS ) |
STRING PROC FNStringGetDecodeStringCharacterEqualCountS( STRING inS ) |
||
STRING s1[255] = "" |
STRING s1[255] = "" |
||
Line 5,767: | Line 5,767: | ||
Warn( "equal strings if result is 1", ",", " ", "and the result is", ":", " ", s1 == s2 ) |
Warn( "equal strings if result is 1", ",", " ", "and the result is", ":", " ", s1 == s2 ) |
||
END |
END |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|TUSCRIPT}}== |
=={{header|TUSCRIPT}}== |
||
< |
<syntaxhighlight lang="tuscript"> |
||
$$ MODE TUSCRIPT,{} |
$$ MODE TUSCRIPT,{} |
||
input="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",output="" |
input="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",output="" |
||
Line 5,780: | Line 5,780: | ||
PRINT input |
PRINT input |
||
PRINT output |
PRINT output |
||
</syntaxhighlight> |
|||
</lang> |
|||
Output: |
Output: |
||
<pre> |
<pre> |
||
Line 5,789: | Line 5,789: | ||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|bash}} |
{{works with|bash}} |
||
< |
<syntaxhighlight lang="bash">encode() { |
||
local phrase=$1 |
local phrase=$1 |
||
[[ -z $phrase ]] && return |
[[ -z $phrase ]] && return |
||
Line 5,833: | Line 5,833: | ||
# replace spaces with the char |
# replace spaces with the char |
||
echo "${result// /$char}" |
echo "${result// /$char}" |
||
}</ |
}</syntaxhighlight> |
||
Demo |
Demo |
||
< |
<syntaxhighlight lang="bash">str="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
enc=$(encode "$str") |
enc=$(encode "$str") |
||
dec=$(decode "$enc") |
dec=$(decode "$enc") |
||
declare -p str enc dec |
declare -p str enc dec |
||
[[ $str == "$dec" ]] && echo success || echo failure</ |
[[ $str == "$dec" ]] && echo success || echo failure</syntaxhighlight> |
||
Output |
Output |
||
<pre>declare -- str="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
<pre>declare -- str="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" |
||
Line 5,850: | Line 5,850: | ||
which is a second order function taking a binary predicate that decides |
which is a second order function taking a binary predicate that decides |
||
when consecutive items of an input list belong to the same run. |
when consecutive items of an input list belong to the same run. |
||
< |
<syntaxhighlight lang="ursala">#import std |
||
#import nat |
#import nat |
||
Line 5,865: | Line 5,865: | ||
< |
< |
||
encode test_data, |
encode test_data, |
||
decode encode test_data></ |
decode encode test_data></syntaxhighlight> |
||
The output shows an encoding of the test data, and a decoding of the encoding, which |
The output shows an encoding of the test data, and a decoding of the encoding, which |
||
matches the original test data. |
matches the original test data. |
||
Line 5,872: | Line 5,872: | ||
=={{header|VBA}}== |
=={{header|VBA}}== |
||
<syntaxhighlight lang="vb"> |
|||
<lang vb> |
|||
Option Explicit |
Option Explicit |
||
Line 5,909: | Line 5,909: | ||
Next |
Next |
||
length_decoding = a |
length_decoding = a |
||
End Function</ |
End Function</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>12W1B12W3B24W1B14W |
<pre>12W1B12W3B24W1B14W |
||
Line 5,920: | Line 5,920: | ||
Newlines are not converted (the regular expression does not count newlines). |
Newlines are not converted (the regular expression does not count newlines). |
||
This methods supports any type of input. |
This methods supports any type of input. |
||
< |
<syntaxhighlight lang="vedit">:RL_ENCODE: |
||
BOF |
BOF |
||
While (!At_EOF) { |
While (!At_EOF) { |
||
Line 5,950: | Line 5,950: | ||
} |
} |
||
} |
} |
||
Return</ |
Return</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-pattern}} |
{{libheader|Wren-pattern}} |
||
< |
<syntaxhighlight lang="ecmascript">import "/pattern" for Pattern |
||
var p = Pattern.new("/u") // match any upper case letter |
var p = Pattern.new("/u") // match any upper case letter |
||
Line 5,998: | Line 5,998: | ||
System.print("Original = decoded : %(s == d)\n") |
System.print("Original = decoded : %(s == d)\n") |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
Line 6,019: | Line 6,019: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
string 0; \use zero-terminated strings, instead of MSb terminated |
string 0; \use zero-terminated strings, instead of MSb terminated |
||
Line 6,059: | Line 6,059: | ||
CrLf(0); |
CrLf(0); |
||
Expand("W11BW11B2W23BW13"); CrLf(0); |
Expand("W11BW11B2W23BW13"); CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
Output (with slightly better compression than the example): |
Output (with slightly better compression than the example): |
||
Line 6,069: | Line 6,069: | ||
=={{header|zkl}}== |
=={{header|zkl}}== |
||
A byte stream to byte stream codec, the streams hard coded for ease. Character '\1' is used as a sentinel and there are limits on the run length to avoid byte overflow. |
A byte stream to byte stream codec, the streams hard coded for ease. Character '\1' is used as a sentinel and there are limits on the run length to avoid byte overflow. |
||
< |
<syntaxhighlight lang="zkl">const MAX_LEN=250, MIN_LEN=3; |
||
fcn compress(text){ // !empty byte/text stream -->Data (byte stream) |
fcn compress(text){ // !empty byte/text stream -->Data (byte stream) |
||
sink:=Data(); cnt:=Ref(0); |
sink:=Data(); cnt:=Ref(0); |
||
Line 6,086: | Line 6,086: | ||
},text[0]) : write(_,cnt.value); |
},text[0]) : write(_,cnt.value); |
||
sink; |
sink; |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">fcn inflate(data){ //-->String |
||
data.howza(3).pump(String, |
data.howza(3).pump(String, |
||
fcn(c){ // if c==1, read n,c2 and expand, else write c |
fcn(c){ // if c==1, read n,c2 and expand, else write c |
||
if(c=="\x01") return(Void.Read,2) else return(Void.Write,c) }, |
if(c=="\x01") return(Void.Read,2) else return(Void.Write,c) }, |
||
fcn(_,n,c){ c*n.toAsc() }) |
fcn(_,n,c){ c*n.toAsc() }) |
||
}</ |
}</syntaxhighlight> |
||
< |
<syntaxhighlight lang="zkl">text:="WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"; |
||
d:=compress(text); |
d:=compress(text); |
||
d.bytes().println(); |
d.bytes().println(); |
||
println(text.len()," bytes --> ",d.len()," bytes"); |
println(text.len()," bytes --> ",d.len()," bytes"); |
||
println(text==inflate(d));</ |
println(text==inflate(d));</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |