Run-length encoding: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(26 intermediate revisions by 9 users not shown)
Line 383:
Encode input: 12W1B12W3B24W1B14W
Decode output: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</pre>
 
=={{header|Amazing Hopper}}==
<syntaxhighlight lang="c">
/*
TASK BASIC-EMBEBIDO de HOPPER
 
onechar("WB",objetivo)
deja un único carcater de todos los que encuentre consecutivamente,
de la lista de caracteres "WB".
índice:=()
copia el valor de la función entre paréntesis en "índice", pero
deja ese valor en el stack de trabajo, para ser asignado a "largo".
poschar(INICIO, v, objetivo)
entrega la posición donde el caracter dado "v" deja de repetirse
(por eso se resta 1 al resultado).
objetivo+=sublargo
borra los primeros sublargo-ésimo caracteres.
#basic{...} / #(...)
BASIC embebido de Hopper.
*/
 
#include <basico.h>
 
#define INICIO 1
#proto codificar(_X_,_Y_,_Z_)
#proto decodificar(_X_,_Y_)
 
principal {
índice="", largo=0, codificado="", decodificado=""
objetivo = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
 
decimales '0', fijar separador 'NULO'
#basic{
largo = len(índice:=( onechar("WB",objetivo) ) )
print ("Original =",objetivo,NL)
 
codificado = codificar(objetivo, índice, largo)
decodificado = decodificar(codificado, índice)
print ("Codificado =",codificado,"\nDecodificado =",decodificado,NL)
}
terminar
}
 
subrutinas
 
codificar( o, i, l)
v="", sublargo=0
para cada caracter ( v, i, l )
/* deja ésto en el stack de trabajo: */
#( sublargo := (poschar(INICIO, v, o) - 1 ) ), 'v'
o+=sublargo
siguiente
unir esto
retornar
 
decodificar(c, i)
v="", posición=0, l=0
#( l=len(i) )
para cada caracter ( v, i, l )
#basic{
posición = find(v, c)-1
/* deja ésto en el stack de trabajo: */
replicate(v, number(copy(posición,1,c)) )
}
++posición,c+=posición
siguiente
unir esto
retornar
 
</syntaxhighlight>
{{out}}
<pre>
Original =WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Codificado =12W1B12W3B24W1B14W
Decodificado =WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
 
</pre>
 
Line 797 ⟶ 881:
111r
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
==={{header|Applesoft BASIC}}===
 
<syntaxhighlight lang="basic"> 10 I$ = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
20 GOSUB 100ENCODE
30 GOSUB 200DECODE
40 PRINT "INPUT: ";I$
50 PRINT "OUTPUT: ";
60 GOSUB 250 PRINT
70 END
100 O$ = MID$ (I$,1,1):N$ = MID$ ( CHR$ (0),1, LEN (O$)): IF LEN (I$) < 2 THEN RETURN
110 FOR I = 2 TO LEN (I$):C$ = MID$ (I$,I,1): IF C$ < > RIGHT$ (O$,1) THEN O$ = O$ + C$:N$ = N$ + CHR$ (0): NEXT I: RETURN
120 N$ = MID$ (N$,1, LEN (O$) - 1) + CHR$ ( ASC ( MID$ (N$, LEN (O$))) + 1): NEXT I: RETURN
200 I$ = "": IF LEN (O$) THEN FOR I = 1 TO LEN (O$): FOR J = 0 TO ASC ( MID$ (N$,I)):I$ = I$ + MID$ (O$,I,1): NEXT J,I
210 RETURN
250 IF LEN (O$) THEN FOR I = 1 TO LEN (O$): PRINT ASC ( MID$ (N$,I)) + 1; MID$ (O$,I,1);: NEXT I
260 RETURN
</syntaxhighlight>
{{out}}
<pre>INPUT: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
OUTPUT: 12W1B12W3B24W1B14W</pre>
 
