Wednesday, June 22, 2011

Given a 1D Array (linear) , you have to convert it in to 2D array & then find sum of each column.you have given number of rows K & number of elemnets N in array.

You are given a 1D array of integers, such as: int[] array = [3,4,7,2,2,6,0,9];
Suppose you need to treat this array as a 2D table with a given number of rows.
You want to sum the columns of the table.One value of numRows is 4..in that case the resultant array would look like

what if numRows==4?
3 4
7 2
2 6
0 9
—-
12 21

Data Structure : 2D Array


Algorithm:
1.As we have given Number of elements N in array & number of rows k to make 2D
Array we can easily find out number of column C=N/k
2.Then using two for loop down the 2D array 1st loop run for coumns & inner loop
work for rows.(A Tricky Mind Needed here although so Simple
).as in inner loop
we will increment by value of column we get.

Working Code:

#include
#include
using namespace std;
int main()
{
int i=0,j=0,k=0,sum=0;
int r=3;//row
int a[]={3,4,7,2,2,6,0,9,5,8,11};
int n=sizeof(a)/sizeof(int);
j=n/r;//column

while(k {
for(i=k;i {
sum=sum+a[i];
}
cout< sum=0;
k++;
}

return 0;
}

Time Complexity O(column*row)=O(N) see above relation C=N/r
Space Complexity O(1)
Run Here https://ideone.com/RWjEf

No comments :