How can this code be improved to avoid timeout with large numbers of data entries? [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
My solution to a HackerRank problem works but times out when very large amounts of data are used, such as the following: https://hr-testcases-us-east-1.s3.amazonaws.com/9403/input11.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1565703339&Signature=JcuoWT7wKxpU3GWudO4wLNWK6Dg%3D&response-content-type=text%2Fplain
I'm quite aware that the code is far from ideal, and will probably make experienced software developers cringe... so I'm hoping it can be improved.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int N;
cin >> N;
vector<int> v;
vector<string> s;
for (int i = 0; i < N; i++) {
int a;
cin >> a;
v.push_back(a);
}
int Q;
cin >> Q;
for (int i = 0; i < Q; i++) {
int a;
int b = 0;
cin >> a;
for (int j = 0; j < v.size(); j++) {
if(v[j]==a) {
s.push_back("Yes " + to_string(j+1));
b++;
j=v.size();
}
}
if (b==0) {
vector<int>::iterator low;
low = std::lower_bound(v.begin(), v.end(), a);
int d = low-v.begin();
d++;
s.push_back("No " + to_string(d));
}
}
for (int i = 0; i < s.size(); i++) {
cout << s[i] <<"\n";
}
return 0;
}
The problem statement is:
Ideally, I'd rather not have a completely new solution, but rather get some help making this one better.

First of all, it is always useful to analyze the performance of a software by profiling it with the adeguate tool, see here.
With just taking a look at is, there are a few points which you could optimize:
the s list is useless. You push back data on it and then print in order. Just print directly. You would save memory and the last for loop.
inside your second loop you first perform a linear search and then, if nothing is found, you use std::lower_bound which has logarithmic complexity. You could reduce the time by just looping once and looking for the element or the smallest one at the same time, reducing the amount of looping you need. You can also take advantage of the fact that the N integers are sorted to stop the search earlier.

Related

C++ malloc(): memory corruption [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.
When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size
In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;

Sum of the first 5 even numbers from the array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
So, I need to get the sum of the first 5 even numbers from my array, this is the code that I've got so far, have no clue what to do next. It runs, but the result is incorrect
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int niz[10];
cout << "Unesi 10 brojeva:";
for (int i = 0; i < 10; i++) {
cin >> niz[i];
}
int suma = 0;
int parni[5];
int j = 0;
for (int i = 0; i < 10; i++) {
if (niz[i] % 2 == 0) {
niz[i] == parni[j];
j++;
if (j == 5) {
break;
}
}
}
for (int i = 0; i < 5; i++) {
suma = parni[i] + suma;
}
cout << suma;
system("PAUSE");
return 0;
}
This line:
niz[i] == parni[j];
does nothing. (It tests if niz[i] happens to be equal to the current, uninitialized value of parni[j], and throws away the result of the comparison.)
You want to store niz[i] in parni[j], so do this:
parni[j] = niz[i];
Incidentally, there is a problem if there are fewer than 5 even numbers in the niz array. In that case, you still sum up all five entries of the parni array, using uninitialized values, which is Bad. One way to avoid this is to just sum up the even entries as you find them, without using a secondary array.
IE, do suma += niz[i] at the line in question, and get rid of parni altogether.
Unless you're really required to use arrays here, vectors will work much more nicely.
You can also use a couple of standard algorithms to make your life easier (especially std::copy_if and std::accumulate).
// for the moment I'll ignore the code to read the input from the user:
auto input = read_input();
auto pos = std::remove_if(input.begin(), input.end(),
[](int i) { return i % 2 != 0; });
// assume that `input` always contains at least 5 elements
pos = std::min(pos, input.begin() + 5);
sum = std::accumulate(input.begin(), pos, 0);

