Tries: Contacts

  • + 0 comments

    Simple Ruby Trie OOP solution:

    class Contacts
      def initialize
        @root = ContactNode.new
      end
    
      def add(name)
        node = @root
        name.each_char do |c|
          idx = c2i(c)
          node.children[idx] = ContactNode.new if node.children[idx].nil?
          node = node.children[idx]
          node.count += 1
        end
      end
    
      def find_count(partial)
        node = @root
        partial.each_char do |c|
          idx = c2i(c)
          return 0 if node.children[idx].nil?
    
          node = node.children[idx]
        end
        node.count
      end
    
      private
    
      def c2i(c)
        c.ord - 'a'.ord
      end
    end
    
    class ContactNode
      attr_accessor :count, :children
    
      def initialize(alphasize = 26)
        @count = 0
        @children = Array.new(alphasize)
      end
    end
    
    contacts = Contacts.new
    gets.to_i.times do
      op, arg = gets.split
      case op
      when 'add'
        contacts.add(arg)
      when 'find'
        puts contacts.find_count(arg)
      end
    end