Run-length encoding: Difference between revisions

→‎{{header|Tcl}}: shorten the encoder by leveraging foreach and regexp
m (→‎{{header|Smalltalk}}: works with + nl)
(→‎{{header|Tcl}}: shorten the encoder by leveraging foreach and regexp)
Line 989:
 
=={{header|Tcl}}==
The encoding is an even-numberedlength list with elements <tt>{count char ...}</tt>
<lang tcl>proc encode {string} {
set encoding [list]{}
# use a regular expression to match runs of one character
while {[string length $string] > 0} {
foreach {run -} [regexp set-all char-inline [string index{(.)\1+|.} $string] 0]{
forlappend {setencoding count[string 1}length $run] {[string index $stringrun $count0] eq $char} {incr count} {}
set string [string range $string $count end]
lappend encoding $count $char
}
return $encoding
Line 1,006 ⟶ 1,004:
}
return $decoded
}</lang>
}
 
<lang tcl>set str "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW"
set enc [encode $str] ;# ==> {12 W 1 B 12 W 3 B 24 W 1 B 14 W}
set dec [decode $enc]
Anonymous user