Advertisement
yarin0600

Untitled

Dec 8th, 2023
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // TrieNode.js file:
  2. --------------------
  3. export class TrieNode {
  4.   #map;
  5.   #wordQuantity;
  6.   constructor() {
  7.     this.map = new Map();
  8.     this.wordQuantity = 0;
  9.   }
  10.  
  11.   get map() {
  12.     return this.#map;
  13.   }
  14.   get wordQuantity() {
  15.     return this.#wordQuantity;
  16.   }
  17.  
  18.   set map(i_Map) {
  19.     this.#map = i_Map;
  20.   }
  21.   set wordQuantity(i_WordQuantity) {
  22.     this.#wordQuantity = i_WordQuantity;
  23.   }
  24. }
  25.  
  26. --------------------
  27. // Trie.js file:
  28. import { TrieNode } from "./TrieNode.js";
  29.  
  30. export class Trie {
  31.   #root;
  32.   constructor() {
  33.     this.root = new TrieNode();
  34.   }
  35.  
  36.   get root() {
  37.     return this.#root;
  38.   }
  39.   set root(i_Root) {
  40.     this.#root = i_Root;
  41.   }
  42.  
  43.   insert(i_NewWord) {
  44.     let current = this.root;
  45.  
  46.     for (const char of i_NewWord) {
  47.       if (!current.map.has(char)) {
  48.         current.map.set(char, new TrieNode());
  49.       }
  50.       current = current.map.get(char);
  51.     }
  52.  
  53.     ++current.wordQuantity;
  54.   }
  55. }
  56. --------------------
  57. // index.js file
  58. --------------------
  59.  
  60. import { Trie } from "./Trie.js";
  61. import { TrieNode } from "./TrieNode.js";
  62. const strings = ["aa", "a", "ab", "aab"];
  63.  
  64. // strings.sort(); // ["a", "aa", "aab", "ab"]
  65.  
  66. const countPrefixPairs = (root, wordsCount, totalPairs) => {
  67.   if (!root) {
  68.     return;
  69.   }
  70.  
  71.   if (root.wordQuantity > 0) {
  72.     wordsCount += root.wordQuantity;
  73.     totalPairs.ctr += wordsCount - 1;
  74.   }
  75.  
  76.   root.map.forEach((currentNode) =>
  77.     countPrefixPairs(currentNode, wordsCount, totalPairs)
  78.   );
  79. };
  80.  
  81. let trie = new Trie();
  82.  
  83. for (const curStr of strings) {
  84.   trie.insert(curStr);
  85. }
  86.  
  87. let totalPairs = { ctr: 0 };
  88. countPrefixPairs(trie.root, 0, totalPairs);
  89. console.log(totalPairs);
  90.  
  91.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement