ruby 在Ruby中实现Trie

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 在Ruby中实现Trie相关的知识,希望对你有一定的参考价值。

# A basic ruby implementation for the trie structure.
class Trie
  # Node class to store node information (character or tag, and action)
  class Node
    attr_reader :children, :tag
    attr_accessor :value

    def initialize(tag, parent, action = nil)
      @tag = tag
      parent.children << self if parent
      @children = []
      @action = action
    end

    def find_child(tag)
      children.find { |node| node.tag == tag }
    end
  end

  # Initialize the trie with an empty root node
  def initialize(name = nil)
    @root = Node.new(name, nil)
  end

  # Add a new set of nodes to the trie.
  def add(string, value)
    current = @root

    string.chars.each do |tag|
      current = current.find_child(tag) || Node.new(tag, current, nil)
    end

    current.value = value
  end

  # Execute a node action given a string. If no node is found, nothing is executed.
  def value(string)
    node = find_node(string)
    node.value if node
  end

  # Pretty print the trie recursively
  def pretty_print(current = @root, level = 0, indent = ' ')
    puts "#{indent * level}#{current.tag}#{current.value ? " (#{current.value})" : ''}"
    current.children.each { |child| pretty_print(child, level + 1, indent) }
  end

  private

  # Traverse the trie to find a node
  def find_node(string)
    current = @root

    string.chars.each do |tag|
      current = current.find_child(tag)
      return if current.nil?
    end

    current
  end
end

# Run example
# ---

trie = Trie.new 'trie_example'

trie.add 'zero', 0
trie.add 'one', 1
trie.add 'two', 2
trie.add 'point', ->(x, y) { "Point #{x},#{y}" }

puts trie.value('zero'), trie.value('one'), trie.value('two'), trie.value('three')
puts trie.value('point').call(41, 42)

trie.pretty_print

以上是关于ruby 在Ruby中实现Trie的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Ruby 中实现查找类?

如何在没有rails的ruby中实现Application Record

Swift中实现ruby中字符串乘法倍增的功能

在 Ruby on Rails 3 应用程序中实现搜索?

ruby 本要点展示了我如何使用Ruby AWS SDK,Fog和Carrierwave在我的应用程序中实现AWS假设角色功能

Ruby 中的抽象方法