How to increase the speed of pandas search process? - performance

I would like to search keywords from a dataframe column, called 'string'.
The keywords are contained in a dictionary.
For each key, the value is an array of several keywords.
My concern is that the speed is very low and it takes a lot of time.
Maybe there are many loops involved and df.str.contains cannot be used.
How to speed up the process?
def match(string, keyword):
m = len(string)
n = len(keyword)
idx = string.find(keyword)
if idx == -1:
return 0
if len(re.findall('[a-zA-Z]', string[idx])) > 0:
if idx > 0:
if len(re.findall('[a-zA-Z]', string[idx - 1])) > 0:
return 0
if len(re.findall('[a-zA-Z]', string[idx+n-1])) > 0:
if idx + n < m:
if len(re.findall('[a-zA-Z]', string[idx + n])) > 0:
return 0
return 1
def match_keyword(df, keyword_dict, name):
df_new = pd.DataFrame()
for owner_id, keyword in keyword_dict.items():
try:
for index, data in df.iterrows():
a = [match(data['string'], word) for word in keyword]
t = int(np.sum(a))
if t > 0:
df_new.loc[index, name+'_'+str(owner_id)] = 1
else:
df_new.loc[index, name+'_'+str(owner_id)] = 0
except:
df_new[name+'_'+str(owner_id)] = 0
return df_new.astype(int)
Input:
String
0 New Beauty Company is now offering 超級discounts
1 Swimming is good for children and adults
2 Children love food though it may not be good
keywords:{'a':['New', 'is', '超級'], 'b':['Swim', 'discounts', 'good']}
Results:
'New' 'is' '超級' result(or relation)
0 1 1 1 1
1 0 1 0 1
2 0 0 0 0
'Swim' 'discounts' 'good' result(or relation)
0 0 1 0 1
1 0 0 1 1
2 0 0 1 1
Final results:
'a' 'b'
0 1 1
1 1 1
2 0 1

I believe need str.contains in loop by dict with word bondaries by \b with join by | for regex OR:
for k, v in keywords.items():
pat = '|'.join(r"\b{}\b".format(x) for x in v)
#print (pat)
df[k] = df['String'].str.contains(pat).astype(int)
print (df)
String a b
0 New Beauty Company is now offering discounts 1 1
1 Swimming is good for children and adults 1 1
2 Children love food though it may not be good 0 1
If need also columns by each value and create MultiIndex in columns:
df = df.set_index('String')
for k, v in keywords.items():
for x in v:
df[(k, x)] = df.index.str.contains(x).astype(int)
df.columns = pd.MultiIndex.from_tuples(df.columns)
print (df)
a b
New is Swim discounts good
String
New Beauty Company is now offering discounts 1 1 0 1 0
Swimming is good for children and adults 0 1 1 0 1
Children love food though it may not be good 0 0 0 0 1
And then is possible get max by MultiIndex:
df = df.max(axis=1, level=0)
print (df)
a b
String
New Beauty Company is now offering discounts 1 1
Swimming is good for children and adults 1 1
Children love food though it may not be good 0 1

Related

Quick way of finding complementary vectors in MATLAB

I have a matrix of N rows of binary vectors, i.e.
mymatrix = [ 1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
.... ]
where I'd like to find the combinations of rows that, when added together, gets me exactly:
[1 1 1 1 1]
So in the above example, the combinations that would work are 1/3, 1/4/5, and 2/6.
The code I have for this right now is:
i = 1;
for j = 1:5
C = combnk([1:N],j); % Get every possible combination of rows
for c = 1:size(C,1)
if isequal(ones(1,5),sum(mymatrix(C(c,:),:)))
combis{i} = C(c,:);
i = i+1;
end
end
end
But as you would imagine, this takes a while, especially because of that combnk in there.
What might be a useful algorithm/function that can help me speed this up?
M = [
1 0 0 1 0;
1 1 0 0 1;
0 1 1 0 1;
0 1 0 0 1;
0 0 1 0 0;
0 0 1 1 0;
1 1 1 1 1
];
% Find all the unique combinations of rows...
S = (dec2bin(1:2^size(M,1)-1) == '1');
% Find the matching combinations...
matches = cell(0,1);
for i = 1:size(S,1)
S_curr = S(i,:);
rows = M(S_curr,:);
rows_sum = sum(rows,1);
if (all(rows_sum == 1))
matches = [matches; {find(S_curr)}];
end
end
To display your matches in a good stylized way:
for i = 1:numel(matches)
match = matches{i};
if (numel(match) == 1)
disp(['Match found for row: ' mat2str(match) '.']);
else
disp(['Match found for rows: ' mat2str(match) '.']);
end
end
This will produce:
Match found for row: 7.
Match found for rows: [2 6].
Match found for rows: [1 4 5].
Match found for rows: [1 3].
In terms of efficiency, in my machine this algoritm is completing the detection of matches in about 2 milliseconds.

