Why does my code fail? (ZCO14001)

Why does my solution CodeChef: Practical coding for everyone to this problem CodeChef: Practical coding for everyone fail?
It is probably something very simple, but I for one have no idea why it is wrong. Thank you very much.

Edit: In case it is of help, variable carr is true if the crane is carrying a box else it is false. Variable curr is the current position of the crane (zero-indexed).

At a guess: for cases 3 and 4, you need to move the break statement out of the body of the if (...) { ... }.

2 Likes

Yup, that’s the bug actually!

2 Likes

Also, please atleast test the sample cases before submitting your code!

1 Like

@anon40864956 Your program is giving wrong answers for the given test-case in the problem description i.e.

7 4
3 1 2 1 4 0 1
3 2 2 2 2 4 1 3 1 4 0

Correct Output: 2 1 3 1 4 0 1
Your Program Output: 2 1 2 1 4 0 1
Refer Try Online!

So the bug in the program is the break statement in cases 3 and 4. Put the break statement out of the if condition.

Updated Source-Code
#include <iostream>

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n, h;
    cin >> n;
    cin >> h;
    int arr[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int a;
    int curr = 0;
    bool carr = false;
    bool t = true;
    while (t) {
        cin >> a;
        switch (a) {
        case 1:
            if (curr != 0) curr -= 1;
            break;
        case 2:
            if (curr != n - 1) curr += 1;
            break;
        case 3:
            if (!(carr) && arr[curr] != 0) {
                carr = true;
                arr[curr] -= 1;
            }
            break;
        case 4:
            if (carr && arr[curr] < h) {
                carr = false;
                arr[curr] += 1;
            }
            break;
        default:
            t = false;
            break;
        }
    }
    for (int i = 0; i < n; i++) cout << arr[i] << ' ';
    return 0;
}

Refer the link Video Game for solution in other programming language.

Suggestion: Next time when you upload your code, do make it readable, because your code is messy even though you have formatted the code.
Writing clean and understandable code is important both as a software developer and while posting on a online forum for help.

Thanks for reading.
Peace :v:

1 Like

Thanks all! I don’t even know how I missed that.

I try to keep my code clean but for some reason my brain thinks less lines = better code. I must work on that.

Probably do not use switch, I would say :slight_smile:

1 Like