javascript - Finding a pattern in a binary string -


i'm trying find repeating pattern in string of binary digits.

eg. 0010010010 or 1110111011 = ok

not. 0100101101 = bad

the strings 10 digits long (as above) & guess 2 iterations of 'pattern' minimum.

i started manually setting 'bank' of patterns program match there must better way using algorithm?

searching got me - think language & terminology i'm using incorrect..

quite challenge. function?

function findpattern(n) {     var maxlen = parseint(n.length/2);     next:     for(var i=1; i<=maxlen; ++i) {         var len=0, k=0, prev="", sub;         {             sub = n.substring(k,k+i);             k+= i;             len = sub.length;             if(len!=i) break;             if(prev.length && sub.length==i && prev!=sub) continue next;             if(!prev.length) prev = sub;         } while(sub.length);         var trail = n.substr(n.length-len);         if(!len || len && trail==n.substr(0,len)) return n.substr(0,i);     }     return false; } 

it works length strings contents. see the fiddle

inspired jack's , zim-zam's answer, here list brute force algorithm:

var oksubs = ["001","010","011","100","101","110", "0001","0010","0011","0100","0101","0110","0111", "1000","1001","1010","1011","1100","1101","1110", "00000","00001","00011","00101","00110","00111","01000", "01001","01010","01011","01100","01101","01110","01111", "10000","10001","10011","10101","10110","10111","11000","11001", "11010","11011","11100","11101","11110","11111"]; 

thanks jack's comment, here both short , effective code:

function findpattern(n) {     var oksubs = [n.substr(0,5),n.substr(0,4),n.substr(0,3)];     for(var i=0; i<oksubs.length; ++i) {         var sub = oksubs[i];         if((sub+sub+sub+sub).substr(0,10)==n) return sub;     }     return false; } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -