// C++ program to calculate prefix sum of 3d array
#include <bits/stdc++.h>
using namespace std;
// Declaring size of the array
#define L 4 //Layer
#define R 4 //Row
#define C 4 //Column
// Calculating prefix
void prefixSum3d(int array[L][R][C])
{
int prefix[L][R][C];
prefix[0][0][0] = array[0][0][0];
// Step 1: Filling the first row,column, and pile of ceils.
// Using prefix sum of 1d array
for (int i = 1; i < L; i++)
prefix[i][0][0] = prefix[i - 1][0][0] + array[i][0][0];
for (int i = 1; i < R; i++)
prefix[0][i][0] = prefix[0][i - 1][0] + array[0][i][0];
for (int i = 1; i < C; i++)
prefix[0][0][i] = prefix[0][0][i - 1] + array[0][0][i];
// Step 2: Filling the cells of sides(made up using cells)
// which have common element array[0][0][0].
// using prefix sum on 2d array
for (int k = 1; k < L; k++)
{
for (int i = 1; i < R; i++)
{
prefix[k][i][0] = array[k][i][0]
+ prefix[k - 1][i][0] + prefix[k][i - 1][0]
- prefix[k - 1][i - 1][0];
}
}
for (int i = 1; i < R; i++)
{
for (int j = 1; j < C; j++)
{
prefix[0][i][j] = array[0][i][j]
+ prefix[0][i - 1][j] + prefix[0][i][j - 1]
- prefix[0][i - 1][j - 1];
}
}
for (int j = 1; j < C; j++)
{
for (int k = 1; k < L; k++)
{
prefix[k][0][j] = array[k][0][j]
+ prefix[k - 1][0][j] + prefix[k][0][j - 1]
- prefix[k - 1][0][j - 1];
}
}
// Step 3: Filling value in remaining cells using formula
for (int k = 1; k < L; k++)
{
for (int i = 1; i < R; i++)
{
for (int j = 1; j < C; j++)
{
prefix[k][i][j] = array[k][i][j]
+ prefix[k - 1][i][j]
+ prefix[k][i - 1][j]
+ prefix[k][i][j - 1]
- prefix[k - 1][i - 1][j]
- prefix[k][i - 1][j - 1]
- prefix[k - 1][i][j - 1]
+ prefix[k - 1][i - 1][j - 1];
}
}
}
// Displaying final prefix sum of array
cout << "prefix sum is:" << endl << endl;
for (int k = 0; k < L; k++)
{
cout << "Layer " << k + 1 << ":" << endl;
for (int i = 0; i < R; i++)
{
for (int j = 0; j < C; j++)
{
cout << prefix[k][i][j] << " ";
}
cout << endl;
}
cout << endl;
}
}
// Driver program to test above function
int main()
{
int array[L][R][C] = {
{{2, 2, 2, 2}, //Layer 1
{2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2}},
{{2, 2, 2, 2}, //Layer 2
{2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2}},
{{2, 2, 2, 2}, //Layer 3
{2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2}},
{{2, 2, 2, 2}, //Layer 4
{2, 2, 2, 2},
{2, 2, 2, 2},
{2, 2, 2, 2}}
};
prefixSum3d(array);
return 0;
}
0 Comments
If you have any doubt let me know.