Реализации алгоритмов/Кодирование длин серий
#include <stdio.h>
#include <string.h>
#define N 80
int main()
{
char *smb, code[N], encode[2 * N] = "", str[N];
int cnt = 1;
fgets(code, 80, stdin);
smb = code;
for (int i = 1; i < strlen(code); i++, smb++, cnt++) if (code[i] != *smb)
{
sprintf(encode + strlen(encode), "%d%c", cnt, *smb);
cnt = 0;
}
printf("%s\n", encode);
return 0;
}
def rle(src):
result = []
if src:
current = src.pop(0)
counter = 1
for e in src:
if e == current:
counter += 1
else:
result.append((counter, current))
current = e
counter = 1
result.append((counter, current))
return result
<?php
$code = 'fafaaaaaaaaaaaaa';
$encode = '';
for ($i = 0; $i < strlen($code);$i++){
$smb = $code[$i] ;
$count = 1 ;
for ($b = $i; $b < strlen($code);$b++){
if ($code[$b + 1] != $smb) break ;
$count++ ;
$i++ ;
}
$encode .= $count . $smb ;
}
print 'Строку: ' . $code . ' удалось сжать до ' . $encode . '.<br> И мы сэкономили ' . (strlen($code) - strlen($encode)) . ' байт.'
?>
function encode(s:string):string;
var i,k:integer; c:char;
begin
Result:='';
if s='' then exit;
c:=s[1];
k:=1;
for i:=2 to length(s)+1 do
if s[i]=c then inc(k) else
begin
if k>1 then Result:=Result+IntToStr(k);
Result:=Result+c;
c:=s[i];
k:=1;
end;
end;
function decode(s:string):string;
var i,j,c:integer;
newS:string;
begin
i:=1;
while i <= length(s) do
begin
j:=i;
while s[j] in ['0'..'9'] do inc(j);
if j-i > 0 then
begin
for c:=1 to strtoint(copy(s,i,j-i)) do newS := newS + s[j];
delete(s,i,j-i+1);
end else
begin
newS := newS + s[i];
inc(i);
end;
end;
result:= newS;
end;
Public Function Encode(ByVal SrcString As String) As String
Dim I As Long, N As Long, sResult As String
N = 1
For I = 1 To Len(SrcString)
If Not Mid(SrcString, I, 1) = Mid(SrcString, I + 1, 1) Then
sResult = sResult & IIf(I - N + 1 > 1, CStr(I - N + 1), CStr("")) & Mid(SrcString, I, 1)
N = I + 1
End If
Next
Encode = sResult
End Function
import Data.List ( group )
main = putStrLn . encode =<< getLine
-- group разбивает строку на подстроки из одинаковых элементов, foldr собирает строку.
encode = foldr (\ cs -> shows (length cs) . showChar (head cs)) "" . group
-- Линейно-рекурсивный вариант (явная реализация).
encode' [] = []
encode' (x : xs) = go 1 x xs
where
go i x (y : ys)
| x == y = go (i + 1) x ys -- увеличение значения счётчика
| True = shows i $ x : go 1 y ys -- присоединение элемента строки
go i x _ = shows i [x]