[QUIZ][SOLUTION] Index and Query (#54)

Z

Zed Lopez

I'm a little late to the party. I just finished PickAxe2 and this is
my first quiz (or Ruby program.) Mine doesn't Marshal the data, but
does offer both has_any and has_all methods.

class Lexicon

@@word_index =3D {}
@@i =3D -1

def initialize()
@map =3D Hash.new(0)
end

def add(doc,word)
@@word_index[word] =3D @@i+=3D1 unless @@word_index.key?(word)
@map[doc] |=3D bitmask(word)
end

def has_any(*words)
@map.keys.select {|k| (@map[k] & bitmask(words)) > 0 }
end

def has_all(*words)
return [] if words.detect { |word| !@@word_index.key?(word) }
x =3D bitmask(words)
@map.keys.select {|k| (@map[k] & x) =3D=3D x }
end

private

def bitmask(words)
x =3D 0
words.each {|word| x |=3D 1 << @@word_index[word] if @@word_index.key?(=
word)}
x
end

end

index =3D Lexicon.new
ARGF.each do |line|
line.downcase.split.each { |word| index.add($FILENAME,word) }
end

while words =3D $stdin.gets
puts index.has_all(*words.split).join(' ')
end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top