what is the exact time to run a program? - c++

I want the exact time to run a program, I use it from clock(). But there is a problem that I can not give an exact time for small n like 2000.
I want it to return the correct answer for n=1000.
#include <iostream>
#include <ctime>
#include <algorithm>
using namespace std;
#define show_time(x, y) cout << endl << #x << " : " << y << endl;
int main()
{
int n;
cin >> n;
int *a = new int[n];
for(int i=0; i<n; i++)
a[i] = i;
random_shuffle(a, a+n);
int last = clock();
//STL_sort:
sort(a, a+n);
int lastP = clock();
show_time(STL_sort, (double)(lastP-last)/CLOCKS_PER_SEC);
return 0;
}
The output is 0. (Definitely 0 will not be the answer)

What platform are you running on? If you're on Windows, you could try the high-resolution time library.
If you have access to C++11, there is a header called chrono that has similar functionality, and is portable (ish)!

Related

Declaring sqrt(var) as a compile time constant in c++

I have a c++ program where I need to pass the square root of a number in a for loop.
#include<random>
#include<iostream>
#include<algorithm>
#include<string>
#include<math.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <omp.h>
using namespace std;
int main()
{
vector<int>inputDataBits(49); // vector of randomly generated input data bits
#ifdef printDebug
std::cout << "the input data bits are" << endl;
std::cout << "-------------------------" << endl << endl;
int var =49;
const int r=(int)sqrt(var);
float input2d[r][r];
for (int i = 0; i < r; i++)
{
for (int j = 0; j < r; j++)
{
input2d[i][j] = inputDataBits[(j %r) + (i *r)];
std::cout << input2d[i][j] << "\t";
}
std::cout << endl << endl;
}
std::cout << endl << endl;
#endif
return 0;
}
I get an error 'expression must have a constant value'. Is there a way to do this in c++?
This is the purpose of the constexpr keyword (make the value known at compile time).
constexpr int var=49;
constexpr int r=(int)sqrt(var);
Unfortunately, in the documentation sqrt() is not declared as a constexpr function.
Only gcc seems to consider it as constexpr but it is not portable.
The size of an array needs to be known at compile-time.
Instead you can use a std::vector, which has a dynamic size.
std::vector<std::vector<float>> input2d(std::vector<float>(r), r);

Linear vector search too slow for online judge

Problem Statement: We have to input a vector and then there is a certain number of queries. For one particular query, we have to search for that number in the vector. If found we print."Yes " and if not found we print the next greater number to the query and print "No ".
The vector is sorted.
#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 size,q,nq=0;
cin>>size;
vector<int> vec1;
int element;
for (int i = 0; i < size; i++)
{
cin>>element;
vec1.push_back(element);
}
cin>>q;
for(int j=0;j<q;j++)
{
cin>>nq;
for(int k=0;k<vec1.size();k++)
{
if(vec1[k]==nq)
{
cout<<"Yes "<<k+1<<endl;
break;
}
else if(vec1[k]>nq)
{
cout<<"No "<<k+1<<endl;
break;
}
}
}
return 0;
}
The code runs perfectly but for some test cases, there is an error due to time.
I need to improve this code. I am struggling with this as I have just learned about std::vector.
as this problem related to sorted vector it requires use Binary Search.
Binary search allows to answer queries with O(Log(N)) vs O(N) complexity (https://en.wikipedia.org/wiki/Computational_complexity). So this is why your implementation is too slow for this problem.
Here is manual implementation Using Binary Search with Vectors.
And also it is more clear to use std::lower_bound function. It does exact the thing needed:
#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 size,q,nq=0;
cin>>size;
vector<int> vec1;
int element;
for (int i = 0; i < size; i++)
{
cin>>element;
vec1.push_back(element);
}
cin>>q;
vector<int>::iterator qit;
for(int j=0;j<q;j++)
{
cin>>nq;
qit = std::lower_bound(vec1.begin(), vec1.end(), nq);
if(qit != vec1.end())
{
if(*qit == nq)
cout << "Yes " << (qit - vec1.begin());
else cout << "No " << *qit << " " << (qit - vec1.begin());
}
else cout << "No " << (qit - vec1.begin());
}
return 0;
}

the vector constructor doesn't change the end_file istream_iterator

i'm studying C++ for C programmers course (coursera) and in module 4 there is an example for how to use istream iterators to load data to STL vector ..but when i tried the code it only printed the first number from the file. i can't find the mistake in the code.
note :the instructor didn't run the code, he Taught is using PDF. so maybe there something missing in it.
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
fstream data_file("data.txt");
istream_iterator<int> start_file(data_file), end_file;
vector<int> data(start_file, end_file);
int sum = 0;
for (auto i = start_file; i != end_file; i++)
{
sum += *i;
cout << *i << endl;
}
cout << data.size()<<endl;
cout << sum << endl;
cout << (sum* 1.0) / data.size() << endl;
return 0;
}

