I am trying to practice C++ by doing some old Google Code Jam problems. A relatively simple one I found is to reverse the words in a string. It can be found here https://code.google.com/codejam/contest/351101/dashboard#s=p1
So far I have:
#include<iostream>using namespace std;int main(){ int n = 0; cin >> n; string rev = ""; string buf = ""; string data = ""; getline(cin, data); for(int _ = 0; _ < n; _++){ getline(cin, data); rev = ""; buf = ""; for(char& c : data) { buf += c; if(c == ''){ rev = buf + rev; buf = ""; } } cout << "Case #"<< _ + 1 << ": "<< buf << ""<< rev << endl; } return 0;}
Which seems to run pretty fast. When running time ./reverse < in > /dev/null
with a test file of around 1.2E6
cases it takes around 3.5
seconds when compiled with g++ -O3
.
So as a benchmark I created a solution in python
#!/usr/bin/env pythonfrom sys import stdin, stdoutstdout.writelines(map(lambda n: "Case #%d: %s\n" % (n + 1, ''.join(stdin.readline().split()[::-1])), xrange(int(stdin.readline()))))
However when I run it under pypy
with time pypy reverse.py < in > /dev/null
it takes only about 1.95
seconds.
In theory as pypy
is written in C++ shouldn't C++ be as fast or faster and if so how could this code be optimised to be faster ?