shz.core.st.triest.FTrieST Maven / Gradle / Ivy
package shz.core.st.triest;
import shz.core.function.FloatPredicate;
import shz.core.queue.a.FArrayQueue;
import shz.core.queue.a.LArrayQueue;
import shz.core.stack.l.LLinkedStack;
/**
* 值为float类型的基于单词查找树的符号表
*
* 8+24+2*r(r为chars数组长度)=chars
* 8+(48+8*r)*n(n为元素个数)+8*r*n*w(w为键的平均长度)
*
* B=8+48*(n+1)+8*r*n*(w+1)+(2*r+对齐填充)
*/
public class FTrieST extends TrieST {
private static final long serialVersionUID = -8200881907407535943L;
/**
* 4+25+8*r(r为数组长度)+对齐填充=32+8*r
*
* B=48+8*r
*/
protected static final class Node extends TrieST.Node {
private static final long serialVersionUID = 7281659871818133759L;
public float val;
public Node(int r) {
super(new Node[r]);
}
}
public FTrieST(char[] chars) {
super(chars);
root = new Node(chars.length);
}
public static FTrieST of(char[] chars) {
return new FTrieST(chars);
}
public final void put(char[] a, float val) {
Node x = root;
for (char c : a) {
int i = charIndex.idx(c);
if (x.next[i] == null) x.next[i] = new Node(len);
x = x.next[i];
}
x.val = val;
x.leaf = true;
}
public final Float get(char[] a, int d) {
Node x = get(root, a, d);
return x == null || !x.leaf ? null : x.val;
}
public final Float get(char[] a) {
return get(a, a.length);
}
public final FArrayQueue getAll() {
return get(root);
}
protected final FArrayQueue get(Node x) {
FArrayQueue queue = FArrayQueue.of();
if (x != null) {
LLinkedStack stack = LLinkedStack.of();
push(stack, x);
while (!stack.isEmpty()) {
Node pop = stack.pop();
if (pop.leaf) queue.offer(pop.val);
push(stack, pop);
}
}
return queue;
}
private void push(LLinkedStack stack, Node x) {
if (x.next == null) return;
for (int i = 0; i < len; ++i) if (x.next[i] != null) stack.push(x.next[i]);
}
public final FArrayQueue getByPrefix(char[] prefix) {
return get(get(root, prefix, prefix.length));
}
public final LArrayQueue getChars(FloatPredicate predicate, int limit) {
return getChars0(x -> predicate == null || predicate.test(x.val), limit);
}
}