Here’s a **Scilab program for Huffman coding and decoding**.
It takes a set of source symbols with
their probabilities, generates Huffman codes, encodes a given message, and decodes it back.
// -------------------------------------------------------
// Huffman Coding and Decoding in Scilab
// -------------------------------------------------------
// --- Input symbols and probabilities ---
symbols = ['A' 'B' 'C' 'D' 'E'];
prob = [0.4 0.2 0.2 0.1 0.1]; // probabilities must sum to 1
// --- Function to build Huffman Tree ---
function [nodes,codes] = huffman(symbols,prob)
n = length(prob);
nodes = list();
// Initialize list with leaf nodes
for i = 1:n
nodes($+1) = list(prob(i), symbols(i), []);
end
// Build tree
while length(nodes) > 1
// Sort by probability
[~, idx] = gsort(matrix([nodes(:)(1)],1,-1), "g", "i");
nodes = nodes(idx);
// Pick two lowest prob nodes
left = nodes($-1);
right = nodes($);
// Merge
newprob = left(1) + right(1);
newnode = list(newprob, '', list(left,right));
// Remove and add merged node
nodes($-1:$) = [];
nodes($+1) = newnode;
end
// Assign codes recursively
codes = dict_create();
function assign_code(node, code)
if node(2) <> '' then
// leaf
dict_insert(codes, node(2), code);
else
assign_code(node(3)(1), code + "0");
assign_code(node(3)(2), code + "1");
end
endfunction
assign_code(nodes(1), "");
endfunction
// --- Build Huffman codes ---
[nodes, codes] = huffman(symbols, prob);
// --- Display codes ---
disp("Huffman Codes:");
for i=1:length(symbols)
mprintf("%s : %s\n", symbols(i), dict_get(codes, symbols(i)));
end
// --- Encoding ---
msg = ['A' 'B' 'A' 'C' 'D' 'E' 'A' 'B'];
encoded = "";
for i=1:length(msg)
encoded = encoded + dict_get(codes, msg(i));
end
disp("Original Message : " + strcat(msg));
disp("Encoded Message : " + encoded);
// --- Decoding ---
decoded = [];
node = nodes(1); // root
current = node;
for i=1:length(encoded)
bit = part(encoded,i);
if bit == "0" then
current = current(3)(1);
else
current = current(3)(2);
end
if current(2) <> '' then
decoded($+1) = current(2);
current = node;
end
end
disp("Decoded Message : " + strcat(decoded));
```
### Explanation
* **Input:** `symbols` and `prob` define your source model.
* **Huffman construction:** Combines least-probable nodes iteratively.
* **Encoding:** Message symbols replaced by Huffman codes.
* **Decoding:** Walks down the Huffman tree following 0/1 until a leaf is found.
* **Output:** Prints the generated Huffman codes, encoded bit string, and decoded message.
---
👉 Do you want me to also show you how to **plot the Huffman tree** in Scilab (graphical
representation), or just text-based code/decoded output is enough?