The Coursera autograder gives me Unknown Signal 11 - c++

I'm in a class in Algorithms and now we are taking Greedy Algorithms.
Two of my solutions output "Uknown Signal 11" on some of the test cases.
However, I drove my program to the limit with the largest inputs possible.
It works just fine on my PC. However on Coursera's grader, it throws tgghis cryptic message of Unknown Signal 11.
Will this go away if I change to Python for example?
Here's the first code exhibiting the problem:
#include <iostream>
#include <utility>
#include <algorithm>
using namespace std;
bool sortAlg(pair<double, pair<uint64_t,uint64_t>> item1, pair<double,
pair<uint64_t,uint64_t>> item2)
{
return (item1.first >= item2.first);
}
int main()
{
uint64_t n, index = 0;
double W, val;
cin >> n >> W;
pair<double, pair<uint64_t,uint64_t>> items[n];
for (int i=0; i <n; i++)
{
cin >> items[i].second.first >> items[i].second.second;
items[i].first = (double)items[i].second.first / (double)items[i].second.second;
}
sort(items,items+n, sortAlg);
while(W > 0 && n > 0)
{
if (items[index].second.second <= W)
{
val += items[index].second.first;
W -= items[index].second.second;
index++;
n--;
}
else
{
val += items[index].first * W;
W = 0;
index++;
n--;
}
}
printf("%.4f",val);
return 0;
}
I think this has to do with the while loop, but I can't think of anything where the program will make an out of bounds array call using index.
Anyways it is a fractional knapsack implementation.
Here's the second code which also gives unknown signal 11:
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
#include <utility>
using namespace std;
bool sortAlg(string num1, string num2)
{
if (num1[0] > num2[0]) return true;
else if (num1[0] < num2[0]) return false;
else
{
if (num1.size() == 1 && (num1[0] > num2[1])) return true;
else if (num1.size() == 1 && (num1[0] < num2[1])) return false;
else if (num2.size() == 1 && (num1[1] > num2[0])) return true;
else if (num2.size() == 1 && (num1[1] < num2[0])) return false;
else if (num1 == "1000" || num2 == "1000") return (num1 < num2);
else
{
if (num1.size() == num2.size()) return (num1 > num2);
else
{
return (num1[1] > num2[1]);
}
}
}
}
int main()
{
string num;
int n, n2 = 1;
cin >> n;
//int numbers[n];
vector<string> numbers2;
for (int i =0; i <n; i++)
{
num = to_string(n2);
cout << num << endl;
numbers2.push_back(num);
n2 += 10;
}
sort(numbers2.begin(), numbers2.end(), sortAlg);
for (auto number : numbers2)
{
cout << number;
}
return 0;
}
I suspect the sortAlg function used in sort function, but on my PC it is relatively fast. And the problem statement required some weird sorting.
The problem was given a set of numbers, arrange them to make thebiggest number possible.
If given 9, 98, 2, 23, 21 for example it should give me 99823221.
(9 > 98 > 23 > 2 > 21)
So I sort by the first digit then the next and so on.

You have a StackOverflow error.
The necessary stack size depends on the depth of your recursion, the number of parameters of your recursive function and on the number of local variables inside each recursive call.
In Python, you have to set the necessary stack size. The starter files provided in Python 3 would have the sample below:
import threading
sys.setrecursionlimit(10 ** 6) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
...
threading.Thread(target=main).start()
Note how the stack_size is allocated.

It's just an additional information related to Coursera grader.
In the week 6 the same course , if you declare a 2D array for the dynamic programming problem, the grader gives the Signal 11 error and program fails even if it is working perfectly fine on local machine .
Solution to above problem - replace 2-D array by 2D vector (in case of C++) and submit again. The grader will accept the code solution and no signal 11 error will be thrown.

Related

Getting SIGSEGV (segmentation error) for the given problem. (Finding LCA of a generic tree)

