Combination of Teams Sets Algorithm - 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.

Related

How to increase the speed of pandas search process?

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

How to reorder a binary matrix such that at least '1' value in the column

I have a binary matrix A as
A=[0 0 0 1
0 1 1 0;
0 1 0 1;
0 0 0 1;
0 1 1 1]
I want to reorder the matrix A such that at least 1 column has '1' values. So, the matrix A will be come
%% switch first col and last col in the first row
A=[1 0 0 0
0 1 1 0;
0 1 0 1;
0 0 0 1;
0 1 1 1]
Now, A is satified the above condition. Is it possible to implement it in MATLAB? Thank all
Second example
A=[1 0 0 1;
0 0 1 1;
0 0 0 1]
Then result is
A=[1 0 0 1;
0 1 1 0; %% second and fourth col is switched
0 0 0 1]
Update: what is happen if the row of A is comming on fly. It means that at t=0, the first row comes and A=[1 0 0 1]. Then next time, the second row comes. The matrix A will be A=[1 0 0 1; 0 0 1 1]. Then the algorithm will be check here because the second col. of A is zero. Performs switching and then next col of A comes, so on. Could you design help me the implementation for that task?
Simple deterministic strategy, start from the top left, fill as many columns as you can with the first row, then continue with the next row and the next columns. For the remaining rows, just start over at the first column.
%Get rows in which ones can be found.
[~,r]=find(A.');
%Assign new column values for the ones
c=mod(0:numel(r)-1,size(A,2))+1;
B=zeros(size(A));
B(sub2ind(size(A),r(:),c(:)))=1;
I guess this would do (at least for tall matrices)
for ind = 1:min(size(A))
t = A(ind,:);
A(ind,:) = circshift(t,[0 -(find(t)-ind)]);
end
I found the dumbest way to do this :D
A=[0 0 0 1
0 1 1 0;
0 1 0 1;
0 0 0 1;
0 1 1 1];
while ~(any(A(:,1)) && any(A(:,2)) && any(A(:,3)) && any(A(:,4)))
for ii = 1:length(A(:,1))
A(ii,:) = A(ii,randperm(4,4));
end
end
disp(A)
The code checks each column in A to have 1. If not, it randomly shifts rows in A and repeats until the requirement is satisfied.

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;
}
}
}
}

Counting in different bases

If you want to count over 8 bits, in base 2, the result is like this:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 1 0;
.....
1 1 1 1 1 1 1 1;
But how can you make an algorithm that counts - for each bit - based on a different bases, ex:
If the least significant bit is counted according to base 5 and the most significant one is on base 2, the result should look like:
0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 1;
0 0 0 0 0 0 0 2;
0 0 0 0 0 0 0 3;
0 0 0 0 0 0 0 4;
1 0 0 0 0 0 0 0;
1 0 0 0 0 0 0 1;
1 0 0 0 0 0 0 2;
...
1 0 0 0 0 0 0 4;
Can you please give me the algorithm that generates these vectors?
One algorithm for this problem is the kind of "ripple-carry" addition most students typically learn in kindergarten, except slightly modified. When you add two numbers, you do so digit-by-digit: first the ones place, then the tens place, then the hundreds place, etc. If you would ever had to write down a number larger than 10 (e.g. 7+8=15), then you write it down minus-10 and "carry" the 10 over to the next place, where you add it (it becomes a 1); this might "ripple" over many places (e.g. 999+1=1000). By repeatedly adding one using this algorithm, we can count up one-by-one.
It is important to clarify what we're after: what does it mean for different places to have different bases. If you allow places to have arbitrary number ranges, and stand for arbitrary numbers, then some bad things can happen: a number can be written in more than one way, and/or some decimal numbers cannot be written. Therefore we will limit ourselves to a "sane" scheme where if a place i has a base bi, that means the valid digits are 0,1,2,...,bi-1 (as usual, just like in decimal), and that digits in that place represents bi times the product of all bases on the right (bi-1 x bi-2 x ...). For example, if our bases were [10,10,10], the values of the digits would be [1000,100,10,1]; if our bases were [5,10,5], the values of the digits would be [250,50,5,1]
How to add 1 to a number:
Increment the least-significant digit (LSD)
Perform ripple-carry as follows:
Set the current place to the LSD
Repeat as long as the current place exceeds its allowed max digit:
Set the digit at the current place to 0
Advance the current place one to the left
Increment the number at the new place (now on the left)
Repeat the above algorithm until you have all numbers you desire.
Python:
from itertools import *
def multibaseCount(baseFunction):
currentDigits = [0]
while True:
yield currentDigits[::-1]
# add 1
currentDigits[0] += 1
# ripple-carry:
for place,digit in enumerate(currentDigits):
if currentDigits[place]>=baseFunction(place): # if exceeds max digit
currentDigits[place] = 0 # mod current digit by 10
if place==len(currentDigits)-1: # add new digit if doesn't exist
currentDigits += [0]
currentDigits[place+1] += 1 # add 1 to next digit
else: # doesn't exceed max digit; don't need to carry any more
break
Demo, where place n has base n+1:
>>> for digits in islice(multibaseCount(lambda n:n+1),30):
... print( ''.join(map(str,digits)).zfill(5) )
...
00000
00010
00100
00110
00200
00210
01000
01010
01100
01110
01200
01210
02000
02010
02100
02110
02200
02210
03000
03010
03100
03110
03200
03210
10000
10010
10100
10110
10200
10210
If you're really only interested in eight-digit "numbers" of this format, here's some pseudo-code that will get you started:
for (a=0; a<2: a++)
for (b=0; b<5; b++)
for (c=0; c<2; c++)
for (d=0; d<2; d++)
for (e=0; e<2; e++)
for (f=0; f<2; f++)
for (g=0; g<2; g++)
for (h=0; h<2; h++)
printf("%d%d%d%d%d%d%d%d\n", a, b, c, d, e, f, g, h);
In this case, it'll be base 2, 5, 2, 2, 2, 2, 2, 2. Change the indices as you wish.
too late, but here is a solution in C.
#include <stdio.h>
#include <assert.h>
void
odo(int base, int len)
{
int stack[len+1];
int pos=0;
#define DIGIT (stack[pos])
#define LOOP(code) for(int i=0; i<len; i++) code
#define PRINT LOOP(printf("%d", stack[i]));printf("\n");
LOOP(stack[i]=-1);
while(pos>=0)
{
if (pos<len-1)
{
if (DIGIT<base)
{
DIGIT++;
pos++;
assert(DIGIT==-1);
}
else
{
DIGIT=-1;
pos--;
continue;
}
}
else
{
assert(pos==len-1);
if (DIGIT<base)
{
DIGIT++;
PRINT;
}
else
{
DIGIT=-1;
pos--;
}
}
}
}
int
main(void)
{
odo(4,6);
}

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