选择从开始到结束的组合

时间:2015-12-20 14:41:12

标签: ruby recursion

我有一系列门票,其中包含有关出发地和目的地的信息:

 class Connection
  DB = [
    {departure: "New York", destination: "Madrid"},
    {departure: "New York", destination: "Berlin"},
    {departure: "Berlin", destination: "Madrid"},
    {departure: "New York", destination: "Barcelona"},
    {departure: "New York", destination: "Warsaw"},
    {departure: "Berlin", destination: "Barcelona"},
    {departure: "Berlin", destination: "Paris"},
    {departure: "Paris",  destination: "Madrid"},
    {departure: "Madrid", destination: "New York"},
    {departure: "Madrid", destination: "Berlin"}
  ].freeze
end

我应该从头到尾选择组合。即,对于start = "New York"finish = "Madrid",方法find应返回以下内容:

 [
     [
       {dep: "New York", dest: "Madrid"}
     ],
     [
       {dep: "New York", dest: "Berlin"},
       {dep: "Berlin", dest: "Madrid"}
     ],
     [
       {dep: "New York", dest: "Berlin"},
       {dep: "Berlin", dest: "Paris"},
       {dep: "Paris", dest: "Madrid"}
     ]
   ]

我用这种方式解决了它:

class Connection
  def initialize(start, finish)
    @start  = start
    @finish = finish
    @result = []
  end

  def find(departure = @start, tickets = [])
    search_by_departure(departure).each do |ticket|
      next if tickets.any?{ |t| t[:departure] == ticket[:destination] }
      tickets << ticket
      if ticket[:destination] == @finish
        @result << clean_route(tickets)
      else
        find(ticket[:destination], tickets)
      end
    end
    @result
  end

  private

  def clean_route(route)
    route.reverse.uniq{|r| r[:departure]}.reverse
  end

  def search_by_departure(start)
    DB.select{ |x| x[:departure] == start }
  end
end

我想知道是否有更简单的方法来解决它。

0 个答案:

没有答案