From: Justin To Date: 2008-06-14T04:32:56+09:00 Subject: Re: Trie data structure require 'ruby-prof' class Trie attr_reader :value, :children attr_accessor :number_exists, :prefix def initialize(value=nil) @value = value @children = [] @number_exists = false @prefix='' end def <<(value) sub_trie = Trie.new(value) sub_trie.prefix = prefix+value.to_s children << sub_trie return sub_trie end def each info = [value, children, number_exists, prefix] yield(info) @children.each do |child_node| child_node.each { |e| yield e } end end def output(opt='all') if(opt.is_a?(String)) if(opt.downcase=='all') each do |x| if(x[3]!='') if(x[2]) puts x[3] end end end else puts "Error: '#{opt}' not a valid selection.\n \ Valid selections\n \ - All: outputs every # in the Trie\n \ - #: (e.g. 1, 123, 43...) checks if the # exists in the Trie" end else if(opt.is_a?(Fixnum)) each do |x| if(x[3].to_i==opt) if(x[2]) puts x[3].to_s + ' exists.' return true end end end puts "#{opt} not found." end end end #-------------------------------------------------------------------------------------- def child_value?(value, node) if(node.children.empty?) return 'empty' # Return: 'empty', children[i], 'D.N.E.' else i=0; while(i