def reorganize_points(points)
hh = {}
points.each do |point|
hh[point.x] ||= {}
hh[point.x][point.y] ||= []
hh[point.x][point.y] << point
end
result = []
hh.values.each do |h|
h.values.each do |pp|
result << pp
end
end
result
end
Refactorings
No refactoring yet !
steved
March 7, 2011, March 07, 2011 00:39, permalink
Assuming you want to group by common (x, y) you can use Ruby 1.9's Enumerable#group_by()
class Point
attr_accessor :x, :y
def initialize(x, y)
self.x = x
self.y = y
end
def to_h
"#{x}, #{y}"
end
end
points = [
Point.new(1,2),
Point.new(4,2),
Point.new(1,3),
Point.new(1,1),
Point.new(2,3),
Point.new(1,1),
]
reorganized_points = points.group_by(&:to_h).values
reorganized_points.each {|ary| puts ary.inspect}
[#<Point:0x00000100862878 @x=1, @y=2>]
[#<Point:0x00000100862800 @x=4, @y=2>]
[#<Point:0x00000100862788 @x=1, @y=3>]
[#<Point:0x00000100862698 @x=1, @y=1>, #<Point:0x00000100862530 @x=1, @y=1>]
[#<Point:0x000001008625a8 @x=2, @y=3>]
rorchesstt-gmail-com.myopenid.com
March 7, 2011, March 07, 2011 02:50, permalink
I think you missed the point of what the method does.
Your suggestion produces a different result.
def reorganize_points(points)
hh = {}
points.each do |point|
hh[point.x] ||= {}
hh[point.x][point.y] ||= []
hh[point.x][point.y] << point
end
result = []
hh.values.each do |h|
h.values.each do |pp|
result << pp
end
end
result
end
class Point
attr_accessor :x, :y
def initialize(x, y)
self.x = x
self.y = y
end
def to_h
"#{x}, #{y}"
end
def to_s
"#{x}, #{y}"
end
end
points = [
Point.new(1,2),
Point.new(4,2),
Point.new(1,3),
Point.new(1,1),
Point.new(2,3),
Point.new(1,1)
]
points1 = reorganize_points(points)
points2 = points.group_by(&:to_h).values
puts "----------------------------------"
puts points1
puts "----------------------------------"
puts points2
puts "----------------------------------"
Output:
----------------------------------
1, 2
1, 3
1, 1
1, 1
4, 2
2, 3
----------------------------------
1, 2
4, 2
1, 3
1, 1
1, 1
2, 3
----------------------------------
Adam
March 9, 2011, March 09, 2011 06:09, permalink
class Point
attr_accessor :x, :y
def initialize(x, y)
@x, @y = x, y
end
def to_a
[ x, y ]
end
def to_s
to_a.join(', ')
end
def <=>(point)
to_a <=> point.to_a
end
end
# Example Usage
points = [ Point.new(1,2), Point.new(4,2), Point.new(1,3), Point.new(1,1), Point.new(2,3), Point.new(1,1) ]
puts points.sort
Thanks