Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
At Line 40 my code stops running and outputs signal: segmentation fault(cored dumped), and I am confused to why my code is segmentation faulting since i am not accessing any index out of bounds nor am I modifying a string literal. Baiscally, If the value (k + i) is greater than N, i want to iterate backwards until there is a spot "." in array(patches) to place either a patch "H" or "G".
Here is the the input i am taking in:
1
5 4
GHHGG
Here is the code I wrote:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
int main() {
string cows;
int CONST_N = 100000;
array<string, 100000> patches;
int t, n, k, patchCounter{}; cin >> t;
while(t--){
patchCounter = 0;
cin >> n; cin >> k;
cin >> cows;
// cout << n << endl;
for(int i = 0 ;i < CONST_N;i++){
patches[i] = "N";
}
for(int i = 0 ;i < n ;i++){
patches[i] = ".";
}
for(int i = 0; i < n ;i++){
if(cows.substr(i, 1) == "G"){
if(patches[k + i] == "N"){
for(int j = n - 1; j >=0;j++){
if(patches[j] == "."){
patches[j] = "G";
break;
}
}
} else {
patches[k+i] = "G"; i+=(2*k); patchCounter++;
}
}
}
for(int i = 0; i < n ;i++){
if(cows.substr(i,1) == "H"){
// cout<<(patches[k +i] == "N") << endl;
//cout << patches[k +i] << endl;
if(patches[k + i] == "N"){
cout << "hello";
for(int j = n - 1; j >=0;j++){
if(patches[j] == "."){
patches[j] = "H";
break;
}
}
} else {
patches[k+i] = "H"; i+=(2*k); patchCounter++;
}
}
}
cout << patchCounter << endl;
for(int i = 0 ;i < n ;i++){
cout << patches[i];
}
cout << endl;
}
return 0;
}
I was unsure what to do since array size is 10^5 and i am only accessing index 6 so i am very confused what's happening. I would really appreciate some help. Thanks!
Your code seems to have a typo, here
for (int j = n - 1; j >= 0; j++) {
if (patches[j] == ".") {
patches[j] = "H";
break;
}
}
should be
for (int j = n - 1; j >= 0; j--) { // TYPO -- not ++
if (patches[j] == ".") {
patches[j] = "H";
break;
}
}
Honestly this took me 30 seconds to discover with a debugger.
Related
The problem is to find if a given sequence of numbers can form a valid permutation or not. The problem statement is trivial for the real problem. So, I am pushing a pair of integers into the vector. The first part being the number itself and second being 0 or 1.
The code works fine till a sequence 1041 long (specific after debugging a lot). Just to debug I added a print statement after pushing each pair inside the vector. For a length of 1042, the code shows pushed 1040 and then pushed 1 (which is weird) and then just hangs on there.
I am attaching the code as well as the input and terminal output.
You can just check the main function
Code
#include <iostream>
#include <vector>
#include <algorithm>
#include <chrono>
using namespace std;
bool comparator_function(pair<int, int> a, pair<int, int> b) {
return (a.first < b.first);
}
//index_added -> the index at which the latest element was added
void set_r_array(int* r_array_ref, int* per_array_ref, int size, int* count, int index_added) {
for(int i = 1;i <= size; i++) {
count[i] = 0;
}
int temp = index_added;
while(index_added <= size) {
if(index_added == size) {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = size;
break;
}
else {
r_array_ref[temp] = -1;
break;
}
}
else {
if(per_array_ref[index_added] == 0) {
r_array_ref[temp] = index_added;
break;
}
else {
index_added++;
}
}
}
for(int i = 1;i <= size; i++) {
if(r_array_ref[i] != -1) {
count[r_array_ref[i]]++;
}
}
}
bool check_max(int* count, int next_element, int size) {
int max_count = -1, index = 0;
for(int i = 1;i <= size; i++) {
int temp_val = count[i];
if(max_count <= temp_val) {
max_count = temp_val;
index = i;
}
}
int num = 0;
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
num++;
}
}
//one max
if(num == 1) {
if(next_element == index) {
return true;
}
return false;
}
else {
for(int i = 1;i <= size; i++) {
if(count[i] == max_count) {
if(next_element == i) {
return true;
}
}
}
return false;
}
}
int main() {
int testCases;
cin >> testCases;
cin.ignore();
while(testCases-- > 0) {
int n, result_flag = 0;
cin >> n;
cin.ignore();
vector<pair<int, int>> per;
int temp;
for(int i = 0;i < n; i++) {
cin >> temp;
pair<int, int> temp_pair = make_pair(temp, i+1);
per.push_back(temp_pair);
//debug statement
cout << "pushed " << temp << endl;
}
auto start = std::chrono::high_resolution_clock::now();
cout << "start" << endl;
sort(per.begin(), per.end(), comparator_function);
int permutation_array[n+1], r_array[n+1], count[n+1];
for(int i = 0;i <= n; i++) {
permutation_array[i] = 0;
r_array[i] = i;
count[i] = 1;
}
cout << "end" << endl;
permutation_array[per[0].second] = per[0].first;
set_r_array(r_array, permutation_array, n, count, per[0].second);
//insertion of numbers
for(int i = 1;i < n; i++) {
//check if the next element inserted has the largest count rn or not
int next_element = per[i].second;
if(!check_max(count, next_element, n)) {
cout << "No" << endl;
result_flag = -1;
break;
}
permutation_array[per[i].second] = per[i].first;
set_r_array(r_array, permutation_array, n, count, per[i].second);
}
if(result_flag == 0) {
cout << "Yes" << endl;
}
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
cout << "Time: " << duration.count() << " microseconds" << endl;
}
}
Input 1
1
5
2 3 4 5 1
Output 1
pushed 2
pushed 3
pushed 4
pushed 5
pushed 1
start
end
Yes
Input 2
1
1042
1 2 3 4 ... so on till 1042
Output 2
pushed 1
pushed 2
.
.
.
pushed 1040
pushed 1
and then hangs, from here on
The complexity of the code is O(n^2). So, I don't think it has to do anything with that. Since the input can be at max 10^4 order. Moreover, according to the print debugging, I think the issue is with the input.
You have issue with input as you reach console line limit.
Put your input into a file should solve that issue.
Then you should be able to debug your algorithm which seems more complicated than needed.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My code compiled(g++) without errors and ran without errors on my system(Macos) for sample input from the website, but is showing a Runtime Error in the online judge. Please help, I'm a new programmer. This is the problem statement.
My program returns correct results for the test input data.
They haven't given the exact reason for the runtime error.
The website has this information about runtime error:
Runtime Error (RE): Your program failed during the execution (segmentation fault, floating point exception...). The exact cause is not reported to the user to avoid hacking. Be sure that your program returns a 0 code to the shell.
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <sstream>
using namespace std;
int main(){
string line;
while(getline( cin,line) && line != "" ){
istringstream split(line);
string kt,jt;
getline(split, kt, ' ');
getline(split, jt);
int k = stoi(kt);
int j = stoi(jt);
vector<int> all_cycles;
for(int i = k; i<= j; i++){
vector<int> cycle ;
int temp = i;
while(temp != 1){
cycle.push_back(temp);
if(temp %2 == 0) temp = temp /2;
else temp = (temp*3) + 1;
}
all_cycles.push_back(cycle.size() + 1 );
cycle.clear();
}
cout << k << " " << j << " " << *max_element(all_cycles.begin(), all_cycles.end()) << "\n";
all_cycles.clear();
}
return 0;
}
Code Update 1:
Replaced vectors with counters.
Fixed undefined behavior if j < k.
Submitted the updated code, still Run time error.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string line;
while(getline( cin,line) && line != "" ){
istringstream split(line);
string kt,jt;
getline(split, kt, ' ');
getline(split, jt);
int k = stoi(kt);
int j = stoi(jt);
if(k > j) {
int t = k;
k = j;
j = t;
}
int max_cycle = 0;
for(int i = k; i<= j; i++){
int cycle = 1 ;
int temp = i;
while(temp != 1){
cycle++;
if(temp %2 == 0) temp = temp /2;
else temp = (temp*3) + 1;
}
if(cycle > max_cycle) max_cycle = cycle;
}
cout << k << " " << j << " " << max_cycle << "\n";
}
return 0;
}
Code Update 2:
I replaceed string parsing the input by using formatted input and solved the newline detection problem by copying the next character of input from the streambuffer to a variable and checked if it is a newline.
This updated code seems to get rid of the Runtime Error and Now it is an output error.
Which I should be able to solve through formatting my output.
So it seems that stoi in my earlier code might have been throwing an exception during runtime.Thank you #walnut for pointing that out.
#include <iostream>
using namespace std;
int main(){
int k, j;
int eofile = 0;
while(cin >> k >> j && !eofile ){
streambuf * pbuf = cin.rdbuf();
char ch = pbuf->snextc();
if(ch == '\n') eofile = 1;
if(k > j) {
int t = k;
k = j;
j = t;
}
int max_cycle = 0;
for(int i = k; i<= j; i++){
int cycle = 1 ;
int temp = i;
while(temp != 1){
cycle++;
if(temp %2 == 0) temp = temp /2;
else temp = (temp*3) + 1;
}
if(cycle > max_cycle) max_cycle = cycle;
}
cout << k << " " << j << " " << max_cycle << "\n";
}
return 0;
}
If there is a better way to get formatted input and also detect newline, please tell me how to do it.
Solved the problem :
Program run without any errors with runtime : 0.330s
The runtime error was solved when I replaced the stoi() function with input formatting.
Finally there was an output error because I was flipping k and j to prevent undefined behavior when j < k, which I solved by formatting the output accordingly.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main(){
string line;
while(getline( cin,line) && line != "" ){
istringstream split(line);
int k,j;
split >> k >> j;
int flip = 0;
if(k > j) {
flip = 1;
int t = k;
k = j;
j = t;
}
int max_cycle = 0;
for(int i = k; i<= j; i++){
int cycle = 1 ;
int temp = i;
while(temp != 1){
cycle++;
if(temp %2 == 0) temp = temp /2;
else temp = (temp*3) + 1;
}
if(cycle > max_cycle) max_cycle = cycle;
}
if(!flip) cout << k << " " << j << " " << max_cycle << "\n";
else cout << j << " " << k << " " << max_cycle << "\n";
}
return 0;
}
Thanks to everyone for all the help.
I took a look online and none of the answers solves the problem I have comparing the elements from a vector.
I tried implementing a bool function but the problem is the same.
I am pretty new in c++ so please be patient!
PART2: First of all thank you.
So I changed my programm and created a bool function, the problem is now that it doesn get recognised before 5-6 tries.
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
vector<int> input, compareMe, randomNumbers;
const unsigned int MAX_VEKTORSTELLEN = 5;
const unsigned int UPPER_GRENZE = 49;
const unsigned int LOWER_GRENZE = 1;
unsigned int i, j;
string output;
int random, anzahlRichtige, eingabe;
bool isEqual = false;
string lotto(vector<int>)
{
if (input[i] < LOWER_GRENZE || input[i] > UPPER_GRENZE)
{
output = "Die Zahlen muessen zwischen 1 und 49 liegen! \n";
input.pop_back();
}
else if (input.size() != MAX_VEKTORSTELLEN)
output = "Es muessen 6 Zahlen uebergeben werde! \n";
else if (isEqual == true)
output = "Es duerfen keine doppelten Zahlen vorkommen! \n";
else
for (i = 0; i <= MAX_VEKTORSTELLEN; i++)
srand((unsigned)time(NULL) <= UPPER_GRENZE && (unsigned)time(NULL) > 0);
random = rand();
randomNumbers.push_back(random);
return output;
}
bool compare()
{
compareMe = input;
for (i = 0; i < input.size(); i++)
for (j = 0; j < compareMe.size(); j++)
if (compareMe[j] == input[i])
isEqual = true;
return isEqual;
}
int main()
{
cout << "insert 6 numbers: ";
while (cin >> eingabe)
{
input.push_back(eingabe);
lotto(input);
compare();
cout << output;
for (i = 0; i < input.size(); i++) //Debug
cout << input[i] << ", ";
continue;
}
for (i = 0; i < input.size(); i++)
cout << input[i];
system("pause");
return 0;
}
From line 34 to line I didn´t finish to code but doesn´t really matter because I got stuck before.
All your loops in lotto are wrong. You go one past the end of your containers.
for (i = 0; i <= input.size(); i++)
// ^ !!!
It should be <.
You got this right in main.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I got this really easy project however i got stuck in a simple issue.
User enters a number not that is larger than 99 and smaller than 1 000 000.
I am supposed to get the number of digits in that number and how many times each one occurs
E.g: 112233 = 6 digits and 3 different numbers
I was able to do the first part however my second part of part is not working.
Here is the part not working:
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}
if for example my input is 112233 the return value should be 3, however i am getting 12
if input is 1122 the return value should be 2, however i am getting 8
Here is the whole program i have written so far:
/*====================================================================================
Headers and namespace
======================================================================================*/
#include <iostream>
using namespace std;
/*====================================================================================
Prototypes list
======================================================================================*/
int getNum(int); //This function checks how many digits there are in a plate number
int getDiff(int, int); //This function checks how many different numbers are there in the plate number
/*====================================================================================
Global variables list
======================================================================================*/
int PlateNumberArray[6];
int NumberCounter[6];
/*====================================================================================
main Function
======================================================================================*/
int main()
{
//Declaring variables
int CLP;
//End of Vriables Declration
cout << endl
<< "=============================" << endl;
cout << "Enter your vehicle's plate number" << endl;
do {
cin >> CLP;
if (CLP >= 1000000)
cout << "Plate number can be no longer than 6 digits, please re-enter" << endl;
else if (CLP < 100 && CLP >= 0)
cout << "Plate number can not be less than 3 digits, please re-eneter" << endl;
else if (CLP < 0)
cout << "Plate number can not be a negative, please re-eneter" << endl;
} while (CLP >= 1000000 || CLP < 100);
int Num = getNum(CLP);
cout << getDiff(CLP, Num);
return 0;
}
/*====================================================================================
getNum Function
======================================================================================*/
int getNum(int CLP)
{
//Declaring variables
int Num;
//End of Vriables Declration
if (CLP > 99999)
Num = 6;
else if (CLP > 9999)
Num = 5;
else if (CLP > 999)
Num = 4;
else if (CLP > 99)
Num = 3;
return Num;
}
/*====================================================================================
getDiff Function
======================================================================================*/
int getDiff(int CLP, int Num)
{
int counter = 0, i = 0, j = 0;
for (int x = CLP, i = 0; x >= 1; x /= 10, i++) {
PlateNumberArray[i] = x % 10;
cout << endl
<< "Test===>" << PlateNumberArray[i] << endl;
} // end of "x = CLP" for loop
while (i < Num) {
j = 0;
while (j <= Num) {
if (PlateNumberArray[i] == PlateNumberArray[j])
NumberCounter[i]++;
j++;
} //end of while(j <= i)
i++;
} //end of while(i < Num)
for (int i = 0; i < Num; i++)
counter += NumberCounter[i];
return counter;
}
You need to reset j each time you increment i.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a question about one of my problems.
I have an array with n elements and I must see if this one is made by this rule:
positive negative positive positive negative negative positive positive positive negative negative negative
Here is my code:
// Sa se verifice daca un vector contine elementele in ordinea:
// pozitiv-negativ-pozitiv-pozitiv-negativ-negativ-pozitiv-pozitiv-pozitiv etc.
// Se va afisa DA sau NU.
#include <iostream>
using namespace std;
int main()
{
int i, j, k;
int n;
cout<<"Dati numarul de elemente: ";
cin>>n;
int v[n+1];
cout<<"Dati elementele vectorului: ";
for(i=1; i<=n; i++)
cin>>v[i];
int stop = 1;
int aici = 2;
int pozitiv, negativ;
for(int i=1; i<=n; i=i+stop)
{
for(int k=i; k<=aici/2; k++)
{
cout<<"v[k] = "<<v[k]<<endl;
if(v[k]>0)
pozitiv = 1;
else
{
pozitiv = 0;
break;
}
}
for(int j=aici/2+1; j<=aici; j++)
{
cout<<"v[j] = "<<v[j]<<endl;
if(v[j]<0)
negativ = 1;
else
{
negativ = 0;
break;
}
}
if(pozitiv == 0 && negativ == 0)
break;
stop = 2*i;
aici = aici + stop;
cout<<stop<<" "<<aici<<endl;
}
if(pozitiv == 1 && negativ == 1)
cout<<endl<<"DA!";
else cout<<endl<<"NU!";
cout<<endl;
return 0;
}
int sign(int v)
{
return (v == 0) ? 0 : ((v > 0) ? 1 : -1);
}
int check(int v[], int n) // return 1 for true, 0 for false
{
int sign = 1;
int count = 1;
int sc = 0;
for (int i = 0; i < n; i++)
{
if (sign(v[i]) != sign)
return 0;
sc++;
if (sc == count)
{
sc = 0;
if (sign == 1)
sign = -1;
else
{
sign = 1;
count++;
}
}
}
return 1;
}
int main()
{
// ... put here your code for filling v
cout << (check(v, n)) ? "DA!" : "NU!" << endl;
}
Also, you should declare v as int v[n], and fill it from v[0] to v[n-1].