javascript - String Search Algorithm Implementation -


i have implemented string search algorithm using naive method count number of times substring occurs in string. did implementation in javascript , python.

algorithm (from topcoder):

function brute_force(text[], pattern[])  {   // let n size of text , m size of   // pattern   count = 0   for(i = 0; < n; i++) {     for(j = 0; j < m && + j < n; j++)        if(text[i + j] != pattern[j]) break;       // mismatch found, break inner loop     if(j == m) // match found         count+=1   return count   } } 

javascript implementation:

a = "rainbow"; b = "rain"; count = 0; function findsubstr(str, substr){     (i = 0; i<a.length; i++){         //document.write(i, '<br/>');         (j = 0; j < b.length; j++)             //document.write('i = ',i, '<br/>');             //document.write(j, '<br/>');             if(a[i + j] != b[j]) break;             document.write('j = ', j, '<br/>')             //document.write('i = ',i, '<br/>');     if (j  == b.length)         count+=1;     }     return count; } document.write("count ",findsubstr(a,b), '<br/>'); 

python implementation:

a = "rainbow" b = "rain" def substrinstr(str, substr):     count = 0     in range(len(str)):         j in range(len(substr)):             print j             if (a[i + j] != b[j]):                 break         if (j+1 == len(substr)):             count+=1     return count print(substrinstr(a, b)) 

now question line implements if (j == b.length): works in javascript python need add 1 value of j or deduct 1 length of b. don't know why happening.

for x in range(4) 

unlike javascript in python loop used every element in list. last value x take last element of list [0, 1, 2, 3] 3.

for(x = 0; x < 4; x++) 

in javascript x take value 4 , loop end because x < 4 condition no longer can applied. last value x take 4.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -