How to fix the segmentation error in the code? - c++

Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
Explanation
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int i, j;
int arr[i][j];
int x1 = 0, x2 = 0;
for (i = 1; i <= n; ++i)
{
for (j = 1; j <= n; ++j)
{
cin >> arr[i][j];
}
}
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
if (i == j)
x1 = x1 + arr[i][j];
}
}
for (i = 1; i <= n; i++)
{
for (j = n; j <= 1; j--)
{
x2 = x2 + arr[i][j];
}
}
cout << abs(x1 - x2);
}

Here is your corrected code:
1) First, you've declared a 2D array of garbage size.
2) Second, array indexing starts from 0 in most of the programming languages except MATLAB.
3) Always use pre-increment until and unless post-increment isn't absolutely necessary.
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int i, j;
int arr[n][n];
int x1 = 0, x2 = 0;
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
cin >> arr[i][j];
}
}
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
if (i == j)
x1 += arr[i][j];
}
}
for (i = 0; i < n; ++i)
{
for (j = 0; j < n; ++j)
{
if(i + j == n - 1)
x2 += arr[i][j];
}
}
cout << abs(x1 - x2);
return 0;
}
PS: There is a lot of scope of improvement in your code formatting.

Related

How to display this pyramid of numbers?

I have this task:
A user inputs a number N and you have to output this pyramid:
0
101
21012
.......
N.21012.N
For N=5 it will be :
0
101
21012
3210123
432101234
54321012345
I managed to only get it working for N<10 with this code:
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
for (int j = 0; j < n - i; j++)
cout << " ";
int dir = -1;
for (int k = i; k <= i; k += dir) {
cout << k;
if (k == 0)
dir = 1;
}
cout << endl;
}
For N=10 it will look like this :
0
101
21012
3210123
432101234
54321012345
6543210123456
765432101234567
87654321012345678
9876543210123456789
10987654321012345678910
After the answers I settled on this :
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
int n, spaces;
string number;
cin >> n;
if (n < 10)
spaces = n;
else
{
spaces = 9;
int pwr = 0, k = n;
while (k > 9)
{
pwr++;
k /= 10;
}
for (int i = 1; i < pwr; i++)
{
spaces += pow(10, i) * 9 * (i + 1);
}
spaces += (n - pow(10, pwr) + 1) * (pwr + 1);
}
// cout << spaces << endl;
for (int i = 0; i < n + 1; i++)
{
for (int j = i; j > -1; j--)
number += to_string(j);
int len = number.length() - 1;
for (int j = 0; j < spaces - len; j++)
cout << " ";
for (int j = 1; j <= i; j++)
number += to_string(j);
cout << number << endl;
number.clear();
}
cout << endl;
return 0;
}
int padding(int n) {
constexpr auto singleDigitNumbersCount = 9;
constexpr auto doubleDigitNumbersCount = 90; // from 10 to 99
if (n < 10) return n;
if (n < 100) return 2*n - singleDigitNumbersCount;
return 3*n - doubleDigitNumbersCount - 2*singleDigitNumbersCount;
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n + 1; i++) {
std::cout << std::string(padding(n) - padding(i), ' ');
for (int k = i; k >= 0; k--) {
cout << k;
}
for (int k = 1; k <= i; k++) {
cout << k;
}
cout << '\n';
}
return 0;
}
https://godbolt.org/z/EEaeWEvf4
I made this a bit ago Compiler Explorer
Not sure if that'd help 🤔
Here is the working code:
#include <string>
#include <iostream>
using namespace std;
#define MAX_SPACE 50
int main()
{
int n;
cin >> n;
string output = "";
for (int i = 0; i < n + 1; i++)
{
for (int k = i; k >= 0; k--) {
output += to_string(k);
}
for (int k = 1; k <= i; k++) {
output += to_string(k);
}
for (uint8_t i = 0, max = MAX_SPACE - output.length() / 2.00; i < max; i++) // Print max spaces minus the integer length divided by 2
{
cout << " ";
}
cout << output << endl; // Print number
output = "";
}
return 0;
}

How do I find errors in a recursive function?

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;
}

C++ Dijkstra's algorithm program with initial vertices problem and resulting one less vertex

I'm working on C++ representation/implementation of Dijkstra's algorithm and I found this program online which fails to execute properly on TurboC++.
Any one know the solution? I also want to know why there is a minimum value of 31999 and the coding runs on a mobile emulator but refuses to run on PC TurboC++
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
//using namespace std;
int shortest(int, int);
int cost[10][10], dist[20], i, j, n, k, m, S[20], v, totcost, path[20], p;
int main()
{
int c;
cout << "enter no of vertices";
cin >> n;
cout << "enter no of edges";
cin >> m;
cout << "\nenter\nEDGE Cost\n";
for (k = 1; k <= m; k++)
{
cin >> i >> j >> c;
cost[i][j] = c;
}
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
if (cost[i][j] == 0)
cost[i][j] = 31999;
cout << "enter initial vertex";
cin >> v;
cout << v << "\n";
shortest(v, n);
}
int shortest(int v, int n)
{
int min;
for (i = 1; i <= n; i++)
{
S[i] = 0;
dist[i] = cost[v][i];
}
path[++p] = v;
S[v] = 1;
dist[v] = 0;
for (i = 2; i <= n - 1; i++)
{
k = -1;
min = 31999;
for (j = 1; j <= n; j++)
{
if (dist[j] < min && S[j] != 1)
{
min = dist[j];
k = j;
}
}
if (cost[v][k] <= dist[k])
p = 1;
path[++p] = k;
for (j = 1; j <= p; j++)
cout << path[j];
cout << "\n";
//cout <<k;
S[k] = 1;
for (j = 1; j <= n; j++)
if (cost[k][j] != 31999 && dist[j] >= dist[k] + cost[k][j] && S[j] != 1)
dist[j] = dist[k] + cost[k][j];
}
}
Arrays are 0 based so all the loops from 1 to <= n are suspect.

