Time limit exceed - c++

The system said: my code was time limit exceed. Is there away to shortcut my code?
I'm using vector to save nails to graph.
Input: e,n
Output: checkcase=1 => Check u adjacent with i
checkcase=2 => find nails that around u
#include <iostream>
#include <vector>
#include <list>
#include <string>
using namespace std;
int main()
{
int e, n;
string u, i;
//using vectors
vector<string> graph;
//use list
list<string>listElementsInCase2;
cin >> e;
cin >> n;
//loop for e
for (long index = 0; index < e; index++)
{
cin>>u>> i;
//add u to graph
graph.push_back(u);
//add i to graph
graph.push_back(i);
}
//Option
int checkCase;
long index;
//loop for n
while(sizeof(n))
{
cin >> checkCase;
if (checkCase == 1)
{
cin >> u >> i;
for (index = 0; index < 2 * e; index += 2)
{ //Check u adjacent ? i
if ((graph.at(index) == u) && (graph.at(index + 1) == i))
{
cout << "TRUE" << endl;
break;
}
}
if (index == 2 * e)
cout << "FALSE" << endl;
}
//checkCase=2
if (checkCase == 2)
{
cin >> u;
for (long index = 0; index < 2 * e; index += 2)
{
if (graph.at(index) == u)
listElementsInCase2.push_back(graph.at(index + 1));
}
// return 0
if (listElementsInCase2.empty() == true)
cout << "0";
else
{
while (0 < listElementsInCase2.size())
{ //find nails that around u
cout << listElementsInCase2.front();
listElementsInCase2.pop_front();
cout << " ";
}
}
cout << endl;
}
n--;
}
}
//end

You seem to have an infinite while loop in your code.
Your statement while(sizeof(n)) will never stop repeating the loop since sizeof(n) always returns the byte size of the type integer, which is always a positive number and thus always evaluates as true.
A shortcut for your code would be to replace the while loop with a for or while loop that actually ends at some point. Also sizeof is probably not the function you want.
for(int i=0; i<n; i++){ might be what you are looking for.

Related

I want to sum all my vector indexes with a recursive function but starting backwards

I am stuck with this program so far, and I don't know what else to do.
I just need help with the recursive function so I can do the other modes too, which are multiplication and subtraction.
#include "std_lib_facilities.h"
//this contains all the libraries my university offers.
int sum(vector <int> test, int i){
if (i < 0){
return 0;
}
else {
return test[i] + sum(test, i - 1);
}
}
int main(){
int n;
int x;
int mode;
int result = 0;
cout << "give the size of the vector:\n";
cin >> n;
while (n < 0){
cout << "you can't give negative number!give again:\n";
cin >> n;
}
vector <int> myvector;
for (int i = 0; i <= n-1; i++){
cout << "give numbers to fill the vector:\n";
cin >> x;
myvector.push_back(x);
}
cout << "give 1 for sum 2 for multiplication 3 for substraction\n";
cin >> mode;
while (mode < 1 && mode > 3){
cout << "this mode doesn't exist.give again:\n";
cin >> mode;
}
if (mode == 1){
result = sum(myvector, n);
cout << "result is:" << result;
}
}
I want to get all the indexes starting from backwards to sum them all.
You are accessing outside the bounds of your array.
The simple fix to your issue is to pass n-1 to your sum function.
result=sum(myvector,n - 1);
However, there is no need for you to pass n at all, rather i would suggest you add a function that starts the recursion like this. (this is a rather common pattern for recursion)
int sum(const vector<int>& test, int i);
int sum(const vector<int>& test)
{
if(test.empty())
{
return 0;
}
if(test.size() == 1)
{
return test[0];
}
return sum(test, test.size() - 1);
};
int sum(const vector<int>& test, int i)
{
if(i < 0)
{
return 0;
}
return test[i] + sum(test, i - 1);
};
then call it like sum(myvector);

Playing with Classes, Objects and Constructors / C++

I am trying to make a calculator application using c++, using a class and a constructor just to practice. I created a class including 4 functions, each for each operator. In the main function I used an if statement to choose the mathematical operator, a vector to store the inputs of the user. This vector is going to be carried out to the constructor of the class and to the functions respectively.
This is my code:
#include <iostream>
#include <vector>
using namespace std;
class Calc {
public:
Calc(vector<int> vec)
{
numbers = vec;
}
int add()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
int sub()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total - numbers[i];
}
return total;
}
int mul()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total = total * numbers[i];
}
return total;
}
int div()
{
int total = numbers[0];
for (int i = 1; i <= numbers.size(); i++)
{
total += numbers[i];
}
return total;
}
private:
vector<int> numbers;
};
int main()
{
int operation;
cout << "\nEnter the digit that corresponds to the wanted operation:\n1. +\n2. -\n3. *\n4. /\n\n";
cin >> operation;
if (operation != 1 && operation != 2 && operation != 3 && operation != 4)
{
cout << "Invalid entry.";
return 0;
}
cout << "\nEnter the numbers followed with a 0 to get the result: ";
int num = 1;
vector<int> nums;
while (num != 0)
{
cin >> num;
nums.push_back(num);
}
Calc Inputs(nums);
if (operation == 1)
{
cout << Inputs.add();
}
else if (operation == 2)
{
cout << Inputs.sub();
}
else if (operation == 3)
{
cout << Inputs.mul();
}
else if (operation == 4)
{
cout << Inputs.div();
}
else
{
cout << "Invalid entry.";
return 0;
}
}
The prgoram runs perfectly until I enter the numbers to calculate. Can anyone help me with finding out whats wrong with my code.
In C++ indexes start by 0 and go up to numbers.size() - 1.
numbers[numbers.size()]
will access the element after the last entry of the vector, aka. is out of bounds access and causes undefined behaviour, which can result in a segmentation fault.
Correct would be
for (int i = 0; i < numbers.size(); i++) { total += numbers[i]; }
or let the compiler do the hard work and use range based loops:
for(auto i : numbers) { total += i; }

