Skip to content

Instantly share code, notes, and snippets.

@andreif
Created May 23, 2011 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreif/987025 to your computer and use it in GitHub Desktop.
Save andreif/987025 to your computer and use it in GitHub Desktop.
Problem with sorting algorithm in RailsWizard
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'
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment