Skip to content

Instantly share code, notes, and snippets.

@kireal
Forked from shivallan/NoZeros
Last active August 29, 2015 14:19
Show Gist options
  • Save kireal/d7a3496e2d6bf9f58969 to your computer and use it in GitHub Desktop.
Save kireal/d7a3496e2d6bf9f58969 to your computer and use it in GitHub Desktop.
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <iostream>
#include <sys/time.h> // for gettimeofday()
//#include <cstdint> C++11 Standart only
using namespace std;
void nozero (std::vector<long long> &v)
{
long long left_val(*v.begin()), cur_val(*v.begin());
for (std::vector<long long>::iterator i = v.begin(); i != v.end(); ++i)
{
cur_val = *i;
if (cur_val) left_val = cur_val; else *i = left_val;
}
}
void nozeroN (std::vector<long long> &v, int N)
{
long long left_val(*v.begin()), cur_val(*v.begin());
int n(N);
for (std::vector<long long>::iterator i = v.begin(); i != v.end(); ++i)
{
cur_val = *i;
if (cur_val)
{
left_val = cur_val;
n = N;
}
else
{
if (n)
{
*i = left_val;
--n;
}
}
}
}
int main()
{
timeval t1, t2;
double elapsedTime;
std::vector<long long> v(100000000); // vector for 100000000 elements
std::generate(v.begin(), v.end(), rand); // filling with random numbers
// start timer
gettimeofday(&t1, NULL);
nozero(v);
// stop timer
gettimeofday(&t2, NULL);
// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
std::cout << "nozero -> " << elapsedTime << " ms.\n";
for (std::vector<long long>::iterator i = v.begin(); i != v.end(); ++i)
{
if (*i == 0)
{
std::cout << "v[" << std::distance(v.begin(), i) << "] = " << (*i) << "\n";
}
}
std::generate(v.begin(), v.end(), rand); // filling with random numbers
int N(3); // number of zeros for changing
// start timer
gettimeofday(&t1, NULL);
nozeroN(v, N);
// stop timer
gettimeofday(&t2, NULL);
// compute and print the elapsed time in millisec
elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms
elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms
std::cout << "nozeroN -> " << elapsedTime << " ms.\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment