On 01/01/2010 09:00 PM, Joe B. wrote:
cLatLngBox.topRightLat = bNextRow ? 90 : cLatLngBox.topRightLat-size
cRemove = []
cluster[:lat]+=listing[:lat].to_f
break
This is faster than not removing the items. But I’d like to remove them
while I’m in the above loop, but still have the ability to break.
I am not sure I fully understand your requirement (partly because the
code seems incomplete, e.g. where does “size” come from?) but I believe
you might have the wrong iteration approach: as far as I understand you
have a large array and every element in that array falls into one of
72 cluster spots. Since the array is large you want to traverse it only
once. So the natural thing would be to traverse the array, put every
element into its corresponding spot and then use the clustered
information. You could use #group_by for this when on 1.8.7 or newer.
[email protected]:~$ ruby1.8 -v
ruby 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]
[email protected]:~$ ruby1.8 -e ‘p (1…10).group_by{|x|x%3}’
{0=>[3, 6, 9], 1=>[1, 4, 7, 10], 2=>[2, 5, 8]}
[email protected]:~$
So I would end up doing something like this:
Spot = Struct.new :lat, :lng do
include Comparable
def <=>(spot)
to_a <=> spot.to_a
end
def get_box(precision)
# place realistic calculation here
Spot.new lat.round(-1), lng.round(-1)
end
end
listings = … # filled with Spot instances
clustered = listings.group_by do |spot|
spot.get_box
end
a variant might be:
ClusterSpot = Struct.new :lat, :lng, :count do
def initialize
self.lat = self.lng = self.count = 0
end
def update(spot)
c = (count + 1).to_f
self.lat = ((lat * count) + spot.lat) / c
self.lng = ((lng * count) + spot.lng) / c
self.count += 1
end
end
clustered = Hash.new do |h,k|
add something to the Hash whenever the key shows
up the first time
h[k] = ClusterSpot.new
end
listings.each do |spot|
clustered[spot.get_box].update(spot)
end
output clustered information
clustered.keys.sort.each do |cl_spot|
printf “%6d entries for %p\n”, clustered[cl_spot].size, cl_spot
end
Of course you can pull this off without defining additional classes but
with specialized classes the code becomes clearer and more reusable
IMHO.
Kind regards
robert