I'm trying to find repetitive pattern of number inside array.
For ex: if i have 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 )
i want to know that from [2] to [7] & [8] to [13] i have the same pattern of 142857.
whatever language suits you best , just trying to figure out how to attack this problem.
Thank you.
CodePudding user response:
I have broke the loop if atleast one repetitive pattern is found, you can continue looking for patterns if you want,
Also used pattern_length = 6 because there will be lot of repetitions for 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')
}
CodePudding user response:
With python.
Using slices of string
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)
And using a regular expression:
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)])
Remark: is nonsense the output that you asked: "i want to know that from [2] to [7] & [8] to [13] i have the same pattern of 142857." because the pattern consist of 6 characters but the length of the given intervals are 5. So, the results in both implementations will be [(2, 8), (8, 14)]