Friday 15 April 2011

Ruby (on rails) check if a tree is not circular -



Ruby (on rails) check if a tree is not circular -

i have list of questions. every question has i.e. 4 answers , every reply linked next question has 4 answers linked next questions until "endquesion" without answers.

this tree-like build , want stays way - no reply linkes question has been asked.

i suppose way recursive function.

i thinking this:

mq = [question.id] q= question.id

def not_circular(q, mq) mother_questions = mq sister_questions = [] question = question.find(q) question.answers.each |a| if mother_questions.include?(a.next_question) homecoming a.content else if !a.endlevel sister_questions << a.next_question end end end mother_questions = mother_questions + sister_questions question.answers.each |a| if !a.endlevel homecoming not_circular(a.next_question, mother_questions) end end homecoming false end

but see few problems - thinking of making array of "parent-questions" , check if "next_question" in array (which stop function , homecoming "circular "next_question"). in illustration code there false alarm "sister-next-questions" (when answers of same question point same next question) can , should same.

can point me in right direction?

edit:

question has many answers. reply belongs questions. reply has :next_question variable pointing next question.

edit 2: got function test @ to the lowest degree 1 branch of tree correctly (see new code above). have figure out how create test branches.

my favorite way of dealing problem in trees or directed, acyclic graphs validation on bring together table. i'm not sure understand construction you're using, i'll take mutual problem of courses prerequisites each other.

class course of study < activerecord::base has_many :course_relationships, dependent: :destroy has_many :prereqs, through: :course_relationships has_many :inverse_course_relationships, class_name: 'courserelationship', foreign_key: 'prereq_id', dependent: :destroy has_many :inverse_prereqs, through: :inverse_course_relationships, source: :course end

then place validation in bring together table:

class courserelationship < activerecord::base belongs_to :course belongs_to :prereq, class_name: 'course' validate :is_acyclic def is_acyclic if course of study == prereq errors.add(:base, "a course of study can't prerequisite itself") homecoming false end check_for_course = proc.new |current_course| if course of study == current_course errors.add(:base, "catch 22 detected. \"#{course.title}\" required before \"#{prereq.title}\".") homecoming false end current_course.prereqs.each |course_to_check| check_for_course.call course_to_check end end check_for_course.call prereq homecoming true end end

this ensures every time new relationship created, course of study never prerequisite of (even if indirectly).

ruby-on-rails ruby

No comments:

Post a Comment