Combination of Teams Sets Algorithm

We have N students with M students per team, and for sure N is divisible by M. so a recursive combination would do the trick.
For example
N=6,N=2
12,34,56 is a combination
13,24,56 is another one
but the problem is that combinations generated can be repeated like
12,34,56
34,12,56
so is there any algorithm to generate non repeated sets of combinations ?
Also if i have an adjacency matrix like
S1 S2 S3 S4 S5 S6 S7 S8 S9
0 1 0 0 0 0 1 0 0 0
1 0 0 1 0 0 1 0 1 0
0 0 0 1 0 0 0 1 0 0
0 1 1 0 0 1 0 1 0 0
0 0 0 0 0 1 0 0 1 0
0 0 0 1 1 0 0 0 0 1
1 1 0 0 0 0 0 0 0 0
0 0 1 1 0 0 0 0 0 0
0 1 0 0 1 0 0 0 0 1
0 0 0 0 0 1 0 0 1 0
Where 1's represents which student used to work with other students, can i generate the combinations where the max number of students in a team worked with each other equals m/2 at max ?
I think the best way to tackle this problem, is assigning each student a team number. So if you have 6 students, and the teams must be of 2 students, then you have to build 3 teams. So [0,0,1,1,2,2] could be the representation of how students are teamed.
That is an array of size 6 (the number of students), and the value in each position represents the assigned team number. If I understood correctly, you don't want to distinguish that team from [1,1,2,2,0,0] as the same students are teamed together.
The way I would do that, is assigning each student a team number, from left to right. The first student will always be in team 0, and for any other student only assign a team number up to one more than the max team number already used in the students at the left of the array. So [0,1,1,2,0,2] would be a candidate representation of how students are teamed, but [0,2,1,1,0,2] not, because student in position 1 is assigned to team 2, but the team 1 isn't started yet.
The code to create such teams could be something like:
IEnumerable<int[]> CombineTeams(int numberOfStudents, int teamSize) {
int numberOfTeams = numberOfStudents / teamSize;
int[] studentsInTeam = new int[numberOfTeams]; // used to avoid assigning more than teamSize students into a same team
studentsInTeam[0] = 1; // first student is initially assigned to team 0 from the start.
List<int[]> teams = new List<int[]>(); // here all the possible teams will be stored
int[] currentTeam = new int[numberOfStudents]; // used to assign the team numbers to studend
AssignTeams(teamSize, currentTeam, teams, 1, 0, studentsInTeam); // start assigning team numbers from the second student, as the first will always be in team 0
return teams;
}
void AssignTeams(int teamSize, int[] currentTeam, List<int[]> teams, int currentStudent, int maxTeam, int[] studentsInTeam) {
if (currentStudent == currentTeam.Length) {
int[] newTeam = new int[currentStudent];
for (int s = 0; s < currentStudent; s++)
newTeam[s] = currentTeam[s];
teams.Add(newTeam);
}
else {
for (int t = 0; t <= min(maxTeam+1, studentsInTeam.Length-1); t++) {
if (studentsInTeam[t] < teamSize) {
studentsInTeam[t]++;
currentTeam[currentStudent] = t;
AssignTeams(teamSize, currentTeam, teams, currentStudent+1, max(maxTeam, t), studentsInTeam);
studentsInTeam[t]--;
}
}
}
}
As this code creates all possible teaming combinations, there you'll find the one that maxes your teaming connections to M/2 if it exists (haven't give a thought to that last part). Hope this works for you.

Comparing Two Matrices in MATLAB which shows how much they are matched

