从二进制字符串中获取模式

时间:2019-05-29 09:54:34

标签: matlab binary-tree

我有一个长度为N的二进制字符串,它是2的幂(N = 2^n)。

我需要提取长度为L的特定模式,这是2L = 2^l)的幂。

完整的二叉树中,这些模式应

  • 从左叶节点(偶数索引)开始,
  • 以右叶节点(奇数索引)结尾。

这些模式应包括整个子树的叶子。 我需要提取的模式是

(1). 0 0 --- 0  (All zero)
(2). 1 1 --- 1  (All one)
(3). 0 0 --- 1  (Only the last right leaf is one). 

例如,如果我有一个N=16的二进制字符串,则(n=4)如  0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0,我需要提取

  • 0 to 7标记为模式(3),

  • 8 to 11标记为模式(2)和

  • 最后4个索引作为模式(1)。

我需要此作为通道解码算法的一部分,以修剪二叉树。 Matlab中有有效的方法吗?

2 个答案:

答案 0 :(得分:1)

我已经如下递归地实现了该解决方案,

s = [0  0  0  1  0  0  0  1  0  0  0  1  0  1  1  1  0  0  0  1  0  1  1  1  0  1  1  1  0  1  1  1 ];
N=length(s);
n = log2(N);

mask = zeros(1,N);
pattern1_indices = [];
pattern2_indices = [];
pattern3_indices = [];


for l= n:-1:1
    L = 2^l;
    t  = 2^(n-l); % Number of strings of size L

    pattern1= zeros(1,L);
    pattern3= pattern1;
    pattern3(end) = 1;
    pattern2 = ones(1,L);

    for i = 1:t
        st = (i-1)*L+1 ;
        ed = i*L ; 
        if(mask(st)==1)
            continue
        end
        chunk =  s(st:ed) ;

        if chunk == pattern3 % Only the last bit is one
            mask(st:ed) = 1;
            pattern3_indices = [pattern3_indices ; [st,ed]];
        elseif chunk == pattern1
            mask(st:ed) = 1; % All zero
            pattern1_indices = [pattern1_indices ; [st,ed]];
        elseif chunk == pattern2
            mask(st:ed) = 1; % All one
            pattern2_indices = [pattern2_indices ; [st,ed]];
        end         
    end
end

我得到如下每个模式的开始和结束索引,

pattern1_indices

pattern1_indices =

     []

>> pattern2_indices

pattern2_indices =

    15    16
    23    24
    27    28
    31    32

>> pattern3_indices

pattern3_indices =

     1     4
     5     8
     9    12
    17    20
    13    14
    21    22
    25    26
    29    30

答案 1 :(得分:0)

我想最简单的解决方案是将regular expressionregexp一起使用

%binary string example
s = '0000000111110000'

%Get the start Index (SI) and the end Index (EI)
[SI,EI] = regexp(s,'0+$')       %pattern 1
[SI,EI] = regexp(s,'0+1')       %pattern 2
[SI,EI] = regexp(s,'(?<!0)1+')  %pattern 3

将matlab上的索引从1而不是0开始。

您还可以一次使用多个正则表达式:

[SI,EI] = regexp(s,{'0+$','0+1','(?<!0)1+'})

结果:

SI = 
{
  [1,1] =  13
  [1,2] =  1
  [1,3] =  9
}
EI = 
{
  [1,1] =  16
  [1,2] =  8
  [1,3] =  12
}
相关问题