Fill an array diagonally

I have following program. with Input 3 5
3 rows
5 growth of numbers
The output should be:
1 2 4 7 10
3 5 8 11 13
6 9 12 14 15
But my program gives:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
Here is what I have tried so far
int main() {
int n, m, c = 0;
cin >> n >> m;
int a[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = ++c;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cout << setw(4) << a[i][j];
cout << endl;
}
}
What I am doing wrong or missing?
About the spaces: Can't find reason for such behavior(first spaces are ignored), displayed on screenshot. Tried to run in different IDE's with different compilers and had such problem only in testing system.
Hi try to use tab instead.
#include <iostream>
using namespace std;
int main() {
int n, m, c = 0;
cin >> n >> m;
int *a = new int[n * m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i * n + j] = ++c;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
cout << "\t" << a[i * n + j];
cout << endl;
}
delete[] a;
return 0;
}
Can't remember how I solved this problem in secondary school, but with n less than m, the following code works:
#include <iostream>
using namespace std;
void nextij(long n,long m,long& i,long& j) {
if (i==n-1) { //bottom row
if (j<n-1) { //in the left square
j = i+j+1;
i = 0;
}
else { //out of the left square
i = j-(n-1)+1;
j = m-1;
}
}
else { //other rows
if (j==0) { //left most column
j = i+1;
i = 0;
}
else { //other columns
i++;
j--;
}
}
}
int main() {
long n = 3;
long m = 5;
long a[3][5];
long i = 0;
long j = 0;
long c = 1;
while (c<=n*m) {
a[i][j] = c;
nextij(n,m,i,j);
c++;
}
for (i=0; i<n; i++) {
for (j=0; j<m; j++)
cout <<a[i][j] <<" ";
cout <<endl;
}
}
/*
output:
1 2 4 7 10
3 5 8 11 13
6 9 12 14 15
*/

getting WA when I try to submit mkbudget spoj

I cannot understand/think of a case where my code fails to give correct output.
Link to the problem: http://www.spoj.pl/problems/MKBUDGET/
The problem clearly has a DP solution. I am posting my solution below:
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<vector <int> > opt;
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++) //num of months
for(int j = A[i]; j <= max_a; j++) //num of workers for ith month >=A[i] and <= max_a
{
opt[i][j] = opt[i-1][A[i-1]] + j*sal + (A[i] > A[i-1] ? (A[i]-A[i-1])*hire : (A[i-1] - A[i])*fire);
for(int k = A[i-1]; k <= max_a; k++)
opt[i][j] = min(opt[i][j], opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
int ans(vector<int> A, int n, int max_a)
{
int ret = opt[n-1][A[n-1]];
for(int i = A[n-1]; i <= max_a; i++)
ret = min (ret, opt[n-1][i]);
return ret;
}
int main()
{
vector<int> A;
int n, hire, fire, sal,max_a, c = 1;
while(1)
{
cin >> n;
if(n == 0)
break;
A.clear();
opt.clear();
max_a = 0;
cin >> hire >> sal >> fire;
A.resize(n);
for(int i = 0; i < n; i++)
{cin >> A[i];
max_a = max(max_a,A[i]);
}
opt.resize(n);
for(int i = 0; i < n; i++)
opt[i].resize(max_a + 2);
compute_opt(A,n,hire,fire,sal,max_a);
cout << "Case " << c << ", cost = $" << ans(A,n,max_a) << endl;
c++;
}
return 0;
}
I am getting correct answers for the two sample test cases but I get a WA when I submit. Any help ?
OK, so your problem is that you disallow the case where you hire any number of employees between A[i] and A[i - 1]. Maybe it's a good idea to fire some unneeded employees, but not all. That's why you get WA. I modified your code and got it accepted:
void compute_opt(vector<int> A,int n,int hire,int fire,int sal,int max_a)
{
// Fill all disallowed entries with infinity
for (int i = 0; i < A[0]; ++i)
opt[0][i] = 1000000000;
for(int i = A[0]; i <= max_a; i++) //for num workers in 1st month
opt[0][i] = i*(hire + sal);
for(int i = 1; i < n; i++)
for(int j = 0; j <= max_a; j++)
{
// No need for special case handling,
//just check all previous numbers of employees
opt[i][j] = 1000000000;
if (A[i] > j) continue;
for(int k = 0; k <= max_a; k++)
opt[i][j] = min(opt[i][j],
opt[i-1][k] + j*sal + (j>k ? (j-k)*hire : (k-j)*fire));
}
}
By the way, there's a "greedier" solution than the one you have that does not depend on the number of employees being small (so that the table can be allocated).