Please assume A is a matrix of 4 x 4 which has:
A = 1 0 1 0
1 0 1 0
1 1 1 0
1 1 0 0
And B is a reference matrix (4 x 4) which is:
B = 1 0 1 0
1 0 1 0
1 0 1 0
1 1 1 0
Now, if A would be compared to B which is the reference matrix, by matching these two matrices, almost all of members are equal except A(4,3) and A(3,2). However, since B is the reference matrix and A is comparing to that, only differences of those members are matter which are 1 in B. In this particular example, A(4,3) is only matter, not A(3,2), Means:
>> C = B ~= A;
ans =
0 0 0 0
0 0 0 0
0 1 0 0
0 0 1 0
A(4,3) ~= B(4,3)
Finally, we are looking for a piece of code which can show how many percentage of ones in A are equal to their equivalent members at B. In this case the difference is:
(8 / 9) * 100 = 88.89 % are matched.
Please bear in mind that speed is also important here. Therefore, quicker solution are more appreciated. Thanks.
For getting only the different entries where there is a 1 in B, just add an & to it, so you'll only get these entries. To get the percentage, take the sum where A and B are 1. Then divide it by the sum of 1 in B (or the sum of 1in A -> see the note below).
A = [1 0 1 0;
1 0 1 0;
1 1 1 0;
1 1 0 0];
B = [1 0 1 0;
1 0 1 0;
1 0 1 0;
1 1 1 0];
C = (B ~= A) & B
p = sum(B(:) & A(:)) / sum(B(:)) * 100
This is the result:
C =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
p =
88.8889
Edit / Note: In the OP's question it's not 100% clear if he wants the percentage in relation to the sum of ones in A or B. I assumed that it is a percentage of the reference-matrix, which is B. Therefore I divide by sum(B(:)). In case you need it in reference to the ones in A, just change the last line to:
p = sum(B(:) & A(:)) / sum(A(:)) * 100
If I got it right, what you want to know is where B == 1 and A == 0.
Try this:
>> C = B & ~A
C =
0 0 0 0
0 0 0 0
0 0 0 0
0 0 1 0
To get the percentage, you could try this:
>> 100 * sum(A(:) & B(:)) / sum(A(:))
ans =
88.8889
You can use matrix-multiplication, which must be pretty efficient as listed next.
To get the percentage value with respect to A -
percentage_wrtA = A(:).'*B(:)/sum(A(:)) * 100;
To get the percentage value with respect to B -
percentage_wrtB = A(:).'*B(:)/sum(B(:)) * 100;
Runtime tests
Here's some quick runtime tests to compare matrix-multiplication against summation of elements with (:) and ANDing -
>> M = 6000; %// Datasize
>> A = randi([0,1],M,M);
>> B = randi([0,1],M,M);
>> tic,sum(B(:) & A(:));toc
Elapsed time is 0.500149 seconds.
>> tic,A(:).'*B(:);toc
Elapsed time is 0.126881 seconds.
Try:
sum(sum(A & B))./sum(sum(A))
Output:
ans =
0.8889

Microsoft Interview: transforming a matrix

Given a matrix of size n x m filled with 0's and 1's
e.g.:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
if the matrix has 1 at (i,j), fill the column j and row i with 1's
i.e., we get:
1 1 1 1 1
1 1 1 1 0
1 1 1 1 1
1 1 1 1 1
Required complexity: O(n*m) time and O(1) space
NOTE: you are not allowed to store anything except '0' or '1' in the matrix entries
Above is a Microsoft Interview Question.
I thought for two hours now. I have some clues but can't proceed any more.
Ok. The first important part of this question is that Even using a straight forward brute-force way, it can't be easily solved.
If I just use two loops to iterate through every cell in the matrix, and change the according row and column, it can't be done as the resulting matrix should be based on the origin matrix.
For example, if I see a[0][0] == 1, I can't change row 0 and column 0 all to 1, because that will affect row 1 as row 1 doesn't have 0 originally.
The second thing I noticed is that if a row r contains only 0 and a column c contains only 0, then a[r][c] must be 0; for any other position which is not in this pattern should be 1.
Then another question comes, if I find such a row and column, how can I mark the according cell a[r][c] as special as it already is 0.
My intuitive is that I should use some kind of bit operations on this. Or to meet the required complexity, I have to do something like After I take care of a[i][j], I should then proceed to deal with a[i+1][j+1], instead of scan row by row or column by column.
Even for brute-force without considering time complexity, I can't solve it with the other conditions.
Any one has a clue?
Solution: Java version
#japreiss has answered this question, and his/her answer is smart and correct. His code is in Python, and now I give the Java version. Credits all go to #japreiss
public class MatrixTransformer {
private int[][] a;
private int m;
private int n;
public MatrixTransformer(int[][] _a, int _m, int _n) {
a = _a;
m = _m;
n = _n;
}
private int scanRow(int i) {
int allZero = 0;
for(int k = 0;k < n;k++)
if (a[i][k] == 1) {
allZero = 1;
break;
}
return allZero;
}
private int scanColumn(int j) {
int allZero = 0;
for(int k = 0;k < m;k++)
if (a[k][j] == 1) {
allZero = 1;
break;
}
return allZero;
}
private void setRowToAllOnes(int i) {
for(int k = 0; k < n;k++)
a[i][k] = 1;
}
private void setColToAllOnes(int j) {
for(int k = 0; k < m;k++)
a[k][j] = 1;
}
// # we're going to use the first row and column
// # of the matrix to store row and column scan values,
// # but we need aux storage to deal with the overlap
// firstRow = scanRow(0)
// firstCol = scanCol(0)
//
// # scan each column and store result in 1st row - O(mn) work
public void transform() {
int firstRow = scanRow(0);
int firstCol = scanColumn(0);
for(int k = 0;k < n;k++) {
a[0][k] = scanColumn(k);
}
// now row 0 tells us whether each column is all zeroes or not
// it's also the correct output unless row 0 contained a 1 originally
for(int k = 0;k < m;k++) {
a[k][0] = scanRow(k);
}
a[0][0] = firstCol | firstRow;
for (int i = 1;i < m;i++)
for(int j = 1;j < n;j++)
a[i][j] = a[0][j] | a[i][0];
if (firstRow == 1) {
setRowToAllOnes(0);
}
if (firstCol == 1)
setColToAllOnes(0);
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i< m;i++) {
for(int j = 0;j < n;j++) {
sb.append(a[i][j] + ", ");
}
sb.append("\n");
}
return sb.toString();
}
/**
* #param args
*/
public static void main(String[] args) {
int[][] a = {{1, 1, 0, 1, 0}, {0, 0, 0, 0, 0},{0, 1, 0, 0, 0},{1, 0, 1, 1, 0}};
MatrixTransformer mt = new MatrixTransformer(a, 4, 5);
mt.transform();
System.out.println(mt);
}
}
Here is a solution in python pseudocode that uses 2 extra bools of storage. I think it is more clear than I could do in English.
def scanRow(i):
return 0 if row i is all zeroes, else 1
def scanColumn(j):
return 0 if col j is all zeroes, else 1
# we're going to use the first row and column
# of the matrix to store row and column scan values,
# but we need aux storage to deal with the overlap
firstRow = scanRow(0)
firstCol = scanCol(0)
# scan each column and store result in 1st row - O(mn) work
for col in range(1, n):
matrix[0, col] = scanColumn(col)
# now row 0 tells us whether each column is all zeroes or not
# it's also the correct output unless row 0 contained a 1 originally
# do the same for rows into column 0 - O(mn) work
for row in range(1, m):
matrix[row, 0] = scanRow(row)
matrix[0,0] = firstRow or firstCol
# now deal with the rest of the values - O(mn) work
for row in range(1, m):
for col in range(1, n):
matrix[row, col] = matrix[0, col] or matrix[row, 0]
# 3 O(mn) passes!
# go back and fix row 0 and column 0
if firstRow:
# set row 0 to all ones
if firstCol:
# set col 0 to all ones
Here's another intuition that gives a clean and simple algorithm for solving the problem.
An initial algorithm using O(n) space.
For now, let's ignore the O(1) memory constraint. Suppose that you can use O(n) memory (if the matrix is m × n). That would make this problem a lot easier and we could use the following strategy:
Create an boolean array with one entry per column.
For each column, determine whether there are any 1's in the column and store that information in the appropriate array entry.
For each row, set that row to be all 1's if there are any 1's in the row.
For each column, set that column to be all 1's if the corresponding array entry is set.
As an example, consider this array:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
We'd start off by creating and populating the auxiliary array, which can be done in time O(mn) by visiting each column one at a time. This is shown here:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
1 1 1 1 0 <--- aux array
Next, we iterate across the rows and fill each one in if it contains any 1's. This gives this result:
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 0 <--- aux array
Finally, we fill in each column with 1's if the auxiliary array has a 1 in that position. This is shown here:
1 1 1 1 1
1 1 1 1 0
1 1 1 1 1
1 1 1 1 1
1 1 1 1 0 <--- aux array
So there's one problem: this uses O(n) space, which we don't have! So why even go down this route?
A revised algorithm using O(1) space.
It turns out that we can use a very cute trick to run this algorithm using O(1) space. We need a key observation: if every row contains at least one 1, then the entire matrix becomes 1's. We therefore start off by seeing if this is the case. If it is, great! We're done.
Otherwise, there must be some row in the matrix that is all 0's. Since this row is all 0's, we know that in the "fill each row containing a 1 with 1's" step, the row won't be filled in. Therefore, we can use that row as our auxiliary array!
Let's see this in action. Start off with this:
1 1 0 1 0
0 0 0 0 0
0 1 0 0 0
1 0 1 1 0
Now, we can find a row with all 0's in it and use it as our auxiliary array:
1 1 0 1 0
0 0 0 0 0 <-- Aux array
0 1 0 0 0
1 0 1 1 0
We now fill in the auxiliary array by looking at each column and marking which ones contain at least one 1:
1 1 0 1 0
1 1 1 1 0 <-- Aux array
0 1 0 0 0
1 0 1 1 0
It's perfectly safe to fill in the 1's here because we know that they're going to get filled in anyway. Now, for each row that contains a 1, except for the auxiliary array row, we fill in those rows with 1's:
1 1 1 1 1
1 1 1 1 0 <-- Aux array
1 1 1 1 1
1 1 1 1 1
We skip the auxiliary array because initially it was all 0's, so it wouldn't normally be filled. Finally, we fill in each column with a 1 in the auxiliary array with 1's, giving this final result:
1 1 1 1 1
1 1 1 1 0 <-- Aux array
1 1 1 1 1
1 1 1 1 1
Let's do another example. Consider this setup:
1 0 0 0
0 0 1 0
0 0 0 0
0 0 1 0
We begin by finding a row that's all zeros, as shown here:
1 0 0 0
0 0 1 0
0 0 0 0 <-- Aux array
0 0 1 0
Next, let's populate that row by marking columns containing a 1:
1 0 0 0
0 0 1 0
1 0 1 0 <-- Aux array
0 0 1 0
Now, fill in all rows containing a 1:
1 1 1 1
1 1 1 1
1 0 1 0 <-- Aux array
1 1 1 1
Next, fill in all columns containing a 1 in the aux array with 1's. This is already done here, and we have our result!
As another example, consider this array:
1 0 0
0 0 1
0 1 0
Every row here contains at least one 1, so we just fill the matrix with ones and are done.
Finally, let's try this example:
0 0 0 0 0
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
We have lots of choices for aux arrays, so let's pick the first row:
0 0 0 0 0 <-- aux array
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
Now, we fill in the aux array:
0 1 0 1 0 <-- aux array
0 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0
Now, we fill in the rows:
0 1 0 1 0 <-- aux array
0 0 0 0 0
1 1 1 1 1
0 0 0 0 0
1 1 1 1 1
Now, we fill in the columns based on the aux array:
0 1 0 1 0 <-- aux array
0 1 0 1 0
1 1 1 1 1
0 1 0 1 0
1 1 1 1 1
And we're done! The whole thing runs in O(mn) time because we
Do O(mn) work to find the aux array, and possibly O(mn) work immediately if one doesn't exist.
Do O(mn) work to fill in the aux array.
Do O(mn) work to fill in rows containing 1s.
Do O(mn) work to fill in columns containing 1s.
Plus, it only uses O(1) space, since we just need to store the index of the aux array and enough variables to do loops over the matrix.
EDIT: I have a Java implementation of this algorithm with comments describing it in detail available on my personal site. Enjoy!
Hope this helps!
Assuming matrix is 0-based, i.e. the first element is at mat[0][0]
Use the first row and first column as table headers to contain column and row info respectively.
1.1 Note the element at mat[0][0]. If it is 1, it will require special handling at the end (described later)
Now, start scanning the inner matrix from index[1][1] up to the last element
2.1 If the element at[row][col] == 1 then update the table header data as follows
Row: mat[row][0] = 1;
Column: mat[0][col] = 1;
At this point we have the complete info on which column and row should be set to 1
Again start scanning the inner matrix starting from mat[1][1] and set each element
to 1 if either the current row or column contains 1 in the table header:
if ( (mat[row][0] == 1) || (mat[0][col] == 1) ) then set mat[row][col] to 1.
At this point we have processed all the cells in the inner matrix and we are
yet to process the table header itself
Process the table header
If the matt[0][0] == 1 then set all the elements in the first column and first
row to 1
Done
Time complexity O(2*((n-1)(m-1)+(n+m-1)), i.e. O(2*n*m - (n+m) + 1), i.e. O(2*n*m)
Space O(1)
See my implementation at http://codepad.org/fycIyflw
Another solution would be to scan the matrix as usual, and at the first 1 you split the matrix in 4 quadrants. You then set the line and the column to 1's, and recursively process each quadrant. Just make sure to set the whole columns and rows, even though you are scanning only a quadrant.
public void setOnes(int [][] matrix){
boolean [] row = new boolean [matrix.length]
boolean [] col = new boolean [matrix[0].length]
for (int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if (matrix[i][j] == 1){
row[i] = true
col[j] = true
}
}
}
for (int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if (row[i] || col[j]){
matrix[i][j] = 1;
}
}
}
}