Hint: Missed newline ? while trying to solve the below quiz [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Problem
This is similar to the previous problem, however there will be multiple integers in the input. You have to write a computer program to read each integer and print Even if the integer is divisible by 2, else print Odd. To help further, the number of integers (T) to read will be the first input to the computer program.
Input Format:
First line of input contains count of integers: T. T>=1
After that, each line contains the integer N.
Sample Input:
2
4
5
Sample Output:
Even
Odd
Note: There should be a newline after each output. Otherwise you might end up printing EvenOdd here, which will result in wrong answer.
#include <iostream>
using namespace std;
int main()
{
int a[3];
cin>>a[0];
cin>>a[1];
cin>>a[2];
for(int i =0; i <sizeof(a)/sizeof(int); i++)
{
if (a[i]%2 == 0) cout<<"Even"<<endl;
else cout<<"Odd"<<endl;
}
return 0;
}
You don't need neither array nor vectors for this:
int main() {
int n;
cin >> n;
while(n--) {
int number;
cin >> number;
// do something with number
}
return 0;
}
Note that this structure is the most common to solve this kind of problems
your problem will be solved if you change
for(int i =0; i <sizeof(a)/sizeof(int); i++)
to
for(int i =1; i <sizeof(a)/sizeof(int); i++)
But, how'd you know the number of elemnts for the array beforehand?
To correct this, you don't declare the array statically. Take the first input, and allocate memory for that many ints.
#include <iostream>
using namespace std;
int main()
{
int a[3];
cin>>a[0];
cin>>a[1];
cin>>a[2];
for(int i =0; i <sizeof(a)/sizeof(int); i++)
{
if (a[i]%2 == 0)
cout<<"Even"<<endl;
else
cout<<"Odd"<<endl;
}
return 0;
}
this code which u posted is working perfectly bro :)

What is the shortest and most effecient way to get the result for this program? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is the code:
is there a way to make this more efficient?
efficiency is to make it shorter and faster in my case
#include <iostream>
int main()
{
int i, n, a[10], b[10];
cin >> n;
for (i = 0; i < n; i++)
{
cin >> a[i] >> b[i];
}
for (i = 0; i < n; i++)
{
if (a[i] > b[i])
cout << "Participant 1 wins\n";
else
cout << "Participant 2 wins\n";
}
return 0;
}
First of all, your code doesn't compile in most machines. Reason? cout and cin are parts of the Standard namespace std, which means that you cannot access them unless you use the appropriate commands. This can be done in two ways:
Write std::cout instead of cout. This tells the compiler that you want to access the object cout, which is a part of the standard namespace
Before the main body, write using namespace std;. This will offer you direct access to everything that belongs to the standard namespace, and is found in the headers you included.
Now let's talk about efficiency:
You don't have to use arrays. You can process the data while you read it from the standard input.
This will reduce the space complexity from O(N) to O(1). In other words, you will have constant space.
If you want your code to execute much faster, and you are familiar with C programming language, you can use C-style input and output. It less readable, but much more efficient and fast, as it is implemented in assembly (machine language).
You can reduce the length of your code by using inline if-else statement. Please note that this is not a good practice, as it makes your code very difficult to read.
Putting all together:
#include <cstdio>
int main() {
int i, n, a, b;
scanf("%d", &n);
for(i=0; i<n; ++i) {
scanf("%d %d", &a, &b);
printf("Participant %d wins\n", (a > b) ? 1 : 2);
}
return 0;
}

how to sort an array in c++ using command line turbo c++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have an exercise for sort an array in c++. I'm coding with command line programming from turbo c++.
You can use this code, it uses bubble sort algorithm.
#include <stdio.h>
#include <iostream>
using namespace std;
void sort(int *,int);
int main()
{
int arr[10] = {2,3,4,12,5,0,2,5,1,20};
sort(arr,10);
for(int i = 0;i<10;i++)
cout << arr[i] << " ";
return 0;
}
void sort(int * ar,int length)
{
for(int i = 0;i<length;i++)
{
for(int j = i;j<length;j++)
{
if(ar[j] < ar[i])
{
int swap = ar[i];
ar[i] = ar[j];
ar[j] = swap;
}
}
}
}
EDIT:
As I said it's based on the bubble algorithm. It sequentially checks the indexes from first one to last one and automatically puts the smallest number in first place, second smallest in second place and so on. You can see here or here for more information.
Here is how i did it. Hope this is what you mean.
Read the command line arguments
Convert the string to integer using atoi function
Sort using any sorting algorithm (bubble sort used here)
Print the result
To see how bubble sort works check out this.
#include<iostream.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int i,j,temp, arr[10];
for(i=1; i<argc; ++i)
{
arr[i-1] = atoi(argv[i]);
}
/* Sort the array using bubble sort alogrithm */
for(i=0; i<argc-2; ++i)
{
for(j=0; j<argc-2; ++j)
{
if(arr[j] > arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
/* Print the result */
cout<<"Sorted array : ";
for(i=0; i<argc-1; ++i)
{
cout<<" "<<arr[i];
}
return 0;
}