How do I find errors in a recursive function? - c++

I'm trying to find the smallest of the biggest sum of each column of every possible permutations of a given 2D array NxN, where the values in each row can shift towards the left. For example, the array
4 6
3 7
would have 4 possibles permutations:
4 6 6 4 4 6 6 4
3 7 3 7 7 3 7 3
The biggest sum of each permutation is respectively, 13, 11, 11, 13. Thus the smallest of the biggest sums is 11. I have written a recursive function that should work, but for some reason, it only works for arrays that are smaller than 6x6... I'm new at programming, and just recently learned about recursion, any help or counsel on how to think recursively and to debug code would be greatly appreciated...
For the array 4x4
7410 1371 2665 3195
4775 4130 6499 3414
300 2092 4009 7638
5351 210 7225 7207
The answer is 18349, and my code gives me the correct answer.
However, for the array 6x6
5219 842 7793 2098 5109 2621
1372 3253 3804 5652 810 1620
4894 6792 1784 4335 4772 6656
3203 1070 4716 5335 1157 6855
5529 2767 2205 408 7516 7454
375 7036 2597 5288 937 2893
The answer should be 23733, but I've got 24176. How is this possible?
Here's my code:
#include <iostream>
using namespace std;
#define MAX_N 1000
int n, matrix[MAX_N][MAX_N], shift[MAX_N] = {0}, minSum = 100000000;
void possibTree(int position){
//Base case
if(position == n){
for (int i = 0; i < n; i++) {
// Temporary array to store the values in the row that just shifted towards the left
int temp[MAX_N] = {0};
for (int j = 0; j < n; j++) {
if(j - shift[i] < 0)
temp[n+(j-shift[i])] = matrix[i][j];
else
temp[j-shift[i]] = matrix[i][j];
}
for (int k = 0; k < n; k++)
matrix[i][k] = temp[k];
}
int max = 0;
for (int i = 0; i < n; i++) {
int temp = 0;
for (int j = 0; j < n; j++) {
temp += matrix[j][i];
}
if(temp > max)
max = temp;
}
if(minSum > max)
minSum = max;
return;
}
for (int i = 0; i < n; i++) {
shift[position] = i;
possibTree(position+1);
}
return;
}
int main() {
while(cin >> n){
memset(matrix, 0, sizeof(matrix));
memset(shift, 0, sizeof(shift));
if(n == -1) // The user enters "-1" to end the loop and terminate the program.
return 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
possibTree(0);
cout << minSum << endl;
minSum = 100000000;
}
return 0;
}

Ok I believe I understand my mistake, I have to reset the matrix to its original state at the end of each base case, when the matrices are small, the code is still capable of finding all the possible biggest sums, but when the matrices got bigger, some of the possibilities weren't generated. Here's my code:
#include <iostream>
using namespace std;
#define MAX_N 1000
int n, matrix[MAX_N][MAX_N], OrigMatrix[MAX_N][MAX_N], shift[MAX_N] = {0}, minSum = 100000000;
void possibTree(int position){
//Base case
if(position == n){
for (int i = 0; i < n; i++) {
// Temporary array to store the values in the row that just shifted towards the left
int temp[MAX_N] = {0};
for (int j = 0; j < n; j++) {
if(j - shift[i] < 0)
temp[n+(j-shift[i])] = matrix[i][j];
else
temp[j-shift[i]] = matrix[i][j];
}
for (int k = 0; k < n; k++)
matrix[i][k] = temp[k];
}
int max = 0;
for (int i = 0; i < n; i++) {
int temp = 0;
for (int j = 0; j < n; j++) {
temp += matrix[j][i];
}
if(temp > max)
max = temp;
}
if(minSum > max)
minSum = max;
//EDITS
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = OrigMatrix[i][j];
}
}
return;
}
for (int i = 0; i < n; i++) {
shift[position] = i;
possibTree(position+1);
}
return;
}
int main() {
while(cin >> n){
memset(matrix, 0, sizeof(matrix));
memset(shift, 0, sizeof(shift));
if(n == -1) // The user enters "-1" to end the loop and terminate the program.
return 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
//EDITS
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
OrigMatrix[i][j] = matrix[i][j];
}
}
possibTree(0);
cout << minSum << endl;
minSum = 100000000;
}
return 0;
}

Related

MAX_value in 2d array for each column

