Huffman coding: Difference between revisions
Content deleted Content added
m →{{header|Perl 6}}: modernize |
m →{{header|Sidef}}: modified code to work with Sidef 2.10 |
||
Line 4,961: | Line 4,961: | ||
<lang ruby>func walk(n, s, h) { |
<lang ruby>func walk(n, s, h) { |
||
n.exists('a') && ( |
n.exists('a') && ( |
||
h |
h{n{'a'}} = s; |
||
say "#{n |
say "#{n{'a'}}: #{s}"; |
||
return; |
return; |
||
); |
); |
||
walk(n |
walk(n{'0'}, s+'0', h); |
||
walk(n |
walk(n{'1'}, s+'1', h); |
||
} |
} |
||
func make_tree(text) { |
func make_tree(text) { |
||
var letters = Hash.new; |
var letters = Hash.new; |
||
text.each { |c| letters |
text.each { |c| letters{c} \\= 0 ++ }; |
||
var nodes = letters.keys.map { |l| |
var nodes = letters.keys.map { |l| |
||
Hash.new('a' => l, 'freq' => letters |
Hash.new('a' => l, 'freq' => letters{l}) |
||
}; |
}; |
||
var n = Hash.new; |
var n = Hash.new; |
||
while (nodes.sort!{|a,b| a |
while (nodes.sort!{|a,b| a{'freq'} <=> b{'freq'} }.len > 1) { |
||
n = Hash.new('0' => nodes.shift, '1' => nodes.shift); |
n = Hash.new('0' => nodes.shift, '1' => nodes.shift); |
||
n |
n{'freq'} = (n{'0'}{'freq'} + n{'1'}{'freq'}); |
||
nodes.append(n); |
nodes.append(n); |
||
} |
} |
||
walk(n, '', n |
walk(n, '', n{'tree'} = Hash.new); |
||
return n; |
return n; |
||
} |
} |
||
func encode(s, t) { |
func encode(s, t) { |
||
t = t |
t = t{'tree'}; |
||
s.split(1).join('' => {t |
s.split(1).join('' => {|c| t{c}}); |
||
} |
} |
||
Line 4,997: | Line 4,997: | ||
enc.each {|bit| |
enc.each {|bit| |
||
n = n{bit}; |
|||
n.has_key('a') && ( |
|||
out += n{'a'}; n = tree; |
|||
); |
); |
||
}; |
}; |