RosettaCodeData/Task/LZW-compression/M2000-Interpreter/lzw-compression-2.m2000
2023-07-01 13:44:08 -04:00

57 lines
1.8 KiB
Text

Module FastM2000 {
plaintext$="TOBEORNOTTOBEORTOBEORNOT"
Function encodeLZW$(i$) {
Def long c, d, i, l, o$, w$
Inventory dict
For i = 0 to 255 {Append dict , Chr$(i):=i}
l = i
i = 1
w$ = LEFT$(i$,1)
REPEAT{
d = 0
Repeat {
c = d
IF i > Len(i$) Then Exit
if exist(dict, w$) Then {
d=eval(dict)
} Else Append dict, w$:=l: Exit
if d<l Then i += 1 : w$ += Mid$(i$, i, 1)
} Until d >= l
l += 1 : w$ = Right$(w$, 1)
o$ += Chr$(c Mod 256) + Chr$(c div 256)
} Until i > Len(i$)
= o$
}
encodeLZW$ = encodeLZW$(plaintext$)
Document Doc$
For i = 1 to Len(encodeLZW$) STEP 2
Doc$= Str$(Asc(Mid$(encodeLZW$,i)) + 256*Asc(Mid$(encodeLZW$,i+1)))
Next i
Doc$={
}
Function decodeLZW$(i$) {
Def c, i, l, o$, t$, w$
Inventory Dict
For i = 0 to 255 {Append dict , i:=chr$(i)}
l = i
c = Asc(i$) + 256*Asc(Mid$(i$,2))
w$ = dict$(c)
o$ = w$
IF Len(i$) < 4 Then = o$
For i = 3 to Len(i$) STEP 2 {
c = Asc(Mid$(i$,i)) + 256*Asc(Mid$(i$,i+1))
IF c < l Then {
t$ = dict$(c)
} Else t$ = w$ + LEFT$(w$,1)
o$ += t$
Append dict, l:=w$ + LEFT$(t$,1)
l += 1 : w$ = t$
}
= o$
}
Doc$=decodeLZW$(encodeLZW$)+{
}
Clipboard Doc$
Report Doc$
}
FastM2000