Why does the code below causes Segmentation Fault (SIGSEGV)?

PROBLEM STATEMENT
You are given a strictly increasing sequence of integers A1,A2,…,AN. Your task is to compress this sequence.
The compressed form of this sequence is a sequence of ranges separated by commas (characters ','). A range is either an integer or a pair of integers separated by three dots (the string "..."). When each range a...b in the compressed form is decompressed into the subsequence (a,a+1,…,b), we should obtain the (comma-separated) sequence A again.
For each maximal contiguous subsequence (a,a+1,…,b) of A such that b≥a+2, the compressed form of A must contain the range a...b; if b≤a+1, such a sequence should not be compressed into a range. A contiguous subsequence is maximal if it cannot be extended by at least one element of A next to it. It can be proved that the compressed form of any sequence is unique (i.e. well-defined).
Input
The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one string ― the compressed form of the given sequence.
Constraints
1≤T≤100
1≤N≤100
1 ≤ Ai ≤ 1000 for each valid i
A1 < A2 < …... <AN
Subtasks
Subtask #1 (100 points): Original constraints
Example Input
3
12
1 2 3 5 6 8 9 10 11 12 15 17
4
4 5 7 8
1
4
Example Output
1...3,5,6,8...12,15,17
4,5,7,8
4
MY Code:
#include <bits/stdc++.h>
using namespace std;
bool b[1005];
int a[1005];
int main()
{
int test, i, j, size, count;
cin >> test;
while (test--)
{
for (i = 0; i < 1005; i++)
b[i] = false;
cin >> size;
for (i = 0; i < size; i++)
{
cin >> a[i];
b[a[i]] = true;
}
for (i = 0; i < 1005; i++)
{
if (b[i] == true)
{
cout << i;
j = i;
count = 0;
while (b[j] == true)
{
count++;
j++;
}
if (count > 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "..." << i - 1 << ",";
else
cout << "..." << i - 1;
}
if (count == 2)
{
i = j;
if ((j - 1) != a[size - 1])
cout << "," << i - 1 << ",";
else
cout << "," << i - 1;
}
if (count == 1 && ((j - 1) != a[size - 1]))
cout << ",";
}
}
}
return 0;
}
}
MY Question:
Above code runs perfectly on my device giving desired output. But when I am submitting this solution to
Online Judge , it says segmentation fault. It's sure that fundamentally I am accessing the memory incorrectly. Could you please show me where it is?
b is defined a bool[1005]
In this part
for(i=0 ; i<4000 ; i++)
b[i] = false;
You are writing false value 4000 times, exceeding the array size.
Overwriting past the array is allowed on the compiler but will have undefined behaviour in runtime.
In short: it can or can not cause a segfault.
Here is another approach given that the input data is in a file input.txt:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
class Reader {
public:
Reader(const std::string& filename) :
filename_(std::move(filename)), is_(filename_)
{
is_.exceptions( std::ifstream::failbit | std::ifstream::badbit );
}
int get_N() {
int N;
is_ >> N;
return N;
}
std::vector<int> get_ints(int N) {
std::vector<int> v;
v.reserve(N);
for (int i = 0; i < N; i++ ) {
int value;
is_ >> value;
v.push_back(value);
}
return v;
}
int get_num_cases() {
int num_cases;
is_ >> num_cases;
return num_cases;
}
private:
std::string filename_;
std::ifstream is_;
};
bool start_range_cur( std::vector<int> &v, int j, int N )
{
if ( j>= (N - 2) ) return false;
return ((v[j+1] - v[j]) == 1) && ((v[j+2] - v[j+1]) == 1);
}
bool in_range_cur( std::vector<int> &v, int j )
{
return (v[j+1] - v[j]) == 1;
}
void print_range( int min, int max, bool print_comma)
{
std::cout << min << ".." << max;
if (print_comma) std::cout << ",";
}
void print_single(int val, bool print_comma)
{
std::cout << val;
if (print_comma) {
std::cout << ",";
}
}
int main() {
Reader is {"input.txt"};
int num_cases = is.get_num_cases();
for (int i = 0; i < num_cases; i++) {
int N = is.get_N();
std::vector<int> v = is.get_ints(N);
bool in_range = false;
int range_start;
for( int j = 0; j< N; j++ ) {
if (in_range) {
if (j == (N - 1)) {
print_range(range_start, v[j], false);
}
else if (in_range_cur(v, j)) {
continue;
}
else {
print_range(range_start, v[j], true);
in_range = false;
}
}
else {
if (j == (N - 1)) {
print_single(v[j], false);
}
else if (start_range_cur(v, j, N)) {
in_range = true;
range_start = v[j];
}
else {
print_single(v[j], true);
}
}
}
std::cout << '\n';
}
return 0;
}

