Ally
Ally

Reputation: 15

Strange output C++

I was trying to solve a simple question on a coding site. I must find how many pairs are there in an array that sumed up are divisible by a given integer k. The logic in the code below is bad, I've got 100p afterwards, but I found a strange bug in the bad code.

Here it is:

#include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);

int divisibleSumPairs(int n, int k, vector<int> ar) {
    int modK[k] = {0};
    for(int i = 0; i < n; ++i)
        ++modK[ar[i] % k];
    int cnt = 0;
    ///cout << modK[0] << '\n';  <- If I uncomment this, the output is 1
    cnt += modK[0] * ((modK[0]) - 1) / 2;
    
    if(k % 2 == 0)
        cnt += (modK[k / 2] * (modK[k / 2] - 1)) / 2;
    else
        for(int i = 0; i < k / 2; ++i)
            cnt += modK[i] * modK[k - i];
        
    return cnt;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    string first_multiple_input_temp;
    getline(cin, first_multiple_input_temp);

    vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp));

    int n = stoi(first_multiple_input[0]);

    int k = stoi(first_multiple_input[1]);

    string ar_temp_temp;
    getline(cin, ar_temp_temp);

    vector<string> ar_temp = split(rtrim(ar_temp_temp));

    vector<int> ar(n);

    for (int i = 0; i < n; i++) {
        int ar_item = stoi(ar_temp[i]);

        ar[i] = ar_item;
    }

    int result = divisibleSumPairs(n, k, ar);

    fout << result << "\n";

    fout.close();

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}

vector<string> split(const string &str) {
    vector<string> tokens;

    string::size_type start = 0;
    string::size_type end = 0;

    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));

        start = end + 1;
    }

    tokens.push_back(str.substr(start));

    return tokens;
}

If I comment out cout << modK[0] << '\n';, the ouput (in an out file, not on the screen) is 65141, If I don't it is 1. Why? This is the problem:

https://www.hackerrank.com/challenges/three-month-preparation-kit-divisible-sum-pairs/problem?h_l=interview&playlist_slugs%5B%5D=preparation-kits&playlist_slugs%5B%5D=three-month-preparation-kit&playlist_slugs%5B%5D=three-month-week-one

Upvotes: 0

Views: 273

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32742

The modK[k - i] accesses out of bounds when i is 0. This should probably be modK[k - i - 1].

Upvotes: 2

Related Questions