#include <bits/stdc++.h>
#define ll unsigned long long int
using namespace std;
ll solve(ll arr[], ll n, ll b, ll x, ll pos) {
if(n == b)
return n;
ll idx = pos - 1;
for(ll i = n -1; i >= idx; --i) {
arr[i + 1] = arr[i];
}
arr[idx] = x;
return (n + 1);
}
signed main() {
ll t;
cin >> t;
while(t--) {
ll n;
cin >> n;
ll arr[n];
ll b;
cin >> b;
for(ll i = 0; i < b; ++i) {
cin >> arr[i];
}
ll x, pos;
cin >> x >> pos;
cout << solve(arr, n, b, x, pos) << endl;
}
cout << endl;
}
Input:
1 // testcases
5 // capacity of array
3 // number of elements to be inserting
3 4 7 // array elements
8 // element to be inserting
2 // position of the element
Output:
18446744073709551615
Which is wrong. Every time I run this code, it generates a new random big number like this. I want the output to be [3, 8, 4, 7]
Please explain what is going on, and how to solve this problem. Basically, whenever I run the program, it generates an unwanted big number. I tried many posible methods, but still the problem is the same.
You need to learn how to debug your code. If you can't do that with a debugger, write a function which prints to the screen the relevant information, such as the following:
void paxDebug(const char *desc, ll arr[], ll sz, ll n, ll b, ll x, ll pos) {
cout << desc << "\n";
cout << "n = " << n << " b = " << b << " x = " << x << " pos = " << pos << "\n";
for (ll i = 0; i < sz, ++i)
cout << " arg[" << i << "] = " << arg[i];
cout << "\n==========\n";
}
This will produce something like:
<Description>
n = 9 b = 9 x = 9 p = 9
arr[0] = 9 arr[1] = 9 arr[2] = 9 arr[3] = 9 arr[4] = 9
=========
Then pepper your code with calls to this function at many different places, such as:
ll solve(ll arr[], ll n, ll b, ll x, ll pos) {
paxDebug("start solve", arr[], n, n, b, x, pos);
if(n == b)
return n;
ll idx = pos - 1;
for(ll i = n -1; i >= idx; --i) {
paxDebug("in solve loop", arr[], n, n, b, x, pos);
arr[i + 1] = arr[i];
}
paxDebug("after solve loop", arr[], n, n, b, x, pos);
arr[idx] = x;
paxDebug("just before solve return", arr[], n, n, b, x, pos);
return (n + 1);
}
This should allow you to analyse the values of those variables, an invaluable aid to diagnosing what your issue is.
And please, for the sake of those who must maintain your code in future (even if it's you six months from now), use better variable names :-)