Estoy tratando de encontrar un patrón repetitivo de números dentro de la matriz.
Por ejemplo: si tengo Array ([0] => 0 [1] => . [2] => 1 [3] => 4 [4] => 2 [5] => 8 [6] => 5 [7] => 7 [8] => 1 [9] => 4 [10] => 2 [11] => 8 [12] => 5 [13] => 7 [14] => 1 [15 ] => 4 )
quiero saber que de [2] a [7] y [8] a [13] tengo el mismo patrón de 142857.
el idioma que más le convenga, solo tratando de descubrir cómo atacar este problema.
Gracias.
He roto el ciclo si se encuentra al menos un patrón repetitivo, puede continuar buscando patrones si lo desea,
También se usó pattern_length = 6 porque habrá muchas repeticiones para pattern_length = 1.
arr = [0,'.',1,4,2,8,5,7,1,4,2,8,5,7,1,4] pattern_length = 6; arr2 = []; arr3 = []; repetitive_string = ''; for(i=0;i<arr.length;i++){ str = ''; for(j=i;j<i+pattern_length;j++){ if(arr[j] || arr[j]===0) str+=arr[j]; else break; } if(arr2.includes(str)){ repetitive_string = str; arr3.push(arr2.indexOf(str)); arr3.push(i); break; } arr2.push(str); } if(repetitive_string){ console.log('Repetitive string found - '+repetitive_string+' at '+arr3[0]+'-'+(arr3[0]+(pattern_length-1))+' and '+arr3[1]+'-'+(arr3[1]+(pattern_length-1))) }else{ console.log('No repetitive string for the mentioned pattern length') }Con pitón.
Usando rebanadas de cuerda
group = '142857' arr = [0,1,4,2,8,5,7,1,4, 2, 3, 1] arr_as_str = ''.join(map(str, arr)) n_grp, n_arr = len(group), len(arr_as_str) match_positions = [] for i in range(n_grp): for j in range((n_arr-i)//n_grp): arr_group = arr_as_str[i+j*n_grp: i+(j+1)*n_grp] if arr_group == group: match_positions += [(i+j*n_grp, i+(j+1)*n_grp)] print(f'The pattern "{group}" occours in "{arr_as_str}"" at the following positions:') print(match_positions)Y usando una expresión regular:
import re arr = [0,'.',1,4,2,8,5,7,1,4,2,8,5,7,1,4] arr_as_str = ''.join(map(str, arr)) group = '142857' regex = r'(?P<g>{})'.format(group) print([match.span() for match in re.finditer(regex, arr_as_str)]) Observación: no tiene sentido el resultado que preguntaste: "Quiero saber que de [2] a [7] y [8] a [13] tengo el mismo patrón de 142857". porque el patrón consta de 6 caracteres pero la longitud de los intervalos dados es de 5. Entonces, los resultados en ambas implementaciones serán [(2, 8), (8, 14)]