当前位置: 首页 > 知识库问答 >
问题:

如何从使用Trie实现的词典中获得给定长度(L)的随机单词?

蒲深
2023-03-14

上面的答案解释了如何选择第一个角色,但我很困惑之后我们将如何进行。我想要长度为L的词,但当我开始遍历树时,我不知道正在遍历的树枝是否有深度L。

词典

package com.FastDictionary;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import sun.rmi.runtime.Log;

/**
 * Dictionary implementation.
 * Uses Trie Data Structure
 * Creates a singleton object
 */
public class FastDictionary {

    private int nineWordCount;
    private int totalWordCount;

    // Root Node
    private DictionaryNode root;

    // Singleton object
    private static FastDictionary fastDictionary;

    // Flag; True if words.txt has been processed once
    private boolean isProcessed;

    private FastDictionary() {

        this.root = new DictionaryNode();
        isProcessed = false;
        this.nineWordCount = 0;
        this.totalWordCount = 0;
    }

    private boolean sanitiseSearch(String text) {

        if (text == null) {
            return false;
        }
        else {
            return text.matches("[a-zA-Z]");
        }
    }

    /**
     * Add a word to Dictionary
     * @param word word to be added
     */
    public void addWord(String word) {

        if (word == null) {

            throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
        }

        // Sanitise input
        if (word.contains(" ")) {

            throw new IllegalArgumentException(
                    "Word to be added to Dictionary can't contain white spaces");
        }

        DictionaryNode currentNode = this.root;

        for (char c: word.toCharArray()) {

            DictionaryNode child = currentNode.getChild(c);

            if (child == null) {

                currentNode = currentNode.addChild(c);
            }
            else {

                currentNode = child;
            }
        }
        // Last node contains last character of valid word
        // Set that node as Leaf Node for valid word
        currentNode.setLeaf();
    }

    /**
     *
     * @param word String to be checked if it is a valid word
     * @return True if valid word
     */
    public boolean isWord(String word) {

        if (word == null) {

            throw new IllegalArgumentException("Word to be added to Dictionary can't be null");
        }

        // Sanitise input
        if (word.contains(" ")) {

            throw new IllegalArgumentException(
                    "Word to be added to Dictionary can't contain white spaces");
        }

        DictionaryNode currentNode = this.root;
        for (char c: word.toCharArray()) {

            DictionaryNode child = currentNode.getChild(c);

            if (child == null) {

                return false;
            }
            currentNode = child;
        }

        // Returns true if Last Character was leaf
        return currentNode.isLeaf();
    }

    /**
     *
     * @param text String that needs to be searched
     * @return List of Strings which are valid words searched using 'text'
     *
     */
    public ArrayList<String> getWords(String text) {

        ArrayList<String> words = new ArrayList<String>();
        DictionaryNode currentNode = this.root;

        for (int i = 0; i < text.length() ; i++) {

            DictionaryNode child = currentNode.getChild(text.charAt(i));

            if (child == null) {

                return words;
            }

            if (child.isLeaf()) {
                words.add(text.substring(0,i+1));
            }

            currentNode = child;

        }
        return words;
    }

    /**
     *
     * @param inputFileStream Text file containing list of valid words
     * Switches Flag isProcessed to True
     */
    public void processFile(InputStream inputFileStream) {

        try {

            BufferedReader br = new BufferedReader(new InputStreamReader(inputFileStream));
            String line;

            while((line = br.readLine()) != null) {
                line = line.trim();
                this.addWord(line);

                // Nine Word test
                if (line.length() == 9) {
                    this.nineWordCount++;
                }
                this.totalWordCount++;
            }

        }
        catch(Exception e){
            System.out.print(e);
        }
        this.isProcessed = true;
    }

    /**
     *
     * @return True if valid words text file has been processed
     * Word file needs to be processed just once
     */
    public boolean isProcessed() {

        return this.isProcessed;
    }

    /**
     * Factory method to create Singleton Object
     * @return Singleton object
     */
    public static FastDictionary getInstance() {

        if (fastDictionary == null) {

            fastDictionary = new FastDictionary();
        }

        return fastDictionary;
    }

    public int getNineWordCount() {
        return this.nineWordCount;
    }
}

**Node**

package com.FastDictionary;

import java.util.HashMap;

/**
 * Node of the Trie Data Structure used for FastDictionary
 */
public class DictionaryNode {

    // Character which the Node represents
    private char nodeChar;

    // Points to children
    private HashMap<Character, DictionaryNode> children = new HashMap<Character,DictionaryNode>();

    // Is Node the last character for a valid word
    private boolean isLeaf;

    /**
     * To create Root Node
     */
    DictionaryNode() {

        this.nodeChar = '.';
        this.isLeaf   = false;

    }

    /**
     * To create Child Node
     * @param c Character that Node represents
     */
    DictionaryNode(char c) {

        this.nodeChar = c;
        isLeaf        = false;
    }

    /**
     *
     * @param c Character that Node represents
     * @return Child Node which was created
     */
    public DictionaryNode addChild(char c) {

        DictionaryNode child = new DictionaryNode(c);
        this.children.put(c, child);
        return child;
    }

    /**
     *
     * @return true if Node is the last character for a valid word; default is false
     */
    public boolean isLeaf() {

        return this.isLeaf;
    }

    /**
     * Set Node as Leaf Node for a valid word
     */
    public void setLeaf() {

        this.isLeaf = true;
    }

    /**
     *
     * @param c the character which the Child Node represnts
     * @return Child Node representing character c; null if no such Child exists
     */
    public DictionaryNode getChild(char c) {

        DictionaryNode child = this.children.get(c);

        return child;
    }
}

共有1个答案

井唯
2023-03-14

是的,他只展示了如何从根节点中选择第一个字符。但是,在更新紧随该字符的CurrentNode之后,可以应用完全相同的主体从新节点中查找下一个字符。观察他的算法所做的另一种方式是,给定一个节点,一个整数L(在他的例子中是5)找到I'th(在他的例子中是1234)字,这个字在该节点的子树中,离它正好是L深度。

因此,在第一次移动之后,可以从新节点递归调用该算法,深度为l-1。这是基本的想法。当然,有些细节还需要填补。

首先,在下一次递归调用之前更新i。假设算法选择的第一个字符是d。前3个字母即a、b、c组合有1000个5个字母的单词。因此,现在需要从这个新节点中查找(1234-1000)=234个字。

String randomWord(Node currentNode,int L,int index){
    if(L==0) return node.wordContainedWithin();
    char ch = find_next_character(node,L,index); //'d' in our example
    newNode = currentNode.getChild(ch); //node following d
    //following example, words_before = 1000
    int words_before = sum(lengthFrequencyByLetter[x][L] of all x before ch)
    int new_index = index - words_before;
    return randomWord(newNode,L-1,new_index);
}
randomWord(tree.root,L,i)
 类似资料:
  • 我有一个简单的Trie,我用它来存储大约80k个长度为2-15的单词。它非常适合检查字符串是否是单词;然而,现在我需要一种获得给定长度的随机单词的方法。换句话说,我需要“getRandomWord(5)”来返回一个5个字母的单词,所有5个字母的单词都有相同的机会被返回。 我能想到的唯一方法是选择一个随机数并遍历树的宽度--首先,直到我通过了所需长度的那么多单词。有没有更好的办法做到这一点? 可能没

  • 如果我正确地看到了这一点,那么trie中的所有叶节点都将拼写出整个单词,所有父节点都包含最终叶节点之前的字符。因此,如果我有一个名为DigitalTreeNode的类,其定义为 如果我想实现一个返回trie中最长单词的方法,是否只需要在每个叶节点查找最长单词?如何实现方法,例如: 我猜它涉及到设置一个最长的字符串变量,递归地遍历每个节点,并检查它是否是一个单词,如果它是一个单词,并且它的长度大于最

  • 我的问题很简单,但我想不出怎么做。 我有一个带有一些文本的文本区,我想从文本中随机获取5个单词并将它们放入另一个输入字段(自动)。我不想成为特定的单词。随机5个单词。就这样。谢谢! 例子: “Lorem ipsum dolor sit amet,concetetur adipising elit,sed do eiusmod tempor incidundut labore et dolore m

  • 我需要得到pdf中给定单词的x,y,宽度和高度。因此,在以后解析同一类型的文件时,我可以从坐标本身获取值。如何使用java从PDF中获取单词的位置。

  • 问题内容: 我有一个单词列表文本文件,我想从该文件中获取最小,最大和平均单词长度。 我有一个流方法: 在我的主要测试方法中,我正在打印最大和最小 它按预期工作。 问题: 是否有可能像我在min和max中那样获得单词长度的平均值?在这两种情况下,是或否,怎么做(仅作为Lambda表达式)? 问题答案: 该方法将为您提供一行流,而不是单词。有了之后,调用用单词替换行,并提供lambda表达式来拆分单词

  • 本文向大家介绍Python生成给定长度的随机字符串,包括了Python生成给定长度的随机字符串的使用技巧和注意事项,需要的朋友参考一下 在本文中,我们将看到如何生成具有给定长度的随机字符串。这在创建需要随机性的随机密码或其他程序时很有用。 random.choices 随机模块中的choices函数可以产生字符串,然后可以将其连接以创建给定长度的字符串。 示例 输出结果 运行上面的代码给我们以下结