Maximum sized square sub-matrix - c

I have a matrix of size N*M filled with 0's and 1's.
For each query K, I have to answer the maximum sized square sub-matrix in which minimum(number of 1's, number of 0's)=k where 1<=K<=10^9. For example consider the matrix of size 8*8:
10000000
01000000
00000000
00000000
00000000
00000000
00000000
00000000
k= 1 answer= 7
k=2 answer= 8
k=0 answer= 6
k=1001 answer= 8
I understood that for k=1, the sub-matrix (1,1) to (7,7) works for k=2, the largest square sub-matrix is the original matrix itself.
For k=1, we have to get all the 7*7 square sub-matrix. Find their min(no. of 1's,no. of 0's) and then get the minimum of all those as the answer.
I am not able to generate all the pairs of square sub-matrix. Can anyone help me in achieving that? Also, if any shorter way is available, that will be good as well because this takes very much time.

Is this an interview question? This problem is very similar to that of the maximum submatrix sum (https://www.geeksforgeeks.org/maximum-sum-rectangle-in-a-2d-matrix-dp-27/), whose DP solution you should be able to adapt for this.
EDIT:
The following is O(n^3) time O(n^2) memory
The import piece to realize is that the area D = Entire Area - B - C + A
| A B |
| C D |
#include <stdlib.h>
#include <stdio.h>
int **create_dp(int **matrix, int **dp, int row, int col) {
dp[0][0] = matrix[0][0];
for (int i = 1; i < row; ++i)
dp[i][0] = matrix[i][0] + dp[i - 1][0];
for (int j = 1; j < col; ++j)
dp[0][j] = matrix[0][j] + dp[0][j - 1];
for (int i = 1; i < row; ++i)
for (int j = 1; j < col; ++j)
dp[i][j] = dp[i - 1][j] + dp[i][j - 1] + matrix[i][j] - dp[i - 1][j - 1];
}
int min(int x, int y) {
if (x > y) return y;
return x;
}
int max_square_submatrix(int **matrix, int row, int col, int query) {
// the value dp[i][j] is the sum of all values in matrix up to i, j
// i.e. dp[1][1] = matrix[0][0] + matrix[1][0] + matrix[0][1] + matrix[1][1]
int **dp = malloc(sizeof(int*) * row);
for (int i = 0; i < row; ++i) dp[i] = malloc(sizeof(int) * col);
create_dp(matrix, dp, row, col);
int global_max_size = 0;
// go through all squares in matrix
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
// begin creating square matrices
// this is the largest size a square matrix could have
int max_size = min(row - i, col - j) - 1;
for (; max_size >= 0; --max_size) {
// you need to see above diagram in order to visualize this step
int num_ones = dp[i + max_size][j + max_size];
if (i > 0 && j > 0)
num_ones += -dp[i + max_size][j - 1] - dp[i - 1][j + max_size] + dp[i - 1][j - 1];
else if (j > 0)
num_ones += -dp[i + max_size][j - 1];
else if (i > 0)
num_ones += -dp[i - 1][j + max_size];
if (num_ones <= query) break;
}
if (global_max_size < max_size + 1) global_max_size = max_size + 1;
}
}
// free dp memory here
return global_max_size;
}
int main() {
#define N 8
#define M 8
int **matrix = malloc(sizeof(int*) * N);
for (int i = 0; i < N; ++i) matrix[i] = malloc(sizeof(int) * M);
for (int i = 0; i < N; ++i)
for (int j = 0; j < M; ++j)
matrix[i][j] = 0;
matrix[0][0] = matrix[1][1] = 1;
printf("%d\n", max_square_submatrix(matrix, 8, 8, 1));
printf("%d\n", max_square_submatrix(matrix, 8, 8, 2));
printf("%d\n", max_square_submatrix(matrix, 8, 8, 0));
printf("%d\n", max_square_submatrix(matrix, 8, 8, 1001));
}

Related

How to matrix inversion For 1 Dimension with c code?

