[Solved] What’s wrong with my code? It shows an unwanted result [closed]


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 🙂

solved What’s wrong with my code? It shows an unwanted result [closed]