Jump to content

Run-length encoding: Difference between revisions

added PowerBASIC
(added PowerBASIC)
Line 978:
return $r;
}</lang>
 
=={{header|PowerBASIC}}==
 
In this example, a character that only appears once isn't given a number in the encoded sequence. This prevents the code from getting longer. (A string without any runs is returned unchanged.) This version can also 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.)
 
<lang powerbasic>FUNCTION RLDecode (i AS STRING) AS STRING
DIM Loop0 AS LONG, count AS STRING, outP AS STRING, m AS STRING
 
FOR Loop0 = 1 TO LEN(i)
m = MID$(i, Loop0, 1)
SELECT CASE m
CASE "0" TO "9"
count = count & m
CASE ELSE
IF LEN(count) THEN
outP = outP & STRING$(VAL(count), m)
count=""
ELSE
outP = outP & m
END IF
END SELECT
NEXT
FUNCTION = outP
END FUNCTION
 
FUNCTION RLEncode (i AS STRING) AS STRING
DIM tmp1 AS STRING, tmp2 AS STRING, outP AS STRING
DIM Loop0 AS LONG, count AS LONG
 
FOR Loop0 = 1 TO LEN(i)
tmp1 = MID$(i, Loop0, 1)
IF tmp1 <> tmp2 THEN
IF count > 1 THEN
outP = outP & TRIM$(STR$(count)) & tmp2
tmp2 = tmp1
count = 1
ELSEIF 0 = count THEN
tmp2 = tmp1
count = 1
ELSE
outP = outP & tmp2
tmp2 = tmp1
END IF
ELSE
INCR count
END IF
NEXT
 
IF count > 1 THEN outP = outP & TRIM$(STR$(count))
outP = outP & tmp2
FUNCTION = outP
END FUNCTION
 
FUNCTION PBMAIN () AS LONG
DIM initial AS STRING, encoded AS STRING, decoded AS STRING
initial = INPUTBOX$("Type something.")
encoded = RLEncode(initial)
decoded = RLDecode(encoded)
MSGBOX initial & $CRLF & encoded & $CRLF & decoded
END FUNCTION</lang>
 
Sample output (last example shows error from numbers in input string):
aaaaeeeeeeiiiioooouuy
4a6e4i4o2uy
aaaaeeeeeeiiiioooouuy
My dog has fleas.
My dog has fleas.
My dog has fleas.
qqq1www2eee3rrr
3q13w23e33r
qqqwwwwwwwwwwwwweeeeeeeeeeeeeeeeeeeeeeerrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
=={{header|PowerShell}}==
1,150

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.