hello i used gauss jordan for 1d but i didnt
i want to find 1d matrix inverse. I found determinant but i dont know inverse of this matrix
Hello my dear friends
Our matrixes:
double A[] = {6, 6 ,2, 4, 9 ,7, 4, 3 ,3};
double B[] = {6, 6 ,2, 4, 9 ,7, 4, 3 ,3};
double Final[9];
Function to calculate determinant:
int Inverse(double *A, double *C, int N){
int n = N;
int i, j, k;
float a[10][10] = { 0.0 };
double C[9] = { 0.0 };
float pivot = 0.0;
float factor = 0.0;
double sum = 0.0; ``` variables
for (k = 1; k <= n - 1; k++)
{
if (a[k][k] == 0.0)
{
printf("error");
}
else
{
pivot = a[k][k];
for (j = k; j <= n + 1; j++)
a[k][j] = a[k][j] / pivot;
for (i = k + 1; i <= n; i++)
{
factor = a[i][k];
for (j = k; j <= n + 1; j++)
{
a[i][j] = a[i][j] - factor * a[k][j];
}
}
}
if (a[n][n] == 0)
printf("error");
else
{
C[n] = a[n][n + 1] / a[n][n];
for (i = n - 1; i >= 1; i--)
{
sum = 0.0;
for (j = i + 1; j <= n; j++)
sum = sum + a[i][j] * C[j];
C[i] = (a[i][n + 1] - sum) / a[i][i];
}
}
}
for (i = 1; i <= n; i++)
{
printf("\n\tx[%1d]=%10.4f", i, C[i]);
}
system("PAUSE");
return 0;
}
Although I tried very hard, I couldn't find the opposite in c programming for a 1x1 dimensional matrix. Output always generates 0. Can you help me where I could be making a mistake. Thank you.
It appears you are using C as an output parameter (to store the inverse); however, you also declare a local variable of the same name in the function. This causes the local variable to shadow (i.e.: hide) the output parameter; thus, changes you make to the C in the function do not affect the C the calling function sees.
To fix this issue, you need to remove the line double C[9] = {0}; from your function.

Interleaving array in C

I posted earlier, but I did not properly format or add my code. Say I have an int array x = [1,2,3]. Given a value i, I want to create an array x^i, such that, if i = 3, array x^i = [1,1,1,2,2,2,3,3,3]. If i = 5, array x^i = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5]. I am dynamically allocating memory for this.
However, my code for i = 3 is creating an array = [1,2,3,1,2,3,1,2,3]. I've tried many different things, and I got something like [1,1,1,1,1,1,1,1,1] or [3,3,3,3,3,3,3,3,3] but never the correct answer.
Here is my code:
void binary_search(int size_a, int * A, int size_x, int *X, int max_i, int min_i){
int i, j, k, count = 0, max_repeat = 0;
while(min_i <= max_i){
int repeats = (max_i + min_i)/2;
int * temp = realloc(X, size_x * sizeof(int) * repeats);
X = temp;
for(k = 0; k < size_x; ++k){
int idx = size_x - k -1;
temp = &X[idx];
for(j = 0; j < repeats; ++j){
X[idx * repeats + j] = *temp;
}
}
printf("New X: ");
for(i = 0; i < size_x * repeats; i++){
printf("%d ", X[i]);
}
int count = 0;
for(i = 0; i < size_x * repeats; i++){
for(j = 0; j < size_a; j++){
if(A[j] == X[i]){
count++;
i++;
}
}
}
if (count == size_x * repeats){
printf("Low: %d Mid %d High % d Passes\n", min_i, repeats, max_i);
min_i = repeats + 1;
}
else
printf("Low: %d Mid %d High % d Fails\n", min_i, repeats, max_i);
max_i = repeats - 1;
}
}
the variable repeats represents the value i in x^i.
The output is this:
Old X: 1 2 3
New X: 1 1 1 2 2 2 3 3 3 Low: 0 Mid 3 High 6 Fails
New X: 1 1 1 Low: 0 Mid 1 High 2 Fails
New X: Low: 0 Mid 0 High 0 Fails
The first iteration is correct, however, the second iteration should not be [1,1,1], it should be [1,2,3].
Where am I going wrong?
Here you go:
int misleading_function_names_is_bad_practice(size_t xsize, int x[xsize], size_t i)
{
void * const tmp = realloc(x, xsize * sizeof(*x) * i);
if (tmp == NULL) {
return -__LINE__;
}
x = tmp;
for (size_t k = 0; k < xsize; ++k) {
// index of the last original digit counting down
const size_t idx = xsize - k - 1;
const int tmp = x[idx];
for (size_t l = 0; l < i; ++l) {
// fill from the back
x[idx * i + l] = tmp;
}
}
return 0;
}
Live example available at onlinegdb.

Inverse of a binary matrix in C

I have a binary matrix (zeros and ones) D[][] of dimension nxn where n is large (approximately around 1500 - 2000). I want to find the inverse of this matrix in C.
Since I'm new to C, I started with a 3 x 3 matrix and working around to generalize it to N x N. This works for int values, however since I'm working with binary 1's and 0's. In this implementation, I need unsigned int values.
I could find many solutions for int values but I didn't come across any solution for unsigned int. I'd like to find the inverse of a N x N binary matrix without using any external libraries like blas/lapack. It'd be great if anyone could provide a lead on M x N matrix.
Please note that I need inverse of a matrix, not the pseudo-inverse.
/* To find the inverse of a matrix using LU decomposition */
/* standard Headers */
#include<math.h>
#include<stdio.h>
int main() {
/* Variable declarations */
int i,j;
unsigned int n,m;
unsigned int rows,cols;
unsigned int D[3][3], d[3], C[3][3];
unsigned int x, s[3][3];
unsigned int y[3];
void LU();
n = 2;
rows=3;cols=3;
/* the matrix to be inverted */
D[0][0] = 1;
D[0][1] = 1;
D[0][2] = 0;
D[1][0] = 0;
D[1][1] = 1;
D[1][2] = 0;
D[2][0] = 1;
D[2][1] = 1;
D[2][2] = 1;
/* Store the matrix value for camparison later.
this is just to check the results, we don't need this
array for the program to work */
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++) {
C[m][j] = D[m][j];
}
}
/* Call a sub-function to calculate the LU decomposed matrix. Note that
we pass the two dimensional array [D] to the function and get it back */
LU(D, n);
printf(" \n");
printf("The matrix LU decomposed \n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
printf(" %d \t", D[m][j]);
}
printf("\n");
}
/* TO FIND THE INVERSE */
/* to find the inverse we solve [D][y]=[d] with only one element in
the [d] array put equal to one at a time */
for (m = 0; m <= rows-1; m++) {
d[0] = 0;
d[1] = 0;
d[2] = 0;
d[m] = 1;
for (i = 0; i <= n; i++) {
x = 0;
for (j = 0; j <= i - 1; j++){
x = x + D[i][j] * y[j];
}
y[i] = (d[i] - x);
}
for (i = n; i >= 0; i--) {
x = 0;
for (j = i + 1; j <= n; j++) {
x = x + D[i][j] * s[j][m];
}
s[i][m] = (y[i] - x) / D[i][i];
}
}
/* Print the inverse matrix */
printf("The Inverse Matrix\n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
printf(" %d \t", s[m][j]);
}
printf("\n");
}
/* check that the product of the matrix with its iverse results
is indeed a unit matrix */
printf("The product\n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
x = 0;
for (i = 0; i <= 2; i++) {
x = x + C[m][i] * s[i][j];
}
//printf(" %d %d %f \n", m, j, x);
printf("%d \t",x);
}
printf("\n");
}
return 0;
}
/* The function that calcualtes the LU deomposed matrix.
Note that it receives the matrix as a two dimensional array
of pointers. Any change made to [D] here will also change its
value in the main function. So there is no need of an explicit
"return" statement and the function is of type "void". */
void LU(int (*D)[3][3], int n) {
int i, j, k;
int x;
printf("The matrix \n");
for (j = 0; j <= 2; j++) {
printf(" %d %d %d \n", (*D)[j][0], (*D)[j][1], (*D)[j][2]);
}
for (k = 0; k <= n - 1; k++) {
for (j = k + 1; j <= n; j++) {
x = (*D)[j][k] / (*D)[k][k];
for (i = k; i <= n; i++) {
(*D)[j][i] = (*D)[j][i] - x * (*D)[k][i];
}
(*D)[j][k] = x;
}
}
}
This is just a sample example that I tried and I have -1 values in the inverse matrix which is my main concern. I have 1000 x 1000 matrix of binary values and the inverse should also be in binary.
The matrix:
1 1 0
0 1 0
1 1 1
The matrix LU decomposed:
1 1 0
0 1 0
1 0 1
The Inverse Matrix:
1 -1 0
0 1 0
-1 0 1
The product:
1 0 0
0 1 0
0 0 1

matrix rotation..for loop changes the value of pointer

In the final value of array only first element becomes zero and that too when it again goes to the for loop(checked using gdb)..i have mentioned the problem using comments at the bottom of code.Help me out.. I have no clue of what is going wrong.
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a, b, c;
printf("enter the size of matrix");
scanf("%d%d",&a,&b);
printf("enter the number of rotations");
scanf("%d",&c);
int *arr = malloc (sizeof(int) * a * b);
int x = (a >= b)? a : b;
printf("enter the values of matrix");
// scanning the values
for(int i = 0; i < a; i++)
{
for(int j = 0; j < b; j++)
{
scanf("%d",(arr + i * b + j));
}
printf("\n");
}
// main code starts
for(int y = 0; y < c; y++)
{
// declared a new array
int *arr1 = malloc (sizeof(int) * a * b);
for(int k = 0; k < x / 2; k++)
{
for(int i = k; i < a - k; i++)
{
for(int j = k; j < b - k; j++)
{
if (i == k && j > k)
{
*(arr1 + i * b + j - 1) = *(arr + i * b + j);
}
else if (i == a - k - 1 && j < b - k - 1)
{
*(arr1 + i * b + j + 1) = *(arr + i * b + j);
}
else if (j == k && i < a - k - 1)
{
*(arr1 + i * b + j + b) = *(arr + i * b + j);
}
else if (j == b - k - 1 && i > k)
{
*(arr1 + i * b + j - b) = *(arr + i * b + j);
}
}
}
if (x % 2 != 0 && a == b)
*(arr1 + x / 2 * b + (b / 2)) = *(arr + x / 2 * b + (b / 2));
}
// changing the old array to new array
arr = arr1;
// first value is getting printed correctly here
printf("%d\n",*(arr));
printf("%p\n",&(*arr));
free(arr1);
}
// printing the output
for(int i = 0; i < a; i++)
{
for(int j = 0; j < b; j++)
{
printf("%d ",*(arr + i * b + j));
}
printf("\n");
}
// first value is getting printed incorrectly here, outside the loop
printf("\n%d\n",*(arr));
printf("%p",&(*arr));
}
C doesn't support array assignment. You have:
int *arr = malloc (sizeof(int) * a * b);
…
int *arr1 = malloc (sizeof(int) * a * b);
…
arr = arr1;
…
free(arr1);
The assignment means you've lost your original array (memory leak) and you then invalidate your new array with the free().
Array copying requires more code — usually a function call such as memmove() or memcpy(), possibly wrapped in a function.
For example, add #include <string.h> and use this in place of the arr = arr1; assignment:
memmove(arr, arr1, sizeof(int) * a * b);
free(arr1); // No longer needed
Alternatively:
free(arr);
arr = arr1;
This code runs cleanly under valgrind on Mac OS X 10.11.5 with GCC 6.1.0 with the 'Either' or the 'Or' options for handling the array assignments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static void dump_matrix(const char *tag, int *arr, int a, int b)
{
printf("Matrix: %s\n", tag);
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
printf(" %3d", arr[i * b + j]);
putchar('\n');
}
}
int main(void)
{
int a, b, c;
printf("enter the size of matrix: ");
scanf("%d%d", &a, &b);
printf("enter the number of rotations: ");
scanf("%d", &c);
int *arr = malloc(sizeof(int) * a * b);
int x = (a >= b) ? a : b;
printf("enter the values of matrix: ");
// scanning the values
for (int i = 0; i < a; i++)
{
for (int j = 0; j < b; j++)
{
if (scanf("%d", (arr + i * b + j)) != 1)
{
fprintf(stderr, "failed to read value arr[%d][%d]\n", i, j);
return EXIT_FAILURE;
}
}
printf("\n");
}
dump_matrix("Initial input", arr, a, b);
// main code starts
for (int y = 0; y < c; y++)
{
// declared a new array
int *arr1 = malloc(sizeof(int) * a * b);
for (int k = 0; k < x / 2; k++)
{
for (int i = k; i < a - k; i++)
{
for (int j = k; j < b - k; j++)
{
if (i == k && j > k)
{
*(arr1 + i * b + j - 1) = *(arr + i * b + j);
}
else if (i == a - k - 1 && j < b - k - 1)
{
*(arr1 + i * b + j + 1) = *(arr + i * b + j);
}
else if (j == k && i < a - k - 1)
{
*(arr1 + i * b + j + b) = *(arr + i * b + j);
}
else if (j == b - k - 1 && i > k)
{
*(arr1 + i * b + j - b) = *(arr + i * b + j);
}
}
}
if (x % 2 != 0 && a == b)
*(arr1 + x / 2 * b + (b / 2)) = *(arr + x / 2 * b + (b / 2));
}
// Changing the old array to new array
// Either:
// memmove(arr, arr1, sizeof(int) * a * b);
// free(arr1);
// Or:
free(arr);
arr = arr1;
dump_matrix("After rotation", arr, a, b);
}
dump_matrix("Finished", arr, a, b);
free(arr);
return 0;
}
Note the use of the dump_matrix() function. Writing such a function once means it can be used multiple places in the code. The tag argument simplifies the use. The 'commercial grade' variant takes a FILE *fp argument too and writes to the specified file stream.
Note the error checking on the main input loop scanf(). I should also have checked the two other scanf() statements. Errors are reported on standard error, of course.
Example run:
$ ./mat31
enter the size of matrix: 3 4
enter the number of rotations: 2
enter the values of matrix: 1 2 3 4 10 11 12 13 99 98 97 96
Matrix: Initial input
1 2 3 4
10 11 12 13
99 98 97 96
Matrix: After rotation
2 3 4 13
1 12 11 96
10 99 98 97
Matrix: After rotation
3 4 13 96
2 11 12 97
1 10 99 98
Matrix: Finished
3 4 13 96
2 11 12 97
1 10 99 98
$
Whether the output is what you intended is a wholly separate discussion. This is simply not abusing the memory.

Sum of the elements on the right side of the second bisector in C

I'm trying to make a function in C that calculates the sum of the elements on the right side of a 2 dimensional square matrix. (only the 1 elements in the below comments)
So far I've got this but it's incorrect since it calculates the sum of the elements for the whole matrix:
#define N 5
int a[N][N] ={{0,0,0,0,1},
{0,0,0,1,1},
{0,0,1,1,1},
{0,1,1,1,1},
{1,1,1,1,1}};
/*
{0,0,0,0,1},
{0,0,0,1,1},
{0,0,1,1,1},
{0,1,1,1,1},
{1,1,1,1,1},
sum =
a[0][4] +
a[1][3] + a[1][4] +
a[2][2] + a[2][3] + a[2][4] +
a[3][1] + a[3][2] + a[3][3] + a[3][4] +
a[4][0] + a[4][1] + a[4][2] + a[4][3] + a[4][4]
*/
int sumSndBisRight(int a[N][N]) {
int i, j, sum = 0, k = N - 1;
for( i = 0;i < N;i++)
for( j = (N - 1);j >= 0;j--)
sum += a[i][j];
return sum;
}
void main() {
int sum;
sum = sumSndBisRight(a);
printf("%d", sum);
}
Thanks in advance for your help.
Change
for( j = (N - 1);j >= 0;j--)
to
for( j = N-1-i; j < N; j++)

Resources