I'm learning C++. While solving Leetcode 0009, I wanted to time the function. For 4 different inputs I got the following results consistently:
1
time: 8993
0
time: 88
0
time: 1374
1
time: 1199
My question is why is it taking so long for the first run but not the others? And any other feedback is appreciated.
Here is the code:
//leetcode 0009. Palindrome Number
#include <iostream>
#include <sstream>
#include <string>
#include <chrono>
bool isPalindrome(int x) {
if (x < 0) return false;
std::stringstream ss;
ss << x;
std::string str;
ss >> str;
int len = str.length();
for (int i=0; i<len/2; i++) {
if (str[i] != str[len-i-1]) {
return false;
}
}
return true;
}
void timeit (bool (*f)(int), int x) {
auto s = std::chrono::high_resolution_clock::now();
auto res = f(x);
auto e = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(e - s);
std::cout << res << std::endl;
std::cout << "time: " << duration.count() << std::endl; //true
}
int main() {
timeit(isPalindrome, 121);
timeit(isPalindrome, -121);
timeit(isPalindrome, 10);
timeit(isPalindrome, 1001);
}
Related
This question already has answers here:
How to get duration, as int milli's and float seconds from <chrono>?
(5 answers)
Closed 13 days ago.
#include <iostream>
#include <chrono>
using namespace std;
class Time
{
chrono::steady_clock::time_point start;
public:
Time()
{
start = chrono::steady_clock::now();
}
~Time()
{
auto end = chrono::steady_clock::now();
std::chrono::duration<double> time = end-start;
cout << "time " << time.count() << endl;
}
};
void revstr(char* input)
{
int length = strlen(input);
int last_pos = length-1;
for(int i = 0; i < length/2; i++)
{
char tmp = input[i];
input[i] = input[last_pos - i];
input[last_pos - i] = tmp;
}
}
int main()
{
Time t;
char str[] = "abcd";
cout << str << endl;
revstr(str);
cout << str << endl;
}
The above outputs:
time 7.708e-06
How should we turn that in milliseconds, nanoseconds or seconds?
I tried (replace std::chrono::duration<double> time = end-start;)
std::chrono::duration<std::chrono::nanoseconds> time = end-start;
But it says:
A duration representation cannot be a duration.
Use std::chrono::duration_cast():
#include <chrono>
#include <iostream>
int main()
{
std::chrono::duration<double> time{7.708e-06};
auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(time);
std::cout << nanos.count() << '\n';
}
I'm working on a program that is supposed to make use of async and futures but i have come across a problem. When an output file is created nothing is in the file. It is just a blank file. I'm not sure if the issue s with reading the original file or write onto a new one I'm also usure if I have properly utilized async so any corrections would be a appreciated.
#include <fstream>
#include <string>
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <future>
#include <vector>
#include <stdexcept>
#include <utility>
#include <sstream>
#include <stdlib.h>
#include <cstdlib>
#include <ctime>
using namespace std;
int prnumber;
static bool bCheckFinished = false;
string guess;
bool process(std::string sFileIn, std::string sFileOut) {
ifstream in(sFileIn);
vector<vector<string>> vsFields;
ofstream outPutFile;
outPutFile.open(sFileOut, std::ofstream::out | std::ofstream::trunc);
if (in) {
string sLine;
while (getline(in, sLine)) {
stringstream sep(sLine);
string sField;
vsFields.push_back(vector<string>());
while (getline(sep, sField, ',')) {
vsFields.front().push_back(sField);
}
}
}
if (outPutFile.is_open()) {
for (auto row : vsFields) {
for (auto field : row) {
outPutFile << field << "," << std::endl;
}
}
}
std::cout << "\n File Successfully Read!" << std::endl;
return true;
}
bool prime(int prnumber) {
std::cout << "Please enter a number" << std::endl;
std::cin >> prnumber;
std::cout << "Processing" << std::endl;
for (int i = 2; i < prnumber; ++i) if (prnumber%i == 0) return false;
return true;
}
int main() {
auto start = std::chrono::high_resolution_clock::now();
std::future<bool> fileProcA = std::async(process, "unigram_freq.cvs", "Word_list.txt");
std::future<bool> fut = std::async(prime, prnumber);
bool pr = fut.get();
bool fileProc = false;
while (!fileProc) {
fileProc = fileProcA.get();
}
auto end = std::chrono::high_resolution_clock::now();
if (pr) std::cout << "The number is prime!" << endl;
else std::cout << "It is not prime";
double elapsed = (std::chrono::duration<double, std::milli>(end - start).count());
std::cout << "The time elapsed is " << elapsed << "ms" << std::endl;
return 0;
}
I want to make a program which displays current time that ticks in background then is it possible to initialize cin input processes while it is ticking?
just for fun:
#include <iostream>
#include <chrono>
#include <thread>
#include <atomic>
#include <mutex>
#include <ctime>
std::mutex more_lock;
std::string more_output;
void set_more_output(const std::string& more)
{
std::lock_guard<std::mutex> lock(more_lock);
more_output = more;
}
std::string get_more_output()
{
std::lock_guard<std::mutex> lock(more_lock);
return more_output;
}
std::atomic_bool running {true};
std::thread start_timer_runner()
{
return std::thread([&]{
while(running) {
using namespace std::chrono;
using namespace std::chrono_literals;
auto now = system_clock::to_time_t(system_clock::now());
auto now_str = std::string(std::ctime(&now));
now_str.pop_back(); // ctime adds new line
std::cout << "\r" << now_str << " | " << get_more_output() << std::flush;
std::this_thread::sleep_for(1s);
}
});
}
void parse_decimals()
{
int x;
set_more_output("please enter a decimal: ");
while(std::cin >> x)
{
set_more_output("thanks! you entered " + std::to_string(x) + ", please enter a new decimal: ");
}
}
int main()
{
auto timer = start_timer_runner();
parse_decimals();
running = false;
timer.join();
std::cout << std::endl << "bye bye!" << std::endl;
}
I've only found some answers to this problem in Python and JS, hopefully you can help me to do the same in c++.
So the challenge is to print out the first recurring character of a given string, here is what i came up with, but I don't know if this code actually looks good. This is my first time posting on StackOverflow, hopefully I'll get some feedback =)
#include <iostream>
#include <vector>
int main() {
std::cout << "Enter some letters:\n";
std::string str;
std::cin >> str;
// vector that stores characters that we will come across in the string
std::vector<char> seen(0);
for (char a : str) {
for (int i = 0; i < seen.size(); i++) {
if (a == seen[i]) {
std::cout << a << std::endl;
return 0;
} else { continue; }
}
seen.push_back(a);
}
std::cout << "none\n";
return 0;
}
For speed, how about:
#include <iostream>
int main() {
std::cout << "Enter some letters:\n";
std::string str;
std::cin >> str;
bool seen [256] = { };
for (char a : str) {
unsigned char u = (unsigned char) a;
if (seen [u]) {
std::cout << a << std::endl;
return 0;
}
seen [u] = true;
}
std::cout << "none\n";
return 0;
}
This is O(N), rather than O(N*N/2)
Live demo
For your task check out std::find:
void printRecurring(const std::string& str) {
std::string::const_iterator it = str.begin(), e = str.end();
for (std::string::const_iterator it2 = str.begin(); it2 != str.end(); ++it2) {
it = std::find(it + 1, e, *it2);
if (it != str.end()) {
std::cout << *it2 << std::endl;
return;
}
}
}
I think you can make it a little simpler by using std::find.
#include <iostream>
#include <vector>
#include <algoritm>
int main()
{
std::cout << "Enter some letters:\n";
std::string str;
std::cin >> str;
// vector that stores characters that we will come across in the string
std::vector<char> seen(0);
for (char a : str) {
auto it = std::find(seen.begin(), seen.end(), a);
if (it != seen.end()) {
std::cout << "Found it: " << *it << std::endl;
return 0;
}
seen.push_back(a);
}
std::cout << "none\n";
return 0;
}
I am trying to implement an algorithm that will take a set of numbers and output the largest possible number (without breaking up the individual numbers). So in an example like this where I give 4 numbers:
4
43 12 3 91
The output would be
91-43-3-12 or 9143312.
My attempt is below.
#include <algorithm>
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using std::vector;
using std::string;
bool compare (int x, int y) {
std::cout << "in func \n";
string a = std::to_string(x);
string b = std::to_string(y);
std::cout << a << " " << b << "\n";
std::cout << std::stoi(a.substr(0, 1)) << " " << std::stoi(b.substr(0, 1)) << "\n" ;
if (std::stoi(a.substr(0, 1)) < std::stoi(b.substr(0, 1))) {
std::cout.flush();
std::cout << "if \n";
return true;
}
else {
std::cout.flush();
std::cout <<"else \n";
return false;
}
}
string largest_number(vector<string> a) {
std::stringstream ret;
while (a.size() > 0) {
int maxNumber =-1;
int index = -1;
std::cout << "going into for " << a.size() << "\n";
for (size_t i = 0; i < a.size(); i++) {
if (! compare (stoi(a[i]), maxNumber ) ) { //stoi(a[i]) >= maxNumber) {
maxNumber = stoi(a[i]);
std::cout << maxNumber << " " << i << "\n";
index = i;
}
std::cout << "here \n";
}
ret << maxNumber;
a.erase(a.begin() + index);
}
string result;
ret >> result;
return result;
}
int main() {
int n;
std::cin >> n;
vector<string> a(n);
for (size_t i = 0; i < a.size(); i++) {
std::cin >> a[i];
}
std::cout << largest_number(a);
}
I do not understand what is wrong with my compare function. When I run it, say with this input:
$ g++ -pipe -O2 -std=c++14 largest_number.cpp -lm -o largest1
$ ./largest1.exe
4
4 23 1 45
going into for 4
in func
4 -1
It doesnt print the cout statements in the conditional if or else. How could this be possible? I even tried flushing. However, if I take the entire conditional out, put a cout statement and the return true or something, then it runs the program in entirety (although this is not the expected output).
I do not mind harsh criticism. What am I doing wrong here? Any advice will be appreciated.
Thanks in advance.
In this statement
std::cout << std::stoi(a.substr(0, 1)) << " " << std::stoi(b.substr(0, 1)) << "\n" ;
when b is equal to -1 the expression b.substr(0, 1) is equal to an object of type std::string that contains one character '-' that is the minus sign.
If to apply the standard function std::stoi to such a string then an exception will be thrown.
Consider the following code snippet
std::string s("-");
try
{
std::stoi(s);
}
catch (const std::exception &e)
{
std::cout << e.what() << std::endl;
}
Its output will be
invalid stoi argument
It seems what you need is just to sort the strings. For example
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
int main()
{
std::vector<std::string> v { "4", "23", "1", "45" };
auto cmp = [](const std::string &a, const std::string &b)
{
std::string::size_type i = 0, m = a.size();
std::string::size_type j = 0, n = b.size();
int result;
do
{
if (m < n)
{
result = a.compare(i, m, b, j, m);
j += m;
n -= m;
}
else
{
result = a.compare(i, n, b, j, n);
i += n;
m -= n;
}
} while (result == 0 && m && n);
return 0 < result;
};
std::sort(v.begin(), v.end(), cmp);
for (const auto &s : v) std::cout << s;
std::cout << std::endl;
return 0;
}
The output of the program will be
454231
Or for this set of numbers
std::vector<std::string> v{ "43", "12", "3", "91" };
the output will be
9143312
or for one more set of numbers
std::vector<std::string> v{ "93", "938" };
the output will be
93938