Martin DeMello
6/11/2008 9:51:00 PM
On Wed, Jun 11, 2008 at 1:04 PM, Justin To <tekmc@hotmail.com> wrote:
> I can't seem to grasp the algorithm for a trie. Can someone please help
> me... I need the trie to store 6-digit numbers. I've read all the above
> articles, but I still have no clue of how I should begin.
here's a quick example of a trie storing the three digit numbers 123,
145, 207, 451, 455. we take advantage of the fact that all numbers are
known to be the same length, otherwise you also need to store a
"number_ends_here?" flag on each node
{ :root =>
{ 1 =>
{ 2 => { 3 => true } },
{ 4 => { 5 => true } }
},
{ 2 =>
{ 0 => { 7 => true } }
},
{ 4 =>
{ 5 =>
{ 1 => true, 5 => true } }
}
}
you traverse it thus (untested code, but it gives the basic idea):
node = trie[:root]
num_to_check = "123"
num_to_check.split(//).each {|digit|
node = node[digit]
return false unless node
}
return true
martin