How to make this algorithm of pattern finding?

I have a matrix and I need to find a pattern inside this matrix.
Matrix is:
1 0 0 1 1 1 0 0 0 1
0 0 0 1 1 0 1 0 0 1
0 1 1 1 0 0 0 1 0 1
1 0 1 0 0 1 1 0 1 0
1 1 1 0 0 0 1 1 0 1
0 1 0 0 1 1 0 1 0 1
1 1 1 0 0 0 1 0 0 1
1 0 0 1 0 1 1 1 0 1
Rules:
We choose one number from every row.
The next choosen number from second row must be an opposite of the precedent.
Positions of the numbers choosed by the 1 and 2 rules, must be a precise pattern.
So the question would be:
Find the best pattern that respect the 3 rules.
Example from the matrix shown:
Choosed a number: 0(2) //what is in "()" represents the position of the value..position start from 1 to 10 on rows.
1(4)
For the positions 2 and 4 to be a pattern must support rules 1 and 2 for the rest of the matrix.
So we go further on the 3rd row and we check 2nd position:1. We go 4th row, we check 4th position:0. Seems to respect the rules. There are opposite numbers on 2nd and 4th position, so we continue: 5th row, 2nd position:, and so on, but you will see on 7th row 2nd position:1 and 8th row 4th position:1; so the pattern of positions 2-4 is not good.
How could I make an algorithm based on these rules?
Maybe this will help (motivated by the comment to your question). This is a C++ sort of answer. This answer assumes 0 is always the number you pick, but you can easily edit this to allow 1 to be first.
int firstPos, secondPos;
for(int i = 0; i < 10; ++i)
if(matrix[0][i] == 0)
firstPos = i;
for(int i = 0; i < 10; ++i)
if(matrix[0][i] == 1)
secondPos= i;
bool success = true;
for(int i = 0; i < 10/2; ++i)
if(matrix[2*i][firstPos] == matrix[2*i][secondPos])
success == false;
if(success)
cout << "success" << endl;
else
cout << "failure" << endl;
I would define a pattern by index of the first item (F) and index of the second item (S). I'll also assume that indices begin with 0 (instead of 1 as in your example). Both F and S can take a value between 0 and 9. Solution is simple. Have a double nested loop that runs F and S from 0 to 9, and in third innermost loop just verify that current F and S form a pattern.

Resources