What is wrong with that code?
Sorry, if here bad code.
I'm need to find max value for all column in 2d dimensional of float values, then find them sum.
First of all I write values for Array, then display them at screen and tried to find max values for each column.
Photo: didn't working and correctly work
___________________
[5.7 ; 4.2 ; 5.8;]
[654.87; 5.86; 3.76;] - Work correctly
[8.54; 7.54; 8.4;]
------------------
Max value of 1 column = A[2,1] = 654.87;
Max value of 2 column = A[3,2] = 7.54;
Max value of 3 column = A[3,3] = 8.4;
___________________
[4.6 ; 2.65 ; 76.3;]
[65.64; 7.32; 76.2;] - Work not correctly
[654.8; 1.6; 5.7;]
------------------
Max value of 1 column = A[3,1] = 654.8;
Max value of 2 column = A[3,2] = 7.32;
Max value of 3 column = A[3,3] = 5.7;
#include<iostream>
#include<conio.h>
int main(void)
{
system("cls");
int N;
int suma = 0;
A:
std::cout<<"Write array size N x N : ";
std::cin>>N;
if(N>10 || N<=1)
{
system("cls");
std::cout<<"N must be <= 10 and > 1;"<<std::endl;
goto A;
}
float **A = new float *[N];
for(int i = 0; i < N; i++)
{
A[i] = new float [N];
for(int j = 0; j < N; j++)
{
std::cout<<"A["<<i+1<<"][";
std::cout<<j+1<<"] = ";
std::cin>>(*(*(A+i)+j));
}
}
system("cls");
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if(j<N-1)
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<"; ";
}
else
{
std::cout<<"A["<<i+1<<"]["<<j+1<<"] = "<<*(*(A+i)+j);
std::cout<<";"<<std::endl;
}
}
}
float *max = new float [N];
std::cout<<"------------------------------------";
std::cout<<std::endl;
for(int i = 0; i < N - (N - 1); i++)
{
for(int j = 0; j < N; j++)
{
*(max+j) = *(*(A+i)+j);
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(max+i)) < (*(*(A+j))+i) &&
(*(max+i)) != ((*(*(A+j)))+i) )
{
*(max+i) = *(*(A+j)+i);
}
}
}
for(int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if( (*(*(A+j)+i)) == (*(max+i)) )
{
std::cout<<"Max value of "<<i+1;
std::cout<<" column = ";
std::cout<<"A["<<j+1<<"]["<<i+1;
std::cout<<"] = "<<(*(max+i));
std::cout<<std::endl;
}
}
suma+=(*(max+i));
}
std::cout<<"Sum of largest value = "<<suma;
_getch();
}
Oh... sorry just a mistake in if() by which i losen more than 3.5 hour...
if( (*(max+i)) < (*(*(A+j))+i)
&&
(*(max+i)) != ((*(*(A+j)))+i) )
{...}
I changed it to:
if( (*(max + i)) < (*(*(A + j) + i))
&&
(*(max + i)) != (*(*(A + j) + i))
)
{...}
After that change all work properly

multiply two negative numbers in c++

when I tried to multiple two negative numbers the value it is zero in c++,
for example -5 * -3
the result is zero,
why?
this is my code
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void Multiply(const int v_arr[], const int m_arr[][3], int signed
o_arr[], int size)
{
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
o_arr[i] = 0;
for (int k = 0; k < 3; k++)
o_arr[i] += v_arr[k] * m_arr[k][i];
}
}
//End your code here
}
int main()
{
int n;
cin >> n;
int v_array[n];
int m_array[n][3];
int signed o_array[3];
for (int i = 0; i < n; i++) {
cin >> v_array[i];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
cin >> m_array[i][j];
}
}
//fuction
Multiply(v_array, m_array, o_array, n);
for (int j = 0; j < 3; j++) {
cout << o_array[j] << " ";
}
return 0;
}
how to fix it to get the correct result?
the input is
2
2 -3
2 -3
2 -4
Your issue is here:
for (int k = 0; k < 3; k++)
o_arr[i] += v_arr[k] * m_arr[k][i];
}
You access elements at indices 0, 1 and 2 in v_arr, but it only has 2 elements. That's Undefined Behaviour.
Assuming this is matrix*vector multiplication code, it should look like this (untested):
for (int k = 0; k < 3; k++)
o_arr[k] += v_arr[i] * m_arr[i][k];
}
Also, your loop based on j is useless. You can remove it:
void Multiply(const int v_arr[], const int m_arr[][3], int signed o_arr[], int size)
{
for(int k = 0; k < 3; k++) { //initialize output array
o_arr[k] = 0;
}
for (int i = 0; i < size; i++) {
for (int k = 0; k < 3; k++)
o_arr[k] += v_arr[i] * m_arr[i][k];
}
}

C++ 2D array index compare