=={{header|BASIC256}}==
Line 2,201 ⟶ 2,305:
? unrle(rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"))
# value: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"</syntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="easylang">
func$ rlenc in$ .
for c$ in strchars in$
if c$ = c0$
cnt += 1
else
if cnt > 0
out$ &= cnt & c0$ & " "
.
c0$ = c$
cnt = 1
.
.
out$ &= cnt & c0$
return out$
.
func$ rldec in$ .
for h$ in strsplit in$ " "
c$ = substr h$ len h$ 1
for i to number h$
out$ &= c$
.
.
return out$
.
s$ = input
print s$
s$ = rlenc s$
print s$
s$ = rldec s$
print s$
#
input_data
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
 
</syntaxhighlight>
 
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">import system'text;
import system'routines;
Line 2,216 ⟶ 2,359:
int count := 0;
char current := s[0];
s.forEach::(ch)
{
if (ch == current)
Line 2,240 ⟶ 2,383:
char current := $0;
var a := new StringWriter();
s.forEach::(ch)
{
current := ch;
Line 2,708 ⟶ 2,851:
{{out}}
La salida es similar a la de [[#BASIC|BASIC]], mostrada arriba.
 
=={{header|FutureBasic}}==
This gives RLE encoding for strings and RLE decoding for strings and arrays, e.g., for [[Conway's_Game_of_Life|Conway's Game of Life]]
<syntaxhighlight lang=FutureBasic>
 
local fn encode( string as CFStringRef) as CFStringRef
CFStringRef ch, s, t
Short i, rl
s = @"" // Initalize the output string
for i = 0 to len( string ) - 1 // Encode string char by char
ch = mid( string, i, 1) // Read character at index
rl = 1 // Start run-length counter
while fn StringIsEqual( mid( string, i + rl, 1), ch )
rl ++ // Same char, so increase counter
wend
if rl == 1 then t = @"" else t = fn StringWithFormat( @"%d", rl ) // Counter as string, don't encode 1's
t = fn StringByAppendingString( t, ch ) // Add character
s = fn StringByAppendingString( s, t ) // Add to already encoded string
i += rl - 1 // Move index
next
print s
end fn
 
 
local fn decode( string as CFStringRef )
CFStringRef ch, s, t // character, outputstring, temporary string
Short i, rl // index, run length
s = @"" // Initalize the output string
for i = 0 to len( string ) - 1 // Decode input string char by char
ch = mid( string, i, 1 ) // Read character at index
if intval( ch ) == 0 // Not a digit
rl = 1
else
rl = intval( mid( string, i ) ) // Read run-length
i += fix( log10( rl ) + 1 ) // Move index past digits
ch = mid( string, i, 1 ) // Read character after run length
end if
t = fn StringByPaddingToLength( ch, rl, ch, 0 ) // Assemble temp string
s = fn StringByAppendingString( s, t ) // Add to decoded string
next
print s
end fn
 
 
local fn decode2D( string as CFStringRef ) // For Conway's Game of Life objects
Boolean a(500, 500) // Or larger to hold bigger life forms
CFStringRef ch
Short i, j, rl, f // Decoded char
Short v = 0, w = 0, x = 0, y = 0 // Temp width, max width, array coordinates
for i = 0 to len( string ) - 2 // Final char is always !
ch = mid( string, i, 1 )
if intval( ch ) == 0
rl = 1
else
rl = intval( mid( string, i ) )
i += fix( log10( rl ) + 1 )
ch = mid( string, i, 1 )
end if
select ch // Decode character as:
case @"$" : f = -1 // - new line
case @"b" : f = 0 // - dead
case @"o" : f = 1 // - live
case else : // Ignore
end select
for j = 1 to rl // Fill array with run of chars
if f = -1
x = 0 : y ++ : v = 0 // New line
else
a(x, y) = f
x ++ : v ++ : if v > w then w = v
end if
next
next
for j = 0 to y : for i = 0 to w - 1
print a(i, j);
next : print : next
end fn
 
fn decode( @"12W1B12W3B24W1B14W" ) // Assignment
fn encode( @"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" )
fn decode2D( @"bo$2bo$3o!" ) // Glider
 
handleevents // Join Mac event loop
 
</syntaxhighlight>
Output:
<pre>
 
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
12WB12W3B24WB14W
011
001
111
 
</pre>
 
=={{header|Gambas}}==
Line 3,625 ⟶ 3,863:
 
=={{header|Maxima}}==
To encode
<syntaxhighlight lang="maxima">rle(a) := block(
[n: slength(a), b: "", c: charat(a, 1), k: 1],
Line 3,631 ⟶ 3,870:
sconcat(b, k, c)
)$
</syntaxhighlight>
To decode
<syntaxhighlight lang="maxima">
 
/* Function to return a list where all but the last entries are integers */
intbucket(lst):=block(bucket:[],while integerp(first(lst)) do (push(first(lst),bucket),lst:rest(lst)),lst:append(reverse(bucket),[first(lst)]));
 
/* Run-length decoding */
rld(string_list):=block(
coref:map(eval_string,charlist(string_list)),
listcharact:sublist(coref,lambda([x],integerp(x)=false)),
map(intbucket,append([coref],makelist(coref:rest(coref,length(intbucket(coref))),length(listcharact)-1))),
makelist(sublist(%%[i],integerp),i,1,length(%%)),
map(eval_string,makelist(apply(concat,%%[i]),i,1,length(%%))),
makelist(smake(%%[i],string(listcharact[i])),i,1,length(listcharact)),
apply(concat,%%));
</syntaxhighlight>
 
Output
<syntaxhighlight lang="maxima">
rle("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW");
"12W1B12W3B24W1B14W"</syntaxhighlight>
rld(%);
/* "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" */
</syntaxhighlight>
 
=={{header|MMIX}}==
Line 5,051 ⟶ 5,312:
12W1B12W3B24W1B14W
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</pre>
 
=={{header|RPL}}==
≪ DUP 1 DUP SUB → in c
≪ "" 1
2 in SIZE '''FOR''' j
in j DUP SUB
'''IF''' DUP c == '''THEN''' DROP 1 +
'''ELSE'''
ROT ROT
→STR + c +
SWAP 'c' STO 1
'''END'''
'''NEXT'''
→STR + c +
≫ ≫ ‘<span style="color:blue">RLENC</span>’ STO
≪ → in
≪ "" 0
1 in SIZE '''FOR''' j
in j DUP SUB
'''IF''' DUP "A" ≥ '''THEN'''
ROT 1 4 ROLL '''START''' OVER + '''NEXT'''
SWAP DROP 0
'''ELSE''' STR→ SWAP 10 * + '''END'''
'''NEXT''' DROP
≫ ≫ ‘<span style="color:blue">RLDEC</span>’ STO
 
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW" <span style="color:blue">RLENC</span> DUP <span style="color:blue">RLDEC</span>
{{out}}
<pre>
2: "12W1B12W3B24W1B14W"
1: "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
</pre>
 
Line 5,369 ⟶ 5,663:
writeln(letterRleDecode("12W1B12W3B24W1B14W"));
end func;</syntaxhighlight>
 
=={{header|SETL}}==
<syntaxhighlight lang="setl">program rle;
test := "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
 
print("Input:");
print(test);
print("Encoded:");
print(enc := rlencode(test));
print("Decoded:");
print(rldecode(enc));
 
proc rlencode(s);
loop while s /= "" do
part := span(s, s(1));
r +:= str #part + part(1);
end loop;
return r;
end proc;
 
proc rldecode(s);
loop while s /= "" do
num := span(s, "0123456789");
item := notany(s, "");
r +:= val num * item;
end loop;
return r;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>Input:
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Encoded:
12W1B12W3B24W1B14W
Decoded:
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW</pre>
 
=={{header|Sidef}}==
Line 6,124 ⟶ 6,454:
=={{header|Wren}}==
{{libheader|Wren-pattern}}
<syntaxhighlight lang="ecmascriptwren">import "./pattern" for Pattern
 
var p = Pattern.new("/u") // match any upper case letter
Line 6,235 ⟶ 6,565:
W11BW11B2W23BW13
WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</pre>
 
=={{header|Zig}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
fn Run(comptime T: type) type {
return struct {
value: T,
length: usize,
};
}
 
fn encode(
comptime T: type,
input: []const T,
allocator: std.mem.Allocator,
) ![]Run(T) {
var runs = std.ArrayList(Run(T)).init(allocator);
defer runs.deinit();
 
var previous: ?T = null;
var length: usize = 0;
 
for (input) |current| {
if (previous == current) {
length += 1;
} else if (previous) |value| {
try runs.append(.{
.value = value,
.length = length,
});
previous = current;
length = 1;
} else {
previous = current;
length += 1;
}
}
 
if (previous) |value| {
try runs.append(.{
.value = value,
.length = length,
});
}
 
return runs.toOwnedSlice();
}
 
test encode {
const input =
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
 
const expected = [_]Run(u8){
.{ .length = 12, .value = 'W' },
.{ .length = 1, .value = 'B' },
.{ .length = 12, .value = 'W' },
.{ .length = 3, .value = 'B' },
.{ .length = 24, .value = 'W' },
.{ .length = 1, .value = 'B' },
.{ .length = 14, .value = 'W' },
};
 
const allocator = std.testing.allocator;
const actual = try encode(u8, input, allocator);
defer allocator.free(actual);
 
try std.testing.expectEqual(expected.len, actual.len);
for (expected, actual) |e, a| {
try std.testing.expectEqual(e.length, a.length);
try std.testing.expectEqual(e.value, a.value);
}
}
 
fn decode(
comptime T: type,
runs: []const Run(T),
allocator: std.mem.Allocator,
) ![]T {
var values = std.ArrayList(T).init(allocator);
defer values.deinit();
for (runs) |r|
try values.appendNTimes(r.value, r.length);
return values.toOwnedSlice();
}
 
test decode {
const runs = [_]Run(u8){
.{ .length = 12, .value = 'W' },
.{ .length = 1, .value = 'B' },
.{ .length = 12, .value = 'W' },
.{ .length = 3, .value = 'B' },
.{ .length = 24, .value = 'W' },
.{ .length = 1, .value = 'B' },
.{ .length = 14, .value = 'W' },
};
 
const allocator = std.testing.allocator;
const decoded = try decode(u8, &runs, allocator);
defer allocator.free(decoded);
 
try std.testing.expectEqualStrings(
"WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW",
decoded,
);
}
 
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer std.debug.assert(gpa.deinit() == .ok);
 
const allocator = gpa.allocator();
var input = std.ArrayList(u8).init(allocator);
defer input.deinit();
 
const stdout = std.io.getStdOut().writer();
const stdin = std.io.getStdIn().reader();
try stdout.print("Input: ", .{});
try stdin.streamUntilDelimiter(input.writer(), '\n', null);
 
const runs = try encode(u8, input.items, allocator);
defer allocator.free(runs);
 
try stdout.print("Encoded:\n", .{});
for (runs) |r|
try stdout.print(" {}\n", .{r});
 
const decoded = try decode(u8, runs, allocator);
defer allocator.free(decoded);
 
try stdout.print("Decoded: {s}\n", .{decoded});
}</syntaxhighlight>
{{out}}
<pre>
Input: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
Encoded:
run_length_encoding.Run(u8){ .value = 87, .length = 12 }
run_length_encoding.Run(u8){ .value = 66, .length = 1 }
run_length_encoding.Run(u8){ .value = 87, .length = 12 }
run_length_encoding.Run(u8){ .value = 66, .length = 3 }
run_length_encoding.Run(u8){ .value = 87, .length = 24 }
run_length_encoding.Run(u8){ .value = 66, .length = 1 }
run_length_encoding.Run(u8){ .value = 87, .length = 14 }
Decoded: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW
</pre>
 
9,476

edits