So, I was trying to solve the below problem using the most basic method i.e. storing the paths and finding LCA.
My code is working fine on VSCode and giving the right output. But when submitting on SPOJ, it gives runtime error (SIGSEGV).
Problem Link: https://www.spoj.com/problems/LCA/
Problem Description:
A tree is an undirected graph in which any two vertices are connected by exactly one simple path. In other words, any connected graph without cycles is a tree. - Wikipedia
The lowest common ancestor (LCA) is a concept in graph theory and computer science. Let T be a rooted tree with N nodes. The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself). - Wikipedia
Your task in this problem is to find the LCA of any two given nodes v and w in a given tree T.
Sample Input:
1
7
3 2 3 4
0
3 5 6 7
0
0
0
0
2
5 7
2 7
Sample Output:
Case 1:
3
1
My Code:
#include <iostream>
#include <vector>
#include <cmath>
#include <cstring>
using namespace std;
vector<vector<int>> edges;
bool storepath(int s, int d, vector<int>& path, vector<bool>& visited) {
if(s == d)
{
path.push_back(d);
return true;
}
else if(edges[s].size() == 1) {
if(s != d)
{
for(int i = 0; i < path.size(); i++)
if(path[i] == s) {
path.erase(path.begin() + i);
}
}
return false;
}
visited[s] = true;
path.push_back(s);
for(auto e: edges[s])
{
if(visited[e] == false)
{
bool ans = storepath(e, d, path, visited);
if(ans)
break;
}
}
}
int LCA(int a, int b)
{
if(a == b)
return a;
vector<int> path1, path2;
vector<bool> visited(edges.size(), false);
storepath(1, a, path1, visited);
visited.assign(edges.size(), false);
storepath(1, b, path2, visited);
int n = path1.size();
int m = path2.size();
int i = 0,j = 0;
while(i < n && j < m && path1[i] == path2[j]) {
i++;
j++;
}
return path1[i-1];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int t;
cin >> t;
int Case = 1;
while(t--)
{
int n;
cin >> n;
edges.resize(n+1);
for(int i = 1; i <= n; i++)
{
int size, val;
cin >> size;
while(size--)
{
cin >> val;
edges[i].push_back(val);
edges[val].push_back(i);
}
}
int q;
cin >> q;
cout << "Case "<< Case << ":" << endl;
while(q--)
{
int a, b;
cin >> a >> b;
cout << LCA(a, b) << endl;
}
Case++;
edges.clear(); //added after igor's comment (forgot to add before but used while submitting)
}
return 0;
}
I think I'm not accessing any out of scope element so SIGSEGV should not occur.
Please tell me how can I fix and improve my code.
Some bugs are easy to find, when you know how to find them. The tools every programmer should know about are valgrind and -fsanitize. Remember to always compile with warnings enabled and fix them. Compiling your code with:
g++ -Wall -Wextra -fsanitize=undefined 1.cpp && ./a.out </tmp/2
results in a helpful warning:
1.cpp:38:1: warning: control reaches end of non-void function [-Wreturn-type]
38 | }
| ^
and a runtime error:
1.cpp:9:6: runtime error: execution reached the end of a value-returning function without returning a value
Your storepath doesn't return value.

Why is this code not working for big number?

I'm doing question 4.11 in Bjarne Stroustrup Programming-Principles and Practice Using C++.
Create a program to find all prime numbers in the range from 1 to max using a vector of primes in order(prime[2,3,5,...]). Here is my solution:
#include <iostream>
#include <string>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
bool check_prime(vector<int> &prime, int n) {
int count = 0;
for (int i = 0; prime[i] <= n || i <= prime.size() - 1; ++i) {
if (n % prime[i] == 0) {
count++;
break;
}
}
bool result = 0;
if (count == 0)
result = 1;
else
result = 0;
return result;
}
int main() {
vector<int> prime{2};
int max;
cout << "Please enter a max value:";
cin >> max;
for (int i = 2; i <= max; ++i) {
if (check_prime(prime, i))
prime.push_back(i);
}
for (int i = 0; i <= prime.size() - 1; ++i) {
cout << prime[i];
if (i <= prime.size() - 2)
cout << ',';
}
}
My code is working for numbers smaller than 23 but fail to work for anything bigger. If I open the program in Windows 10 the largest working number increase to 47, anything bigger than that fail to work.
This condition
prime[i]<=n||i<=prime.size()-1
makes the loop continue as long as at least one of them is true, and you're accessing prime[i] without checking the value of i.
This will cause undefined behaviour as soon as i == prime.size().
This means that anything can happen, and that you're experiencing that any specific values are working is just an unfortunate coincidence.
You need to check the boundary first, and you should only continue for as long as both conditions are true:
i <= prime.size() - 1 && prime[i] <= n
which is more idiomatically written
i < prime.size() && prime[i] <= n
(It's never too soon to get comfortable with the conventional half-open intervals.)
You check prime[i]<=n before i<=prime.size()-1. Then, if it's true (even if i>prime.size()-1, which is random behaviour), you work on it, generating wrong results.

Print all prime number lower than n in C++ ( file crash )

I wrote a C++ program that prints all prime numbers lower than n, but the program keeps crashing while executing.
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
As Igor pointed out, i is zero the first time when n%i is done. Since you want only prime numbers and the smallest prime number is 2, I suggest you initialise i to 2 instead of 0.
You want to print all prime numbers less than n and has a function to check primality already.
Just
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
And while printing, add a some character to separate the numbers inorder to be able to distinguish them like
cout<<i<<endl;
P.S: I think you call this a C++ program. Not a script.
Edit: This might interest you.

Whats wrong with my Prime number Checker?

I created a prime number checking program which checks the user entered number prime or not.
It detects non prime numbers easily, but when we type prime numbers, it crashes!
I think I know why, but don't know how to rectify them...
Here's my Program:
#include "stdafx.h"
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
Remainder(n, x + 1 > n);
/*
Here is the PROBLEM
*/
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n = Asker();
int r = Remainder(n, 2);
if (r == 1)
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
main();
return 0;
}
Suppose, when I enter 7, I know that, it checks upto 6, then it should crash!(due to x + 1 > n condition). I don't know how to return 0 when it fails the else condition...
To answer to your question "Whats wrong with my Prime number Checker?" a lot of things are wrong:
Don't call main() in main. That's not how you do recursion
int Remainder(int n, int x) and you call it with a float (cast is missing) then with a bool : Remainder(n, x + 1 > n);
Your asker doesn't need to be a float
About the recursion within main there is two reason:
With this config you'll get an endless loop;
ISO C++ forbids taking address of function '::main'
//#include "stdafx.h" //This is an invalid header.
#include <iostream>
#include<iomanip>
#include <cmath>
using namespace std;
float Asker()
{
float n;
cin >> n;
return n;
}
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0 && n>2 )//'2' have to be excluded.
//otherwise 2%2==0 can set
//'2' as a non prime which is wrong
return 1;
else if(x+1<n)
Remainder(n, x + 1);
/*
Here was the PROBLEM
Remainder(n, x + 1 > n) 'x + 1 > n ' is an invalid paramrter.
*/
else
return 0;
}
int main()
{
cout << "Enter your Number : ";
float n=Asker();
int r=1; //It is essential to initialize r to 1
if(n!=1) //Have to exclude '1'. Otherwise
//It will assign '1' as prime which is wrong
r = Remainder(n, 2);
if (r == 1 )
cout << "That Ain't Prime!\n";
else
cout << "Yep Thats Prime!\n";
//main(); //Why are you calling main again?
return 0;
}
Your first error was " #include "stdafx.h" ". Where'd you get this header?
Then inside int Remainder(int n, int x) function you used recursion and sent an invalid syntax " Remainder(n, x + 1 > n) ". You can't use syntax like x+1>n in a parameter.
After that why are you calling main() inside main function?
And your algorithm needed some touch which I have added and explained in comment.
But you should know that the shortest way to check a prime number is to check n%x==0 till x<=square_root(n).
First of all you don't have to check modulo for all numbers up to n-1: it is sufficient to check modulo up to sqrt(n). Second, you should return 0 from the function if the next divisor to check is larger than sqrt(n). Here is the corrected Remainder function.
int Remainder(int n, int x)
{
int q = n%x;
if (q == 0)
return 1;
else
{
if(x+1 > std::sqrt(n)) return 0;
else return Remainder(n, x + 1);
}
}
Finally, it is better to change the type of n in main and Asker from float to int, and return type of Asker should be int too.
This is not an exhausting list of what's wrong with the prime number checker in focus - just a way to fix it quickly. Essentially, such prime number checker shouldn't use recursion - it's more neat to just iterate over all potential divisors from 2 to sqrt(n).

debugging integer to binary code? doesnt convert 32, 64

So here is my problem, I have (what I think) is a decent section of code, it seems to work for most numbers I put in. However, when I put in a 2^x number (32 or 64 for example) it returns 10 rather than 10000000, which obviously isn't right. Any help would be greatly appreciated.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
//void thework(unsigned int num); /*was going to take this another direction and decided not to*/
int main(){
int num;
int por;
int mun;
por = 64;
cout<<"imput a number you want to convert to binary"<<endl;
cin>>num;
start:
if(num < pow(2.0,por)){ /*just to get the power widdled down to size*/
por--;
goto start;
}
/*part 2 is the "print 1" function, part 2 is the "print 0 and return to part 1, or kill section */
p2:
if((num >= (pow(2.0,por)))&&(num != 0)){
cout<<"1";
num -= pow(2,por);
por--;
goto p2;
}
p3:
if((num < pow(2,por))&&(num > (-1))){
mun=num;
if((mun -= pow(2.0,por)) > 0){
cout<<"1";
num -= pow(2.0,por);
goto p2;
}
if((mun -= pow(2.0,por)) > 0){
cout<<"0";
num -= pow(2.0,por);
por--;
goto p2;
}
return 0;
}
Here's another approach, some important details
Uses only int; using doubles is unnecessary and a source of possible error
Loop size based on sizeof.
Makes use of 0 == false, everything else == true. Simply masking the bit in question avoids the need to worry about the implementation specific behavior of right-shifting a signed value with the highest order bit set.
Doesn't use goto. Yea, goto is in the language, but only YACC can get away with it, people should not use it.
Source
#include <iostream>
using namespace std;
int main(int argc,char *argv[])
{
int num;
cout << "input a number you want to convert to binary" << endl;
cin >> num;
for(int j = sizeof(num)*8 - 1;j >= 0;j--)
{
if(num & (0x1 << j)) cout << "1";
else cout << "0";
}
cout << endl;
return 0;
}