Square Root Code C++ without sqrt()

I have to create a code where the user inputs a number which is a perfect square, and I have to show its root. I've made this code, but I'm getting Segmentation Fault 11 , in this piece: int j = squareRootVector[i];
squareRoot.push_back(j);.
I can't change the code too much, so is there a way that I can do that?
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout <<
"Enter the number:\n";
int input;
int number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
cin >> number;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
cout << number << endl;
squareRootVector.push_back(divider);
}
}
for(int i = 0; i < squareRootVector.size(); i++) {
cout << squareRootVector[i] << " ";
/*******PROBLEM*******/
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
/*********************/
}
int root;
for (int i = 0; squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is: " << root << endl;
return 0;
}
The behaviour on accessing squareRootVector[i+1] with i just one below size (which your loop constaint allows) is undefined.
Consider writing
for (std::size_t i = 1; i < squareRootVector.size(); i++) {
instead, and rebasing the for loop body accordingly. I've also slipped in a change of type for i.
Shortly, the problem is that the last cycle in the last "for":
for(int i = 0; i < squareRootVector.size(); i++)
has the following line in it:
squareRootVector[i] == squareRootVector[i+1];
This is an "out of limits" error: squareRootVector only has squareRootVector.size() elements (let's say n), and the elements are indexed from 0 to n-1.
squareRootVector[i+1] in the last cycle points one element after the last one of squareRootVector, which is undefined behavior.
Using vector::iterator is proper way.
for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
if( (it+1) == squareRootVector.end() )
{
//what to do if there's no next member???
break;
}
if( *it == *(it+1) )
{
squareRoot.push_back(*it);
}
}
Thanks for the answers, guys. I've ended up with this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the number:\n";
int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
squareRootVector.push_back(divider);
}
}
int vectorSize = squareRootVector.size() - 1;
for(int i = 0; i < vectorSize; i++) {
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
}
int root = 1;
for (int i = 0; i < squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is " << root << endl;
return 0;
}

A C++ program that gets 100 integers and finds the possibly given negative ones

