2d arrays, functions, C -
the problem write function takes 2 dimensional array, 2 integers represent number of rows , columns in array, , prints out 2 x 2 array represents largest square in array. largest square means square sum of elements greatest in array.
given array: 1 2 3 4
5 6 7 8
9 10 11 12
output should be:
7 8
11 12
though never learned subarray/matrixes , kadane algorithm in class i've been online day , im hopping close solution? (*my professor interested in function, we're not supposed submit full program) due yesterday im lost, please if can , in advance!
/*void f(x) opens file take in given array*/ void largestsqaure(int array[row][column]) { file*ifp= fopen("largestsquare.txt", "r"); file*ofp= fopen("output.txt", "w"); for(r0w= 0; row < size; row++) fscanf(ifp, "%d", &array[row]); /*declaring variables*/ int maxsum = int_min, finalleft, finalright, finaltop, finalbottom; int left, right, i; int temp[row], sum, start, finish; /* adding left , right columns & intiializing size in loop*/ (left = 0; left < column; ++left) { memset(temp, 0, sizeof(temp)); (right = left; right < column; ++right) { /* calucalting sums in between*/ (i = 0; < row; ++i) temp[i] += array[i][right]; /* finding max subarray using kadane*/ sum = kadane(temp, &start, &finish, row); if (sum > maxsum) { maxsum = sum; finalleft = left; finalright = right; finaltop = start; finalbottom = finish; } } } /* printing 2 x 2 array had max sum*/ printf("%d, %d\n", finaltop, finalleft); printf("d, %d\n", finalbottom, finalright); system("pause"); }
#include <stdio.h> #include <limits.h> #define row 3 #define column 4 int main(void){ int a[row][column] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; int max = int_min; int max_r, max_c; int r, c; for(r=0; r < row-1; ++r){ for(c=0; c < column-1; ++c){ int sum = a[r][c] + a[r][c+1] + a[r+1][c] + a[r+1][c+1]; if(sum > max){ max = sum; max_r = r; max_c = c; } } } printf("%d %d\n", a[max_r][max_c], a[max_r][max_c+1]); printf("%d %d\n", a[max_r+1][max_c], a[max_r+1][max_c+1]); return 0; }
Comments
Post a Comment