ruby - How to efficiently determine percentage of particular character in each block of 100 characters in a string? -
ruby - How to efficiently determine percentage of particular character in each block of 100 characters in a string? -
i'm trying calculate percentage of particular character within each 100 block substring of given string of arbitrary length. have working version shown below, given string can potentially long - 10s of thousands millions of characters.
the string consist of no more 8 different characters: a, b, c, d, e, f, g, , h.
i need scan each 100 character block , determine percentage of given character within block. if percentage more determined amount, block index recorded. i'm finding hard explain '100 character block' is. don't need split string in 100 character chunks, need start @ each character , read next 99 characters, repeat each character until end. like, read [0..99], [1..100], [2..101], [3..102], [4..103] , on.
i'm brute forcing calculation slow. there clever way of making more efficient?
def calculate_percentage_errors full_string, searched_character, percentage_limit # full_string: abcdgfgedcbaddegdcggbcdeefgaaac....... # searched_character: # percentage_limit: 0.5 n = 0 error_index = [] while n < (full_string.length - 99) #grab string 1..100, 2..101 .... sub_string = full_string[n..(n+99)] # determine number of characters in string character_count = (100 - sub_string.gsub(searched_character, '').length) if (character_count/100.0) > percentage_limit # record index if percentage exceeds limit error_index << [(n+1),(n+100)] end n += 1 end homecoming error_index end
using each_char , index behind characters leave block:
def calc_errors string, char, threshold errors = [] count = 0 string.each_char.with_index |c, i| count += 1 if c == char count -= 1 if > 99 , string[i - 100] == char if >= 99 if count > threshold errors << [i - 99, i] end end end errors end unlike other answers, visit characters 100 times, algorithm visits each character twice: 1 time when entering block , 1 time when leaving.
ruby algorithm
Comments
Post a Comment