I'm trying to write the code for a C++ program which will get some numbers (integers) and will put them into a 100 sized array, and will begin searching for possibly given negative ones (Negative of given positive numbers) after the user had inputted the sentinel number (101). For example; when we give the integers 1, 45, 12, -32, 103, 2015 and 32 to the program, it should give us the the integer 32 (because the negative form of it is existing) and if there were no numbers with this statement, then it will prints nothing. I wrote something like below; but I don't know how to do the rest... Any help or suggestions are appreciated.
I forgot to say that I use CodeBlocks 13.12 .
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[0]= number;
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){
if (myArray[i] > 0) // I'm stuck at here!
}
return 0;
}
Thanks and please apologize for possible English mistakes.
Here are some mistakes in the code :
First, you are assigning all the input elements to the 0th indexed element of the array.
The user can very well give 200 elements without typing 101, in that case you will overrun your array size.
A simple algorithm should be like this:
Pick the ith positive element and search through out the array for its negative.
Repeat 1 for every possible positive element in the array.
Here is a working example.
The input should be like this :
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
And the checking condition:
for ( i = 0; i < nCounter; i++ ){
if (myArray[i] > 0) {
for( j = 0; j < nCounter; j++) {
if(myArray[i] + myArray[j] == 0) // positive and negative add up to 0
std::cout << myArray[i] << std::endl ;
}
}
}
Here's a slight modification of your code that will get you what you need
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i, negMatch;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){
cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
cout << "Enter the number to negative match";
cin >> negMatch;
for ( i = 0; i < nCounter; i++ ){
if ( (myArray[i] + negMatch) == 0) {
cout << myArray[i];
return 0;
}
}
return 0;
}
Please note the following changes:
You were inserting all the elements into the first slot, I changed it so that you enter them in the correct spot
Getting the number to be matched as input (negMatch is "32" in your question)
Modified the loop to check the numbers
However, this program is not ideal. Ideally, you would use something like Vectors, which can dynamically grow. Also, it might be better to have the user input the count of numbers, instead of using a sentinel number that he might want to give as input.
If I understand this correctly you want to print the negative ones but with positive sign. With this simple code you can do it!
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101;
int myArray[100];
int main (){
cout << "Please enter your numbers: " << endl;
while ( (nCounter < 100) && (number != sentinel) ) {
std::cin >> number;
myArray[nCounter]= number;
nCounter += 1;
}
for (int i = 0; i < nCounter; i++ ){
if (myArray[i] < 0) {
std::cout << (myArray[i] * -1) << std::endl ;
}
}
return 0;
}
A simple change that reduce the computational cost is the following: you can try to get information from the number given when you read it
#include <iostream>
#include <vector>
using namespace std;
int number = 0, sentinel = 101;
int main (){
cout << "Please enter your numbers: " << endl;
vector<int> array;
while (number != sentinel) {
std::cin >> number;
if(number < 0)
array.push_back(number);
}
for (int i = 0; i < array.size(); i++ )
std::cout << (array[i] * -1) << std::endl ;
return 0;
}
I suggest to write positive numbers in the beginning of the array and negative numbers in the end of the array.
Here is a demonstrative program
#include <iostream>
int main()
{
const size_t N = 100;
const int SENTINEL = 101;
int a[N];
int number;
size_t positive_end = 0;
size_t negative_begin = N;
for ( size_t i = 0; i < N && std::cin >> number && number != SENTINEL; i++ )
{
if ( number < 0 )
{
a[--negative_begin] = number;
}
else
{
a[positive_end++] = number;
}
}
if ( positive_end != 0 && negative_begin != N )
{
for ( size_t i = 0; i < positive_end; i++ )
{
size_t j = negative_begin;
while ( j != N && a[i] + a[j] != 0 ) ++j;
if ( j != N ) std::cout << a[i] << '\t' << a[j] << std::endl;
}
}
return 0;
}
If for example to enter the following sequence of numbers
1 2 -3 4 -5 6 7 3 -9 9 101
then the output will be
3 -3
9 -9
Also you could sort each part of the array (the part of positive numbers and the part of negative numbers) and apply standard algorithm std::set_intersection. In this case you could exclude situations when one negative number corresponds to several positive numbers.:)
You did not pay enough attention to the logic of your code. I'll assume you are very new at this, but no person will want to enter 100 inputs before they see what your program does.
Here is what's wrong with your code:
#include <iostream>
using namespace std;
int number = 0, nCounter = 0, sentinel = 101, i; // OK
int myArray[100]; // OK, an array with 100 elements
int main (){
cout << "Please enter your numbers: " << endl;
while ( number != 101 ){ //this is where you got it wrong
// this should have been nCounter instead of number
// If you are looking at 100 elements then the condition
// should be "nCounter != 100"
cin >> number;
myArray[0]= number; // this should have been "myArray [nCounter]=number;"
nCounter += 1;
}
for ( i = 0; i <= nCounter; i++ ){ // defining i from outer scope is unnecessary
// since it is only used in the for loop
if (myArray[i] > 0) // I'm stuck at here! // Put a semicolon here
// the remainder of the code probably here
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
//initialize size and empty array
int size = 10, x;
int myArray[10] = {};
//enter integers into array
for (int i = 0; i < size; i++)
{
cin >> myArray[i];
}
//search array for negative numbers
for (int i = 0; i < size; i++)
{
if (myArray[i] < 0)
{
x = (myArray[i] * (-1)); //multiply by -1 to get (+)
cout << x << ' ';
}
}
return 0;
}