I need help in a C++ for a school task.
I don't really know where the error is.
It seems like it skips the first row.
I should compare the highest value with an other row's avarage value.
Task:
In the first row of the standard input there are the count of the cities (1≤N≤1000) and the count of days (1≤M≤1000). In the following N row there are the daily forecast M temperature values (-50≤Hi,j≤50).
In the standard output's first row, you have to write the city number, which maximal forecast has to be lower than some other city's avarage temperature! If there is none you should write -1!
Example:
Input
3 5
11 11 11 11 20
18 16 12 16 20
10 15 12 10 10
The code:
#include <iostream>
using namespace std;
int main() {
int N, M;
cin >> N;
cin >> M;
int homerseklet[N][M];
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
cin >> homerseklet[i][j];
}
}
int maxh[N] = {0}, osszh[N] = {0};
for (int i = 0; i < N; i++)
{
maxh[i] = homerseklet[i][0];
for (int j = 0; j < M; j++)
{
osszh[i] = osszh[i] + homerseklet[i][j];
if (homerseklet[i][j] > maxh[i])
{
maxh[i] = homerseklet[i][j];
}
}
}
int atlag[N] = {0};
for (int i = 0; i < N; i++)
{
atlag[i] = osszh[i] / M;
}
bool van = false;
for (int i = 0; i < N; i++)
{
for(int j = 0; j < N; j++)
{
if (i != j && maxh[i] < atlag[j])
{
if (van = true)
{
cout << i + 1 << endl;
}
}
}
}
if (!van)
{
cout << -1 << endl;
}
return 0;
}

Why is my largest sub-square-matrix sum program not woring with small matrices with negtive numbers?

This program is meant to take in a square matrix of integers and outputs the largest sub-square-matrix sum.
The first line of input is an integer which indicates the dimension of the square matrix, followed by the actual matrix row-by-row.
My program works almost perfectly except it does not work when using small matrices with negative values. Can anyone help me optimise the code, I cant see where its is going wrong
Example Input1:
3
1 2 3
4 5 6
7 8 9
Output: 45
Example Input2:
3
1 2 3
4 5 6
-7 -8 -9
Output: 16
NB: Since the largest square matrix is [2 3; 5 6] which sums to 16
My code:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int Numberofelements,n,counter = 0,sum=0,result = 0,Maximumvalue = -1, *pointervalue = NULL;
int count = 0;
cin>>n;
int mat[n][n];
int TempMatrix[n][n];
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
cin>>mat[i][j];
if(mat[i][j]<0){
count++;
}
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j< n; ++j)
{
sum = sum + mat[i][j];
}
if (sum > 0 )
{
counter++;
}
sum = 0;
}
Numberofelements = counter;
for (int j = 0; j < n; j++)
{
sum = 0;
for (int i = 0; i < Numberofelements; i++)
{
sum = sum + mat[i][j];
}
TempMatrix[0][j] = sum;
for (int i=1; i<n-Numberofelements+1; i++)
{
sum = sum+(mat[i+Numberofelements-1][j] - mat[i-1][j]);
TempMatrix[i][j] = sum;
}
}
for (int i=0; i<n-Numberofelements+1; i++)
{
sum = 0;
for (int j = 0; j < Numberofelements; j++)
{
sum = sum + TempMatrix[i][j];
}
if (sum > Maximumvalue)
{
Maximumvalue = sum;
pointervalue = &(mat[i][0]);
}
for (int j = 1; j < n-Numberofelements+1; j++)
{
sum = sum + (TempMatrix[i][j+Numberofelements-1] - TempMatrix[i][j-1]);
if (sum > Maximumvalue)
{
Maximumvalue = sum;
pointervalue = &(mat[i][j]);
}
}
}
for (int i = 0; i < Numberofelements; i++)
{
for (int j = 0; j < Numberofelements; j++)
{
result+=*(pointervalue + i*n + j);
}
}
cout << result;
return 0;
}

Find a subarray of m*m (2<=m<n) having largest sum; out of an n*n int array(having +ve, -ve, 0s)

