All Downloads are FREE. Search and download functionalities are using the official Maven repository.

shz.core.st.triest.ConcurrentITrieST Maven / Gradle / Ivy

package shz.core.st.triest;

import shz.core.queue.a.IArrayQueue;
import shz.core.stack.l.LLinkedStack;

import java.util.Collections;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * 值为int类型的基于单词查找树的符号表
 * 

* 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 ConcurrentITrieST extends ConcurrentTrieST { /** * 4+25+8*r(r为数组长度)+对齐填充=32+8*r *

* B=48+8*r */ protected static final class Node extends ConcurrentTrieST.Node { public int val; public Node(int r) { super(r); } } protected ConcurrentITrieST(char[] chars) { super(chars); root = new Node(chars.length); } public static ConcurrentITrieST of(char[] chars) { return new ConcurrentITrieST(chars); } public final void put(char[] a, int val) { acceptWrite(unused -> { 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 Integer get(char[] a) { return applyRead(() -> { Node x = get(root, a, a.length); return x == null || !x.leaf ? null : x.val; }); } public final Iterable getAll() { return applyRead(() -> get(root)); } protected final Iterable get(Node x) { IArrayQueue queue = IArrayQueue.of(); LLinkedStack stack = LLinkedStack.of(); push(stack, x); while (stack.size() > 0) { Node pop = stack.pop(); if (pop.leaf) queue.offer(pop.val); push(stack, pop); } return queue.isEmpty() ? Collections.emptyList() : 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 Iterable getByPrefix(char[] prefix) { return applyRead(() -> { Node x = get(root, prefix, prefix.length); if (x == null) return Collections.emptyList(); return get(x); }); } public final Iterable getChars(Predicate predicate, int limit) { return applyRead(() -> getChars0(x -> predicate == null || predicate.test(x.val), limit)); } public final Integer computeIfAbsent(char[] a, Function func) { Integer oldVal = get(a); if (oldVal != null) return oldVal; return applyWrite(() -> { Node x = get(root, a, a.length); if (x != null && x.leaf) return x.val; Integer val = func.apply(a); put(a, val); return val; }); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy