I am currently working on a dynamic programming problem, and I decided code it in C++ instead of my usual Java/C# to improve my skills. However, I am getting an error that I cannot figure out. EDIT: I will post my entire solution here:
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int linecounter = 0;
int value = -1;
int differentCoins = -1;
int uniqueCoinCount = -1;
std::vector<std::vector<int>> array;
int *uniqueCoins;
int totalAmount = -1;
for (std::string line; std::getline(std::cin, line); ) {
if (linecounter % 2 == 0) {
string inputs[2];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 2){
ssin >> inputs[i];
++i;
}
cout << inputs[0];
cout << inputs[1];
totalAmount = std::stoi(inputs[0]);
uniqueCoinCount = std::stoi(inputs[1]);
uniqueCoins = new int[uniqueCoinCount + 1];
}
if (linecounter % 2 == 1) {
array.resize(uniqueCoinCount + 1, std::vector<int>(totalAmount + 1));
for (int i = 0; i < totalAmount; i++) {
array[i][0] = 0;
}
for (int i = 0; i <= uniqueCoinCount; i++) {
array[0][i] = 1;
}
stringstream ssin(line);
int coinCounter = 0;
uniqueCoins[coinCounter] = 0;
coinCounter++;
while (ssin.good() && coinCounter < uniqueCoinCount + 1){
ssin >> uniqueCoins[coinCounter];
coinCounter++;
}
for (int i = 1; i < totalAmount; i++) {
for (int j = 1; j <= uniqueCoinCount; j++) {
int totalExcludingCoin = array[i][j - 1];
if (uniqueCoins[j] <= i) {
array[i][j] = totalExcludingCoin + array[i - uniqueCoins[j]][j];
}
else {
array[i][j] = totalExcludingCoin;
}
}
}
}
linecounter++;
}
//cout << array[totalAmount][uniqueCoinCount + 1];
}
When I use cout << inputs[0]
, I can see that it prints out 4
. However, the hackerrank compiler gives me an error saying
"terminate called after throwing an instance of '
std::invalid_argument
'
what(): stoi
"
What could be the problem? I've also tried atoi()
, which returns me 40
instead of 4
, possibly due to atoi
returning 0
when it errors? Is it because it reads the null terminator or something?
Thanks
Here is the output on hackerrank:
Nice try, but you did not pass this test case. Input (stdin) 4 3 1 2 3 Your Output (stdout) 43 Expected Output 4 Compiler Message Abort Called Error (stderr) terminate called after throwing an instance of 'std::invalid_argument' what(): stoi