Novice C++, seeking help in array division

#include <iostream>
#include <valarray>
using namespace std;
// to get new card number
int main ()
{
int i;
int array[5]= {10,2,6,34,51};
valarray<int> v[5];
int v %= 13;
for (int i=0; i<5 ; i++) {
cout << v[i]%=13 << " ";
}
}
hello, my goal is to get the array to perform a modulus division by number 13.
I've search and try a few different way but I can't figure out a way to make it work.....
Thank you...
Some of the problems with your code:
valarray does not have the same notation as normal arrays: valarray<int> v[5]; declares 5 different valarray objects and puts them in a C-style array. The notation you are looking for is valarray<int> v(10);
Get rid of the int v %= 13; line: this redefines v (an array) as an integer.
Use v[i]=(array[i]%13); for the calculation, what you have doesn't make sense.
Then output cout << v[i] << " ";
Also, you aren't really using any of the features of valarray, so it may make more sense just to use one single array, like:
#include <iostream>
using namespace std;
// to get new card number
int main ()
{
int array[5]= {10,2,6,34,51};
for (int i=0; i<5 ; i++) {
array[i]%=13;
cout << array[i] << " ";
}
}
Edit: by the way, the cool thing about valarray here is that you can apply the same function to every value at once. Like this:
#include <iostream>
#include <valarray>
using namespace std;
int main() {
valarray<int> v(10);
for (int i=0;i<10;++i) {
v[i]=i*i; //Fill the array with 0,1,4,9,16,... as an example
}
v%=13; //This applies the modulo 13 on the whole array at once.
for (int i=0;i<10;++i) {
cout << v[i] << endl;
}
}
Seems you want something like...
int array[5]= {10,2,6,34,51};
int v[5];
for (int i = 0; i < 5; ++i)
v[i] = array[i] % 13;
for (int i = 0; i < 5; ++i)
std::cout << v[i] << " ";
std::cout << '\n';

Extract Digits From An Integer Without sprintf() Or Modulo

The requirements of this are somewhat restrictive because of the machinery this will eventually be implemented on (a GPU).
I have an unsigned integer, and I am trying to extract each individual digit.
If I were doing this in C++ on normal hardware & performance weren't a major issue, I might do it like this:
(Don't hate on me for this code, it's just a sample to illustrate the method)
#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int someVal = 1234;
char stringVal[256] ={0};
sprintf(stringVal, "%016d", someVal);
int digits[16] = {0};
for( int i = 0; i < strlen(stringVal); ++i )
{
digits[i] = stringVal[i] - '0';
}
cout << "Integer Value = " << someVal << endl;
cout << "Extracted Digits = ";
copy( &digits[0], &digits[16], ostream_iterator<int>(cout, "-") );
cout << endl;
return 0;
}
I'm trying to find a method to extract these digits with the following restrictions:
Don't convert the integer to a string
Don't use the modulus operator (floating point division is fine)
The value in question is a 32-bit unsigned integer
I'm looking for an algorithm, not necessarily specific code. But specific code would be great. The languages I'm most familiar with that translate well to my target hardware are C++, C and assembler.
Any ideas?
EDIT: Here's an update with the algorithm I implemented based on the comments & links below. Thanks all.
#define _CRT_SECURE_NO_WARNINGS
#include <cstdlib>
#include <string>
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int main()
{
unsigned someVal = 12345678;
static const unsigned numDigits = 10;
unsigned digits[numDigits] = {0};
for( unsigned i = 0, temp = someVal; i < numDigits; ++i, temp /= 10 )
{
digits[numDigits-i-1] = temp - 10 * (temp/10) /*temp % 10*/;
}
cout << "Integer Value = " << someVal << endl;
cout << "Extracted Digits = ";
copy( &digits[0], &digits[numDigits], ostream_iterator<int>(cout, "-") );
cout << endl;
return 0;
}
Remember that the modulo operator can actually be implemented as:
mod(a, n) = a - n * floor(a / n)
Hence, you can use your favorite modulo based algorithm. You can simulate floor itself by typecasting.
Have a look around here in Bob Stout's snippets here under the C Archive, and here under the C++ Archive. Not alone that the snippets archive strive to be portable.
Hope this helps,
Best regards,
Tom.
One worth considering, by Terje Mathisen.