如何在 Javascript 中检索基数 trie 中的所有数据/单词

2023-12-07

我已经能够用 JavaScript 编写一个基数树示例(未优化,所以不要评判)

到目前为止我已经能够Add, Transverse and Find nodes.

我在编写一个可以的函数时遇到问题retrieve所有节点,这是我需要帮助的地方。预先感谢您

// As illustrated in:
// http://programminggeeks.com/c-code-for-radix-tree-or-trie/

// Make a class of the Tree so that you can define methods all nodes of the tree
// which are actually Trees in structure inherit the functions
function Tree() {
    this.character = undefined;

    // if this node is the end of a complete word
    // this was we can differentiate "sell" and "sells" if both are searched for
    this.isword = false;

    // How to nest the nodes, thus creating a tree structure
    this.node = {}; // [new Tree(), new Tree(), new Tree()];

    // abcdefghijklmnopqrstuvwxyz
    var start = 97,
        end = start + 25;

    function constructor(that) {
        for (var x = start; x <= end; x++) {
            // for now they are all unsigned objects
            that.node[x] = null // new Tree()
        }
        return that;
    }

    constructor(this);
    return this;
}

Tree.prototype.addNode = function(word) {
    return this.transverseNodes(word, true);
};

Tree.prototype.searchForNodes = function(word) {
    return this.transverseNodes(word, false);
};

Tree.prototype.stringToNodes = function(word) {
    var nodeArray = []
    for (var x = 0, length = word.length; x < length; x++) {
        nodeArray.push(word.charCodeAt(x));
    }
    return nodeArray;
};

Tree.prototype.transverseNodes = function(word, bool) {
    // make all of the letters lowercase to create uniformity
    var nodes = this.stringToNodes(word.toLowerCase());
    // console.log(nodes);

    // start with parent/root tree
    var currentTreeNode = this

    // transverse checking if node has been added, if not add it
    // if it was already added and it terminates a word set it "isword" property to true
    for (var i = 0, length = nodes.length; i < length; i++) {
        var node = nodes[i];

        // If the current tree node is defined so not overwrite it
        if (currentTreeNode.node[node] === null) {

            if (!bool) {
                // if bool is undefined of false, then this is a search
                return false;
            }

            // create a node
            currentTreeNode.node[node] = new Tree();
            currentTreeNode.node[node].character = String.fromCharCode(node);
        }

        // check if the node is the last character of the word
        if ((nodes.length - 1) === i) {
            // console.log(nodes.length - 1, i)
            if (!bool) {
                // if bool is undefined of false, then this is a search
                return true;
            }

            currentTreeNode.node[node].isword = true;
        }

        // get into the nested node
        currentTreeNode = currentTreeNode.node[node];
    };

    return this;
};

var tree = new Tree()

// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");

// Search the nodes
console.log(tree.searchForNodes("cat")); // true
console.log(tree.searchForNodes("catapult")); // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama")); // false
console.log(tree.searchForNodes("lamboghini")); // true

// retrieving all node
// console.log(tree.retrieveAllNodes());

该提案采用迭代和递归方法来获取树中的单词。

'use strict';
// As illustrated in:
// http://programminggeeks.com/c-code-for-radix-tree-or-trie/

// Make a class of the Tree so that you can define methods all nodes of the tree
// which are actually Trees in structure inherit the functions
function Tree() {
    this.character = undefined;

    // if this node is the end of a complete word
    // this was we can differentiate "sell" and "sells" if both are searched for
    this.isword = false;

    // How to nest the nodes, thus creating a tree structure
    this.node = {}; // [new Tree(), new Tree(), new Tree()];

    // abcdefghijklmnopqrstuvwxyz
    var start = 97,
        end = start + 25;

    function constructor(that) {
        for (var x = start; x <= end; x++) {
            // for now they are all unsigned objects
            that.node[x] = null // new Tree()
        }
        return that;
    }

    constructor(this);
    return this;
}

Tree.prototype.addNode = function (word) {
    return this.transverseNodes(word, true);
};

Tree.prototype.searchForNodes = function (word) {
    return this.transverseNodes(word, false);
};

Tree.prototype.stringToNodes = function (word) {
    var nodeArray = []
    for (var x = 0, length = word.length; x < length; x++) {
        nodeArray.push(word.charCodeAt(x));
    }
    return nodeArray;
};

Tree.prototype.transverseNodes = function (word, bool) {
    // make all of the letters lowercase to create uniformity
    var nodes = this.stringToNodes(word.toLowerCase());
    // console.log(nodes);

    // start with parent/root tree
    var currentTreeNode = this

    // transverse checking if node has been added, if not add it
    // if it was already added and it terminates a word set it "isword" property to true
    for (var i = 0, length = nodes.length; i < length; i++) {
        var node = nodes[i];

        // If the current tree node is defined so not overwrite it
        if (currentTreeNode.node[node] === null) {

            if (!bool) {
                // if bool is undefined of false, then this is a search
                return false;
            }

            // create a node
            currentTreeNode.node[node] = new Tree();
            currentTreeNode.node[node].character = String.fromCharCode(node);
        }

        // check if the node is the last character of the word
        if ((nodes.length - 1) === i) {
            // console.log(nodes.length - 1, i)
            if (!bool) {
                // if bool is undefined of false, then this is a search
                return true;
            }
            currentTreeNode.node[node].isword = true;
        }

        // get into the nested node
        currentTreeNode = currentTreeNode.node[node];
    };

    return this;
};

