Which row has the most 1s in a 0-1 matrix with all 1s "on the left"? - algorithm

Problem
Each row of an n x n matrix consists of 1's and 0's such that in any row, all 1's come before any 0's. Find row containing most no of 1's in O(n).
Example
1 1 1 1 1 0 <- Contains maximum number of 1s, return index 1
1 1 1 0 0 0
1 0 0 0 0 0
1 1 1 1 0 0
1 1 1 1 0 0
1 1 0 0 0 0
I found this question in my algorithms book. The best I could do took O(n logn) time.
How to do this in O(n)?

Start at 1,1.
If the cell contains 1, you're on the longest row so far; write it down and go right.
If the cell contains 0, go down.
If the cell is out of bounds, you're done.

You can do it in O(N) as follows:
Start at A[i][j] with i=j=0.
1, keep moving to the right by doing j++
A[i][j] =
0, move down to the next row by doing i++
When you reach the last row or the last column, the value of j will be the answer.
Pseudo code:
Let R be number of rows
Let C be number of columns
Let i = 0
Let j = 0
Let max1Row = 0
while ( i<R && j<C )
if ( matrix[i][j] == 1 )
j++
max1Row = i
else
i++
end-while
print "Max 1's = j"
print "Row number with max 1's = max1Row"

Start with the first row. Keep the row R that has the most numbers of 1s and the index i of the last 1 of R. in each iteration compare the current row with the row R on the index i. if the current row has a 0 on position i, the row R is still the answer.
Otherwise, return the index of the current row. Now we just have to find the last 1 of the current row. Iterate from index i up to the last 1 of the current row, set R to this row and i to this new index.
i
|
v
R-> 1 1 1 1 1 0
|
v 1 1 1 0 0 0 (Compare ith index of this row)
1 0 0 0 0 0 Repeat
1 1 1 1 0 0 "
1 1 1 1 0 0 "
1 1 0 0 0 0 "

Some C code to do this.
int n = 6;
int maxones = 0, maxrow = -1, row = 0, col = 0;
while(row < n) {
while(col < n && matrix[row][col] == 1) col++;
if(col == n) return row;
if(col > maxones){
maxrow = row;
maxones = col;
}
row++;
}

int [] getMax1withRow(int [][] matrix){
int [] result=new int[2];
int rows=matrix.length;
int cols=matrix[0].length;
int i=0, j=0;
int max_row=0;// This will show row with maximum 1. Intialing pointing to 0th row.
int max_one=0;// max one
while(i< rows){
while(matrix[i][j]==1){
j++;
}
if(j==n){
result[0]=n;
result[1]=i;
return result;
}
if(j>max_one){
max_one=j;
max_row=i;
}
j=0;// Again start from the first column
i++;// increase row number
}
result[0]=max_one;
result[1]=max_row;
return result;
}
Time complexity => O(row+col), In worse case If every row has n-1 one except last row which have n 1s then we have be travel till last row.

Related

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.

Finding a minimal set of rectangles covering a binary matrix [duplicate]

This question already has answers here:
Algorithm for finding the fewest rectangles to cover a set of rectangles without overlapping
(2 answers)
Closed 5 years ago.
Say I have the following binary matrix:
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
I want to find the set of rectangles parallel to the x and y axis that covers every 1 at least once and covers not a single 0 which has minimal cardinality (the least amount of rectangles). In the example above this would be the rectangles ((0, 3), (6, 5)) and ((3, 0), (5, 8)) (notation is in the form (topleft, bottomright)) - the minimal solution is using two rectangles.
My previous attempt was finding the rectangle with the largest area covering only 1's, adding that rectangle to the set and then marking all those 1's as 0's, until all 1's are gone. While this set would cover every 1 and not a single 0, it won't necessarily have minimal cardinality (this algorithm will fail on the example above).
I think you should replace covered 1's with 2's instead of 0's. This way you can include the 2's when covering 1's and still not cover any 0's.
Here's what I came up with:
#include <stdio.h>
#include <stdlib.h>
struct board {
int **data;
int w,h;
};
int load_board(char *, struct board *);
void print_board(struct board *);
int max_height_with_fixed_w(struct board *board, int i, int j, int w) {
int jj = -1, ii;
if (board->data[j][i] != 0) {
for (jj = j; jj < board->h && board->data[jj][i] != 0; jj++) {
for (ii = i; ii - i < w; ii++) {
if (board->data[jj][ii] == 0)
return jj - j;
}
}
printf("maximum height = %d\n", jj);
}
return jj - j;
}
void find_largest_rect_from(
struct board *board,
int i, int j, int *ei, int *ej) {
int max_w = 0, max_h = 0, max_a = 0;
*ei = *ej = -1;
for (max_w = 0; max_w < board->w - i &&
(board->data[j][i + max_w] != 0);
max_w++) {
int max_aa;
int max_hh = max_height_with_fixed_w(board, i, j, max_w + 1);
if (max_hh > max_h) {
max_h = max_hh;
}
max_aa = max_hh * (max_w + 1);
printf(" area: %d x %d = %d\n", max_hh, max_w + 1, max_aa);
if (max_aa > max_a) {
max_a = max_aa;
*ei = i + max_w;
*ej = j + max_hh - 1;
}
}
printf("max width : %d\n", max_w);
printf("max height: %d\n", max_h);
printf("max area : %d\n", max_a);
}
int main(int arc, char **argv) {
struct board board;
int jj, ii, i = 0, j = 0;
int total_rects = 0;
if(load_board(argv[1], &board)) return 1;
print_board(&board);
for (j = 0; j < board.h; j++) {
for (i = 0; i < board.w; i++) {
if (board.data[j][i] == 1) {
find_largest_rect_from(&board, i, j, &ii, &jj);
printf("largest from %d, %d ends at %d,%d\n", i, j, ii, jj);
int marki, markj;
total_rects++;
for (markj = j; markj <= jj; markj++) {
for (marki = i; marki <= ii; marki++) {
board.data[markj][marki] = 2;
}
}
print_board(&board);
}
}
}
printf("minimum %d rects are required\n", total_rects);
return 0;
}
int load_board(char *fname, struct board *board) {
FILE *file = fopen(fname, "r");
int j,i;
if (!file) return 1;
fscanf(file, "%d %d", &board->w, &board->h);
board->data = (int**)malloc(sizeof(int*)*board->h);
for (j = 0; j < board->h; j++) {
board->data[j] = (int*)malloc(sizeof(int)*board->w);
for (i = 0; i < board->w; i++) {
fscanf(file, "%d", &board->data[j][i]);
}
}
return 0;
}
void print_board(struct board *board) {
int i,j;
printf("board size: %d, %d\n", board->w, board->h);
for (j = 0; j < board->h; j++) {
for (i = 0; i < board->w; i++) {
printf("%d ", board->data[j][i]);
} printf("\n");
}
}
Example input 1:
7 9
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
0 0 0 1 1 1 0
0 0 0 1 1 1 0
0 0 0 1 1 1 0
Example input 2:
7 7
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0
Idea for an algorithm:
As long as there are 1s in the matrix do:
For every 1 that doesn't have 1 above it AND doesn't have 1 to its left, do:
Go greedy: start from this 1 and go in diagonal to the right and down, as long as there are 1s on the way - create a rectangle and change the 1s of the created rectangle into 0s.
I'd go for an algorithm that picks points and expands until it comsumed all possible space, and then picks more, until all points on the grid have been consumed.
For your example, say we're consuming 1s.
I'll pick (0,3), the uppermost of the leftmost 1s. My rectangle would start at a size of 0,0. I'd expand it right and down until it grew to a size of 6,2. At this point, I'd mark those points as occupied.
I'd then pick another point, say (3,0), with a rectangle of size 0,0. I'd grow it down and right until it took up the largest available space, at a size of 2,6.
Consider the following:
0 0 0 1 0 0 0
0 0 1 1 1 0 0
0 1 1 1 1 1 0
1 1 1 1 1 1 1
0 1 1 1 1 1 0
0 0 1 1 1 0 0
0 0 0 1 0 0 0
You can easily determine that for any random starting points, it will always take 4 rectangles.
In order to mark points as "occupied", you should mark them differently than those marked "unconsumable". You can then differentiate between unconsumable (which cannot be expanded into) and "occupied" (which may be expanded into, but do not have to be since they already have been).

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

Partitioning a no. N into M partitions

I'm trying a problem in which I have to partition a no. N into M partitions as many as possible.
Example:
N=1 M=3 , break 1 into 3 parts
0 0 1
0 1 0
1 0 0
N=3 M=2 , break 3 into 2 parts
2 1
1 2
3 0
0 3
N=4 M=4 , break 4 into 4 parts
0 0 0 4
0 0 4 0
0 4 0 0
4 0 0 0
0 0 1 3
0 1 0 3
0 1 3 0
.
.
.
and so on.
I did code a backtrack algo. which produce all the possible compositions step by step, but it chokes for some larger input.Because many compositions are same differing only in ordering of parts.I want to reduce that.Can anybody help in providing a more efficient method.
My method:
void backt(int* part,int pos,int n) //break N into M parts
{
if(pos==M-1)
{
part[pos]=n;
ppart(part); //print part array
return;
}
if(n==0)
{
part[pos]=0;
backt(part,pos+1,0);
return;
}
for(int i=0;i<=n;i++)
{
part[pos]=i;
backt(part,pos+1,n-i);
}
}
In my algo. n is N and it fill the array part[] for every possible partition of N.
What I want to know is once generating a composition I want to calculate how many times that composition will occur with different ordering.For ex: for N=1 ,M=3 ::: composition is only one : <0,0,1> ,but it occurs 3 times. Thats what I want to know for every possible unique composition.
for another example: N=4 M=4
composition <0 0 0 4> is being repeated 4 times. Similarly, for every unique composition I wanna know exactly how many times it will occur .
Looks like I'm also getting it by explaining here.Thinking.
Thanks.
You can convert an int to a partitioning as follows:
vector<int> part(int i, int n, int m)
{
int r = n; // r is num items remaining to be allocated
vector<int> result(m, 0); // m entries inited to 0
for (int j = 0; j < m-1; j++)
{
if (r == 0) // if none left stop
break;
int k = i % r; // mod out next bucket
i /= r; // divide out bucket
result[j] = k; // assign bucket
r -= k; // remove assigned items from remaining
}
result[m-1] = r; // put remainder in last bucket
return result;
}
So you can use this as follows:
for (int i = 0; true; i++)
{
vector<int> p = part(i, 3, 4);
if (i != 0 && p.back() == 3) // last part
break;
... // use p
};
It should be clear from this how to make an incremental version of part too.
A much simpler and mathematical approach:
This problem is equivalent to finding the co-efficient of x^N in the expression f(x) = (1+x+x^2+x^3+....+x^N)^M
f(x) = ((x^(N-1) - 1)/(x-1))^M
differentiate it M times(d^Nf(x)/dx^N) and the co-efficient will be (1/n!)*(d^Nf(x)/dx^N) at x = 0;
differentiation can be done using any numerical differentiation technique. So the complexity of the algorithm is O(N*complexity_of_differentiation)..

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