【发布时间】:2014-06-24 15:32:57
【问题描述】:
我正在尝试计算任意长度的任意给定字符串的每 100 个块子字符串中特定字符的百分比。我有一个如下所示的工作版本,但给定的字符串可能很长 - 几千到几百万个字符。
字符串将包含不超过 8 个不同的字符:A、B、C、D、E、F、G 和 H。
我需要扫描每个 100 个字符的块并确定该块中给定字符的百分比。如果百分比大于确定的量,则记录块索引。我发现很难解释什么是“100 个字符块”。我不需要将字符串分成 100 个字符块,我需要从每个字符开始并读取接下来的 99 个字符,然后对每个字符重复直到结束。比如,读[0..99]、[1..100]、[2..101]、[3..102]、[4..103]等等。
我目前正在强制计算,但速度相当慢。有没有一种聪明的方法可以提高效率?
def calculate_percentage_errors full_string, searched_character, percentage_limit
# full_string: ABCDGFGEDCBADDEGDCGGBCDEEFGAAAC.......
# searched_character: A
# percentage_limit: 0.5
n = 0
error_index = []
while n < (full_string.length - 99) do
#grab the string 1..100, 2..101 ....
sub_string = full_string[n..(n+99)]
# determine the number of characters in the string
character_count = (100 - sub_string.gsub(searched_character, '').length)
if (character_count/100.0) > percentage_limit
# record the index if percentage exceeds limit
error_index << [(n+1),(n+100)]
end
n += 1
end
return error_index
end
【问题讨论】:
-
@IvayloPetrov:这应该是一个答案,而不是评论!