From: cruiserdan Date: 2007-12-19T04:31:01+09:00 Subject: Re: Database-like Algorithmic Problem Interesting problem. Aside from seeing a doctor, my suggestions are in the comments in the revised variant below: --- require 'set' # encapsulate class DB # use hash's default syntax def initialize @c = Hash.new{ | hash, key | hash[key] = Set.new } end # was: add, use << to follow ruby idiom for array, set # store val with hash for quicker comparison def <<(hash) hash.each do |key,val| @c[key] << [ val, hash ] end end # need a delete operation ... def delete(hash) @c.delete(hash) end # was: match_all, use select to follow ruby enumerable idiom # determine candidates on the fly, avoid intersection code using Set def select(template) good = Set.new; bad = Set.new template.each do |key,val1| (@c[key]).each do |val2,hash| ( val1 === val2 ? good : bad ) << hash unless bad.include? hash end end return good.to_a end # was: match_first, use select to follow ruby enumerable idiom # determine candidates on the fly, avoid intersection code using Set def find(template) good = Set.new; bad = Set.new template.each do |key,val1| (@c[key]).each do |val2,hash| ( val1 === val2 ? good : bad ) << hash unless bad.include? hash end return good.to_a.first unless good.empty? end return nil end end --- HTH! Dan Yoder http://dev.zeraweb.com/ On Dec 18, 9:45 am, Christophe Mckeon wrote: > > You are crazy. Please contact a doctor ASAP. Oh, sorry. :-) > > :) > > > > > I think you are on a pretty good way. Here's what I would do > > differently: > > > ... > > thanks robert. yeah i'd like to do some caching, but as hashes are > constantly > added and removed from the collection, i'll have to weigh up the > overhead of managing a cache, maybe even implement it and do some > profiling w/ and w/o. guess i'll have to read up on cache algs. > > regards, > _c > > -- > Posted viahttp://www.ruby-forum.com/.