Frage

I'm playing around with multidimensional arrays in Javascript. Basically I'm trying to put letters of a string into some kind of Trie (actually a Radix Tree), using a multi-dimensional array.

  var data= [];
  var word="test";

  if (l=word[0]) {
      if (!data[l]) {
          data[l] = [];
      }
  }
  if (l=word[1]) {
      if (!data[word[0]][l]) {
          data[word[0]][l] = [];
      }
  }
  if (l=word[2]) {
      if (!data[word[0]][word[1]][l]) {
          data[word[0]][word[1]][l] = [];
      }
  }
  if (l=word[3]) {
      if (!data[word[0]][word[1]][word[2]][l]) {
          data[word[0]][word[1]][word[2]][l] = [];
      }
  }

  console.log(data);

See fiddle: http://jsfiddle.net/TN28c/

I was wondering if this could be automated (without using eval()) to handle any-length words. I know Javascript doesn't have pointers/references, which is what I would probably use in PHP, but is there maybe another way?

I'm not looking for a trie-library, I already found some of these, but I was just wondering if the above is even possible to do dynamically in Javascript.

War es hilfreich?

Lösung

var word= 'tree';
var data = [];
var obj = data;
for (var i = 0; i < word.length; i++) {
    if (!obj[word[i]]) {
        obj[word[i]] = []
    }
    obj = obj[word[i]];
}
console.log(data);

Andere Tipps

Here's a simple recursive version as an example. You could do it iteratively too of course.

function trieAdd(trie, word) {
  function addWorker(trie, position) {
    var l = trie[word[position]];
    if (!l)
      trie[word[position]] = l = [];

    if (position < word.length - 1)
      addWorker(l, position + 1);
  }

  addWorker(trie, 0);
  return trie;
}

trieAdd([], "test");
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top