【发布时间】:2011-12-30 17:47:16
【问题描述】:
我一直在研究一个小型抄袭检测引擎,它使用来自MOSS 的 Idea。 我需要一个 Rolling Hash 函数,我的灵感来自 Rabin-Karp 算法。
我写的代码 -->
#!/usr/bin/env ruby
#Designing a rolling hash function.
#Inspired from the Rabin-Karp Algorithm
module Myth
module Hasher
#Defining a Hash Structure
#A hash is a integer value + line number where the word for this hash existed in the source file
Struct.new('Hash',:value,:line_number)
#For hashing a piece of text we ned two sets of parameters
#k-->For buildinf units of k grams hashes
#q-->Prime which lets calculations stay within range
def calc_hash(text_to_process,k,q)
text_length=text_to_process.length
radix=26
highorder=(radix**(text_length-1))%q
#Individual hashes for k-grams
text_hash=0
#The entire k-grams hashes list for the document
text_hash_string=""
#Preprocessing
for c in 0...k do
text_hash=(radix*text_hash+text_to_process[c].ord)%q
end
text_hash_string << text_hash.to_s << " "
loop=text_length-k
for c in 0..loop do
puts text_hash
text_hash=(radix*(text_hash-text_to_process[c].ord*highorder)+(text_hash[c+k].ord))%q
text_hash_string << text_hash_string << " "
end
end
end
end
我正在使用值运行它 --> calc_hash(text,5,101) 其中 text 是字符串输入。
代码很慢。我哪里错了?
【问题讨论】:
-
瓶颈(或瓶颈)在哪里?哪段代码占用的 CPU 时间最多?请至少运行一些简单的测试,“太慢”过于模糊。
-
我一直在尝试基于文本“算法简介”来实现算法,根据先前计算的哈希计算哈希的主循环很慢。如何进一步分析它?
-
作为编码风格建议,在运算符和值之间使用空格。它们不会对运行速度产生任何影响,并且会使您的代码更易于维护。
标签: ruby algorithm plagiarism-detection rabin-karp