0

I have a simple problem which needs solving. I have some code which sorts out tasks dependant on other tasks. For examaple tasks A, B, C, and D. However These need sorting in order of dependancies. Example, task B can only be completed after task D is done. Therefore the order of tasks would be :

  • A
  • D
  • B
  • C

I have some code in Python, is there a way to make this code work in Rails (as in correct the syntax/method)

class Node:
def __init__(self, name):
  self.name = name
  self.edges = []

def addEdge(self, node):
  self.edges.append(node)
4

1 回答 1

0
require 'set'

class CircularDependenciesError < Exception
end

class Task
  attr_reader :name, :depends

  def initialize(task_name, dependencies=[])
    @name = task_name
    @depends = Set.new dependencies
  end

  def add_dependencies(*d)
    @depends.merge d 
  end

  def <=>(rhs)
    if depends.include?(rhs.name) and rhs.depends.include?(name) 
      raise CircularDependenciesError,
            "#{name} and #{rhs.name} depend on each other"
    elsif rhs.depends.include? name 
      -1
    elsif depends.include? rhs.name
      1
    else 
      0
    end
  end
end

tasks = [
  Task.new("A", ["B", "C"]),
  Task.new("B", ["C", "D"]),
]

t = Task.new("C")
t.add_dependencies("D", "E")
tasks << t

p tasks
p tasks.sort

--output:--
[#<Task:0x000001018c0530 @name="A", @depends=#<Set: {"B", "C"}>>,
 #<Task:0x000001018c0350 @name="B", @depends=#<Set: {"C", "D"}>>,
 #<Task:0x000001018c01c0 @name="C", @depends=#<Set: {"D", "E"}>>]

[#<Task:0x000001018c01c0 @name="C", @depends=#<Set: {"D", "E"}>>,
 #<Task:0x000001018c0350 @name="B", @depends=#<Set: {"C", "D"}>>,
 #<Task:0x000001018c0530 @name="A", @depends=#<Set: {"B", "C"}>>]
于 2013-08-13T17:05:53.143 回答