【问题标题】:JS: debugging a Map-based trie treeJS:调试基于 Map 的 trie 树
【发布时间】:2018-03-22 15:21:25
【问题描述】:

我已经使用 JS Map 实现了一个 Trie 树。 每个条目都是一个 TrieBlock,定义如下:

class TrieBlock {
  constructor (key) {
    this.related = new Map() // children (key => UID) 
    this.key = key // node key in Trie
    this.eof = false // end-of-word stop flag
    this.data = null // additional embeded data, associated with a word
  }


}

// and the Trie
class Trie {
  constructor(debug) {
    this.debug = debug
    this.entries = new Map()
    this.entries.set(null, new TrieBlock()) // Trie ROOT block

  }

  insert(str, withData) {
    // ... ok for me !
  }

  has(word) {
    // walk through Trie
    // seek for the word
  }

  fetch(word) {
    // fetch the data associated with the word
  }
}    

为什么要在 Map 中展平特里树?只是为了简化序列化过程。好的,存储 UID 的成本过高:这些是 8 位十六进制数字 UID(如 'a2b4c6d8' 是),但我希望它可以加快 uo 访问速度,因为 Map 是时间常数的复杂性。

我的问题是:如何漂亮地打印所有前缀以进行调试?我尝试使用 DFS(深度优先搜索)算法,但它很棘手

类似:

trie.insert('CAR', 'Vroom!')  
trie.inseert('CAST', 'Habracadabra')
trie.inseert('CAR', 'Meow!')

可能输出:

* ROOT
    . C
      . A
        . R : Vroom!
        . S
          . T : Habracadra!
        . T : Meow!

编辑:

通过在控制台中运行:

$ node dist/test-debug.js 

当 dist/test-debug.js 是:

var ecmasy = require('ecmasy');

trie = new e cmasy.Trie();

trie.insert('DESCAT');
trie.insert('DESCAMP');
trie.insert('DESTOOP');

console.log('' + trie);

我们得到类似的东西:

ecmasy/Trie:

 0 : null  false
 * 1 : D  false
 * * 2 : E  false
  * * * 3 : S  false
 * * * * 4 : C  false
 * * * * 4 : T  false
 * * * * * 5 : A  false
 * * * * * 5 : O  false
 * * * * * * 6 : T  true
 * * * * * * 6 : M  false
 * * * * * * 6 : O  false
 * * * * * * * 7 : P  true
 * * * * * * * 7 : P  true

堆栈长度,符号和foef标志值是什么。

但正确答案的可能性更大:

D
+ D
  + S
    + C
      + A
        +M
          +P
        +T
         +O
           +O
             +P        

编辑:(2)

我将尽快提供一种序列化算法,人们希望使用自定义回调函数运行该算法,以序列化用户定义的数据。

有什么建议吗?

【问题讨论】:

  • 我认为用 Map 实现 Trie 树没有任何意义,因为您一开始可以只使用 Map。
  • 用于自动完成目的...
  • 你试过什么?显示一些代码并描述您的预期和得到的结果。
  • 请参考这个repo:github/hefeust/ecmasy项目。我尝试存储 4,750 多个公交车站名称(总计 52k 的累积字符串长度),它在 trie 树底层地图中分配了 8,500 多个块!
  • 我的意思是您尝试解决问题的源代码以及对该尝试的问题描述。另请提供Minimal, Complete, and Verifiable example。

标签: javascript dictionary tree trie


【解决方案1】:

使用 coorect DFS:

 after inserting "DESTOOP", "DESCAT", "LYS" and "DESCAMP" strings :

 : null  false
  : D  false
   : E  false
    : S  false
     : C  false
      : A  false
       : M  false
        : P  true
       : T  true
     : T  false
     : O  false
       : O  false
        : P  true
  : L  false
   : Y  false
    : S  true

这个 DFS 提供了正确的输出,就像打开的文件夹树窗口一样,但是在控制台中。在 repo github > hefeust > ecmasy 中提交。

享受你的下午!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    相关资源
    最近更新 更多