나는 시퀀스를 인코딩하는 프로그램을 가지고있다. 즉, 허프만 방법을 사용하여 코드 워드를 만든다.허프 먼 트리를 인코딩하는 알고리즘
node = 0, leaf = 1 인 트리 자체를 인코딩해야합니다. 첫 번째 요소 (0)에 2 개의 자식이 있고 다음 두 요소 (예 : 00)에도 각각 두 개의 자식이 있고 다음 4 개 (10 00) - 하나의 리프가있는 것으로 가정 할 때 바이너리 힙과 같아야합니다. 3 잎이 아닌 아이들 등등
나는 주어진 시퀀스에 대한 결과를 가지고 있지만 어떻게 얻는 지 모른다.
function [ ] = encodeTwoPassHuff()
global CODE
global codeTree
codeTree=[];
clc;
inputStr='IF_WE_CANNOT_DO_AS_WE_WOULD_WE_SHOULD_DO_AS_WE_CAN';
a=unique(inputStr);
N=size(inputStr,2);
Nx = zeros(1, size(a, 2));
for i = 1:size(a,2)
for j = 1:N
if (a(i) == inputStr(j))
Nx(i) = Nx(i)+1;
end
end
end
for i = 1 : size(a, 2)
prob(i) = Nx(i)/N;
end
CODE = cell(length(prob), 1);
p=prob;
s = cell(length(p), 1);
for i = 1:length(p)
s{i} = i;
end
while size(s, 1) > 2
[p,i] = sort(p, 'ascend');
p(2) = p(1) + p(2);
p(1) = [];
s = s(i);
s{2} = {s{1},s{2}};
s(1) = [];
end
CODE = makecode(s, []);
fprintf('00010000010100110111101101111\n'); % encoded tree (true)
fprintf('%d', codeTree); % my result
fprintf('\n');
for i = 1:length(CODE)
len(i) = length(CODE{i});
end
% print
disp('symbol | probabil | len | codeword');
for i=1:length(prob)
fprintf('%5s\t %.4f\t %3d\t %s\n', a(i), prob(i), len(i), num2str(CODE{i}));
end
end
function [CODE]=makecode(ss, codeword)
global CODE
global codeTree
if isa(ss,'cell') % node
codeTree = [codeTree 0];
makecode(ss{1}, [codeword 1]);
makecode(ss{2}, [codeword 0]);
else % leaf
CODE{ss} = char('0' + codeword);
codeTree = [codeTree 1];
end
end
`
불행히도, 그것은 허프 먼 나무가 아닙니다. – beaker
@ 비커, 어쩌면 어떻게 든 개선 할 수 있을까요? 입증 된 허프만 코드와 동일한 평균 코드 워드 길이를 제공하는 한 괜찮다고 생각했습니다. –
트리를 생성 할 수 없을뿐만 아니라 코드가 작동하지 않을 때도 그러한 주장을하는 방법을 모르겠습니다. 당신은 당신이하려는 것을 충분히 묘사하지 않았습니다. – beaker