I have written a solution for the above problem but can someone please suggest an optimized way.
I have traversed through the array for count(2 to n) where count is finding subarrays of size count*count.
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] = {{1,2,3,4,5},{2,4,7,-2,1},{4,3,9,9,1},{5,2,6,8,0},{5,4,3,2,1}};
int max = 0;
int **tempStore, size;
for(int count = 2; count < n; count++)
{
for(int i = 0; i <= (n-count); i++)
{
for(int j = 0; j <= (n-count); j++)
{
int **temp = new int*[count];
for(int i = 0; i < count; ++i) {
temp[i] = new int[count];
}
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
temp[k][l] = a[i+k][j+l];
}
}
//printing fetched array
int sum = 0;
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
sum += temp[k][l];
cout<<temp[k][l]<<" ";
}cout<<endl;
}cout<<"Sum = "<<sum<<endl;
if(sum > max)
{
max = sum;
size = count;
tempStore = new int*[count];
for(int i = 0; i < count; ++i) {
tempStore[i] = new int[count];
}
//Locking the max sum array
for(int k = 0; k < count; k++)
{
for(int l = 0; l <count; l++)
{
tempStore[k][l] = temp[k][l];
}
}
}
//printing finished
cout<<"------------------\n";
//Clear temp memory
for(int i = 0; i < size; ++i) {
delete[] temp[i];
}
delete[] temp;
}
}
}
cout<<"Max sum is = "<<max<<endl;
for(int k = 0; k < size; k++)
{
for(int l = 0; l <size; l++)
{
cout<<tempStore[k][l]<<" ";
}cout<<endl;
}cout<<"-------------------------";
//Clear tempStore memory
for(int i = 0; i < size; ++i) {
delete[] tempStore[i];
}
delete[] tempStore;
Example:
1 2 3 4 5
2 4 7 -2 1
4 3 9 9 1
5 2 6 8 0
5 4 3 2 1
Output:
Max sum is = 71
2 4 7 -2
4 3 9 9
5 2 6 8
5 4 3 2
This is a problem best solved using Dynamic Programming (DP) or memoization.
Assuming n is significantly large, you will find that recalculating the sum of every possible combination of matrix will take too long, therefore if you could reuse previous calculations that would make everything much faster.
The idea is to start with the smaller matrices and calculate sum of the larger one reusing the precalculated value of the smaller ones.
long long *sub_solutions = new long long[n*n*m];
#define at(r,c,i) sub_solutions[((i)*n + (r))*n + (c)]
// Winner:
unsigned int w_row = 0, w_col = 0, w_size = 0;
// Fill first layer:
for ( int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
at(r, c, 0) = data[r][c];
if (data[r][c] > data[w_row][w_col]) {
w_row = r;
w_col = c;
}
}
}
// Fill remaining layers.
for ( int size = 1; size < m; size++) {
for ( int row = 0; row < n-size; row++) {
for (int col = 0; col < n-size; col++) {
long long sum = data[row+size][col+size];
for (int i = 0; i < size; i++) {
sum += data[row+size][col+i];
sum += data[row+i][col+size];
}
sum += at(row, col, size-1); // Reuse previous solution.
at(row, col, size) = sum;
if (sum > at(w_row, w_col, w_size)) { // Could optimize this part if you only need the sum.
w_row = row;
w_col = col;
w_size = size;
}
}
}
}
// The largest sum is of the sub_matrix starting a w_row, w_col, and has dimensions w_size+1.
long long largest = at(w_row, w_col, w_size);
delete [] sub_solutions;
This algorithm has complexity: O(n*n*m*m) or more precisely: 0.5*n*(n-1)*m*(m-1). (Now I haven't tested this so please let me know if there are any bugs.)
Try this one (using naive approach, will be easier to get the idea):
#include <iostream>
#include<vector>
using namespace std;
int main( )
{
int n = 5; //Size of array, you may take a dynamic array as well
int a[5][5] =
{{2,1,8,9,0},{2,4,7,-2,1},{5,4,3,2,1},{3,4,9,9,2},{5,2,6,8,0}};
int sum, partsum;
int i, j, k, m;
sum = -999999; // presume minimum part sum
for (i = 0; i < n; i++) {
partsum = 0;
m = sizeof(a[i])/sizeof(int);
for (j = 0; j < m; j++) {
partsum += a[i][j];
}
if (partsum > sum) {
k = i;
sum = partsum;
}
}
// print subarray having largest sum
m = sizeof(a[k])/sizeof(int); // m needs to be recomputed
for (j = 0; j < m - 1; j++) {
cout << a[k][j] << ", ";
}
cout << a[k][m - 1] <<"\nmax part sum = " << sum << endl;
return 0;
}
With a cumulative sum, you may compute partial sum in constant time
std::vector<std::vector<int>>
compute_cumulative(const std::vector<std::vector<int>>& m)
{
std::vector<std::vector<int>> res(m.size() + 1, std::vector<int>(m.size() + 1));
for (std::size_t i = 0; i != m.size(); ++i) {
for (std::size_t j = 0; j != m.size(); ++j) {
res[i + 1][j + 1] = m[i][j] - res[i][j]
+ res[i + 1][j] + res[i][j + 1];
}
}
return res;
}
int compute_partial_sum(const std::vector<std::vector<int>>& cumulative, std::size_t i, std::size_t j, std::size_t size)
{
return cumulative[i][j] + cumulative[i + size][j + size]
- cumulative[i][j + size] - cumulative[i + size][j];
}
live example