Tree.prototype.retrieveAllNodes = function () {

    // function for traversing over object, takes the object and an empty string for
    // the appearing words, acts as closure for the object
    function iterObject(o, r) {
        // how i like to start functions with return (...)
        // returns basically the up coming word.
        // reason for reduce, this provides a return value, with the letters
        // of the path
        return Object.keys(o).reduce(function (r, key) {
            // check if the key property has a truthy value (remember the default
            // null values)
            if (o[key]) {
                // if so, check the property isword
                if (o[key].isword) {
                    // if its truty here, we have a hit, a word is found
                    wordList.push(r + o[key].character);
                };
                // check for children
                if (o[key].node) {
                    // if node exist, go on with a new iteration and a new word
                    // extension
                    iterObject(o[key].node, r + o[key].character);
                }
            }
            // return the inevitable word stem
            return r;
        }, r);
    }

    var wordList = [];
    iterObject(this.node, '');
    return wordList;
}

var tree = new Tree();

// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");

// Search the nodes
console.log(tree.searchForNodes("cat"));         // true
console.log(tree.searchForNodes("catapult"));    // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama"));        // false
console.log(tree.searchForNodes("lamboghini"));  // true

// retrieving all words
console.log(JSON.stringify(tree.retrieveAllNodes(), 0, 4));
// retrieving whole tree
console.log(JSON.stringify(tree, 0, 4));
.as-console-wrapper { max-height: 100% !important; top: 0; }

奖励:下面是一个开销非常小的版本。

'use strict';
function Tree() {
    return this;
}

Tree.prototype.addNode = function (word) {
    this.stringToNodes(word).reduce(function (node, character, i, a) {
        if (!node[character]) {
            node[character] = {};
        }
        if (i === a.length - 1) {
            node[character].isword = true;
        }
        return node[character];
    }, this);
    return this;
};

Tree.prototype.searchForNodes = function (word) {

    function iterObject(o, r) {
        return Object.keys(o).reduce(function (r, key) {
            if (key === 'isword' && r === word) {
                found = true;
            }
            typeof o[key] === 'object' && iterObject(o[key], r + key);
            return r;
        }, r);
    }

    var found = false;
    iterObject(this, '');
    return found;
};


Tree.prototype.stringToNodes = function (word) {
    return word.toLowerCase().split('');
};

Tree.prototype.retrieveAllNodes = function () {

    function iterObject(o, r) {
        return Object.keys(o).reduce(function (r, key) {
            key === 'isword' && wordList.push(r);
            typeof o[key] === 'object' && iterObject(o[key], r + key);
            return r;
        }, r);
    }

    var wordList = [];
    iterObject(this, '');
    return wordList;
}

var tree = new Tree();

// Create the nodes
tree.addNode("cat");
tree.addNode("camel");
tree.addNode("condom");
tree.addNode("catastrophe");
tree.addNode("grandma");
tree.addNode("lamboghini");

// Search the nodes
console.log(tree.searchForNodes("cat"));         // true
console.log(tree.searchForNodes("catapult"));    // false
console.log(tree.searchForNodes("catastrophe")); // true
console.log(tree.searchForNodes("mama"));        // false
console.log(tree.searchForNodes("lamboghini"));  // true

// retrieving all words
console.log(JSON.stringify(tree.retrieveAllNodes(), 0, 4));
// retrieving whole tree
console.log(JSON.stringify(tree, 0, 4));
.as-console-wrapper { max-height: 100% !important; top: 0; }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Javascript 中检索基数 trie 中的所有数据/单词 的相关文章

