public
Created

Problem with sorting algorithm in RailsWizard

  • Download Gist
sort_test.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
require 'yaml'
require 'pp'
hash = YAML.load '
a:
after:
before:
l:
after:
before:
n:
after:
before: l
b:
after:
before:
m:
after:
before:
c:
after:
before:
z:
after:
before:
'
hash.each do |k,v|
v.each do |vk,vv|
v[vk] = (vv||'').split
end
end
 
class Hash
def without *ks
delete_if { |k,v| ks.include? k }
end
def delete! *ks
#print "\n\nwithout: #{ks.join(', ')}"
replace without *ks
end
end
 
def print_keys hash
puts hash.map(&:first).join(' ')
end
 
def sort hash
sorted_array = hash.sort do |a,b|
if b.last['after'].include?(a.first) || a.last['before'].include?(b.first)
-1
elsif b.last['before'].include?(a.first) || b.last['after'].include?(b.first)
1
else
a.first <=> b.first # simple sort by keys
end
end
print_keys sorted_array
Hash[sorted_array]
end
 
def test hash
puts nil,nil
print_keys hash
puts '-'*hash.count*3
hash.count.times { hash = sort hash }
end
 
test hash
test hash.delete! 'z'
test hash.delete! 'c'
test hash.delete! 'b'
test hash.delete! 'a'
test hash.delete! 'm'
stdout
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
a l n b m c z
---------------------
a b c m n l z
a b c l m n z
a b c n l m z
a b c m n l z
a b c l m n z
a b c n l m z
a b c m n l z
 
 
a l n b m c
------------------
a b c l m n
a b c m n l
a b c n l m
a b c l m n
a b c m n l
a b c n l m
 
 
a l n b m
---------------
a b l m n
a b m n l
a b n l m
a b l m n
a b m n l
 
 
a l n m
------------
a l m n
a l m n
a l m n
a l m n
 
 
l n m
---------
m n l
m n l
m n l
 
 
l n
------
n l
n l

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.