#include <bits/stdc++.h>
using namespace std;
void solve(vector<vector<long long>> &answer, vector<long long> first, int n)
{
if (n == 0)
{
return;
}
vector<long long> second;
for (int i = -1; i < first.size(); i++)
{
if (i == -1)
{
second.push_back(first[0]);
continue;
}
if (i == first.size() - 1)
{
second.push_back(first.back());
continue;
}
long long sum = first[i] + first[i + 1];
second.push_back(sum);
}
answer.push_back(second);
solve(answer, second, n - 1);
}
vector<vector<long long int>> printPascal(int n)
{
vector<vector<long long>> answer;
vector<long long> first;
first.push_back(1);
answer.push_back(first);
solve(answer, first, n - 1);
return answer;
}
int main()
{
vector<vector<long long>> answer = printPascal(5);
for (int i = 0; i < answer.size(); i++)
{
for (int j = 0; j < answer[i].size(); j++)
{
cout << answer[i][j] << " ";
}
cout << endl;
}
return 0;
}
I tried solving the issue with AI, but it just says that my approach is not good and gives me a new better code. I don’t want a better code. This approach was made by me and I just want to know why this is not working.
When I asked AI to dry run my code, it gave the correct answer, but it does not give correct answer in vs code or the platform on which I am solving it (code 360). I know the platform is disappointing, but the code should work as expected in other environments.
YOGESH DANGI is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
9
The error is here
for (int i = -1; i < first.size(); i++)
The expression i < first.size()
will always evaluates to false because the return value from vector::size
is unsigned. This is a case where C++ and regular math don’t agree, so it’s an easy mistake to make.
When comparing a signed value to an unsigned value C++ first converts the signed value to unsigned. In the case of -1
this results in the largest possible unsigned value, and this means that i < first.size()
is always false.
Here’s one way to fix this problem (this is untested)
vector<long long> second;
second.push_back(first[0]);
for (size_t i = 0; i < first.size(); i++)
{
if (i + 1 == first.size())
{
second.push_back(first.back());
continue;
}
...
In general be very careful about using signed types (e.g. int
) for vector indexes, prefer size_t
instead. Also be careful about using -
on unsigned values because of potential overflow problems. That’s why I replaced i == first.size() - 1
with i + 1 == first.size()
in the code above.
3