随机推荐

  • 将时间戳(以微秒为单位)转换为 r 中的数据和时间

    我正在尝试将以微秒为单位的时间戳转换为 R 中的以下格式 年 月 日 时 分 秒 我尝试过不同的方法 但未能成功 按照我的代码 options digits 16 value 1521222492687300 as POSIXct valu
  • 如何在 Perl 的 system() 中检查管道中第一个程序的状态?

    perl e system crontab1 l print 按预期返回 1 程序 crontab1 不存在 perl e system crontab1 l grep blah print 返回 256 检查第一个 或两个 程序的状态的方
  • 如何自动缩放传单中的多边形?

    我的 geoJson 格式如下 statesData features push type Feature id AFG properties name Afghanistan geometry type Polygon coordinat
  • 是否可以阻止 JIT 优化方法调用?

    我们正在构建一个用于 Java 字节码程序的平均情况运行时分析的工具 其中一部分是测量实际运行时间 因此 我们将采用任意的 用户提供的方法 该方法可能有也可能没有结果 并且可能有也可能没有副作用 示例包括快速排序 阶乘 虚拟嵌套循环 并执行
  • 使用哈希值跟踪文件的唯一版本

    我将跟踪可能数百万个不同文件的不同版本 我的目的是对它们进行散列以确定我已经看到了该文件的特定版本 目前 我只使用 MD5 该产品仍在开发中 因此尚未处理过数百万个文件 这显然不够长 无法避免冲突 然而 这是我的问题 如果我使用两种不同的方
  • ffmpeg AVFrame 获取完整解码数据到 char*

    我在循环中获取帧并使用 ffmpeg 对其进行解码 得到 AVFrame 作为其结果 因此 我必须将帧的必要像素数据获取到 char 中 并作为回调函数的参数给出 那么如何生成这样的 char 数组呢 在互联网上我看到了一些例子 例如 fo
  • 每小时自动运行一次 php

    我使用的是共享 Windows 主机 其中允许通过 php 代码发送 120 封邮件 小时 我有一个 php 页面可以一次发送超过 200 封邮件 但我想每小时运行一次该页面 计划任务 我将拆分电子邮件 以 100 秒为单位 并希望每小时自
  • amp-iframe 内的 amp 页面上的 Disqus

    我尝试在 amp 文档上实现 Disqus 我的想法是使用amp iframe它加载一个仅包含 Disqus 的小文档 我用的是这个放大器框架
  • api.get_retweeter_ids() 实际上是如何工作的(Tweepy Python)?

    我对 twitter api 很陌生 我一直在尝试获取转发特定推文的每个人的 ID 列表 经过几次尝试后 我无法使用 api get retweeter ids 来获取每个 id 似乎总是能得到一些 我知道每个请求的限制为 100 个 但在
  • Javascript:如何避免在函数中添加新属性?

    我是一个JS新手 正在看书JavaScript 模式为了理解 我可以看到的代码片段之一 var myFunc function param myFunc cache 这表明函数体之外的任何人都可以添加新属性 这不会破坏封装吗 如果程序的其他
  • Delphi Firemonkey 跨平台 - 传递 Windows 句柄的通用方法

    我正沉浸在我的第二个适用于 Windows 和 OSX 的 Firemonkey 应用程序中 并慢慢地转换我的函数库以处理跨平台问题 我正在尝试创建一个通用的 SelectDirectory 函数 它将运行 Windows 或 OSX 平台
  • 如何告诉数据注释验证器也验证复杂的子属性?

    我可以在验证父对象时自动验证复杂的子对象并将结果包含在填充的结果中吗ICollection
  • 斯特林格的行为令人费解?

    Go 新手 请耐心等待 我一直在浏览 Tour of Go 页面 无意中发现了一些关于 Stringers 的令人费解的事情 考虑以下练习 https tour golang org methods 18 我最初的答案是实施 func th
  • 使用 React 更新 HTML5 视频上的源 URL

    我想更新 HTML5 视频元素中的源标签 以便当我单击按钮时 正在播放的任何内容都会切换到新视频 我有一个 Clip 组件 它返回一个 HTML5 视频元素 并通过 props 提供源 URL function Clip props ret
  • 使用jquery在密码字段中进行密码屏蔽

    如何在 Android 手机中进行密码屏蔽 例如当我们输入一个键时 它会显示一个键几秒钟并将其更改为 我尝试了中提到的插件使用js在手机中进行密码屏蔽这不是最佳的 还有 jsfiddlehttp jsfiddle net medopal X
  • 如何使用 RSpec 测试 STDIN

    好的 需要帮助进行测试 我想测试这个类是否收到字母 O 并且 当调用 move computer 方法时 会返回用户在 cli 上输入的内容 我的心理子处理器告诉我 这是一个简单的分配变量来保存 STDIN 上的随机人类输入 只是现在不明白
  • SQL Server 2012 中具有列和行总计的动态数据透视表

    我有表 RPT DailySalesSummary 其中包含 CalDate OrderID SalesAmount LocRecID 列 CalDate OrderID SalesAmount LocRecID 2016 12 01 R1
  • 在视图控制器segue之间传递数据[重复]

    这个问题在这里已经有答案了 我的第一个视图控制器 AllAthletes 是我所有核心数据实体的 uitableview 它在字幕样式表格单元格中显示实体 运动员 及其属性 例如名字等 当您单击视图单元格时 我希望此视图控制器传递所选实体的
  • 使整个应用程序可以访问数据(可能在运行时发生变化)的最佳方法是什么?

    在整个应用程序中访问数据的最佳方式是什么 在我的具体示例中 我将应用程序的设置从 XML 文件加载到 Settings Object 的实例中 并且我不想将这些设置为绝对常量 因为用户应该能够更改这些设置 并查看效果 无需重新启动程序 现在
  • 如何在 Javascript 中检索基数 trie 中的所有数据/单词

    我已经能够用 JavaScript 编写一个基数树示例 未优化 所以不要评判 到目前为止我已经能够Add Transverse and Find nodes 我在编写一个可以的函数时遇到问题retrieve所有节点 这是我需要帮助的地方 预