Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

javascript - How to implement a binary trie that has nodes that read 4 bits at a time?

I am trying to find a way to sort of inline a binary trie in some sense. Basically, a binary trie has a node for every slot in a binary number, branching left on 0 and right on 1. How would you structure this so you could read 4 bits at a time rather than 1? It seems this would be possible by having 16 slots in each trie node, but I'm having a hard time visualizing how this would actually look; how you would read the binary input like 10101010 4-bits at a time using this sort of approach. What would it look like?

[  left    , right   ,    left,  right  ,  left,   right   ...]
  (goto2)    (goto5)   (goto7)  (goto8)   (goto9), (goto10)

Or I don't know. What is an algorithm that would check the 4 bits against 16 slots in an array?

It seems that 4 bits can be represented in 16 slots, but I just don't see how an algorithm can figure out how to read these without manually visualizing every step in detail. There must be some equation or something.

question from:https://stackoverflow.com/questions/65645992/how-to-implement-a-binary-trie-that-has-nodes-that-read-4-bits-at-a-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What you describe is a radix trie base 16. By extracting 4 bits from your key, you get a number between 0 and 15 (inclusive). You can use that number to index into your node:

struct Node {
    Node *children[16];
    Value value;
};

Value *find(const char *key, int nkey, Node *node) {
    int i = 0;
    while(i < 2*nkey && node) {
        int digit = (key[i/2] >> (i%2==0 ? 0 : 4)) & 0xf;
        node = node->children[digit];
        ++i;
    }
    return node ? &node->value : 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...