2012-06-08 2 views
1

뒤집힌 색인에서 부분 일치를 검색해야합니다. 다음 코드는 완전 일치는 작동하지만 부분 일치는 작동하지 않습니다. http://rosettacode.org/wiki/Inverted_Index (더 이상 Ruby1.9.3에서 작동하지 않음)의 예제에서 이것을 다시 작성했습니다. 가장 효율적인 방법을 수행하는 방법을 알려주십시오. Lucene, Sphinx 등을 사용하는 것에 관해서는 조언하지 마십시오. 경량의 단순하고 순수한 Ruby 솔루션을 알고 있다면 직접 해보고 싶지 않습니다. 다음과 같이Ruby : 뒤집힌 ​​색인에서 부분 일치 검색

@data = {"contents"=>["1.txt", "2.txt"], "of"=>["1.txt", "2.txt"], "file"=>["1.txt", "2.txt"], "one"=>["1.txt"], "two"=>["2.txt"]} 

def search words 
    result = [] 
    words.each do |word| 
    result << @data[word] if @data[word] #should do a partial match 
    end 
    result 
end 

p search ['of'] #=> [["1.txt", "2.txt"]] 
p search ['one'] #=> [["1.txt"]] 
p search ['on'] #=> []     <<should become [["1.txt"]] 
+0

쉽게 (시간)는 O (1) 알고리즘을 사용할 수 있습니다 당신이 공간을 상관하지 않는 경우 각 단어에 대해; 모든 하위 문자열이 해당 값을 갖는 키로 갖는 해시를 작성하십시오. – tokland

답변

3

search을 정의

def search words 
    words.map do |word| 
    matches = @data.keys.select {|key| key.include?(word)} 
    matches.map {|match| @data[match] } 
    end  
end 

p search ['of'] #=> [[["1.txt", "2.txt"]]] 
p search ['one'] #=> [[["1.txt"]]] 
p search ['on'] #=> [[["1.txt", "2.txt"], ["1.txt"]]] - note that "contents" contains "on" 
+0

아마도 가장 간단한 방법이지만, 가장 효율적이지는 않습니다. 'flat_map'은 중첩 된 배열을 평평하게 만듭니다. – tokland

+0

Chowlett, 고맙습니다.이 배열은 괄호 안에이 검색 ([ 'of'])과 같이 괄호 안에 포함해야합니다. 그렇지 않으면 << 문자열을 정수로 변환 할 수 없습니다 (TypeError) >> – peter

+0

@tokland, 효율적인가? 또한 답을 줄 수 있습니까? – peter