All of the interesting technological, artistic or just plain fun subjects I'd investigate if I had an infinite number of lifetimes. In other words, a dumping ground...

Saturday, 29 December 2007

Boost library - counting Sundays

http://blog.nixternal.com/2007.12.26/boost-library-rocks/

Boost library rocks!

26 12 2007

I have been messing with a project through the university and we decided that we would go with the Boost library for the project, so to read up on Boost and how to use it, I decided I would attack Project Euler using Boost. One area that Boost really showed its strength was determining how many Sundays fell on the first day of the month between January 1, 1901 and December 31, 2000. In just a few lines, the answer was apparent. Here is the lines of code that answers this problem, and answers it immediately. I had used other calendar solutions in C++ in the past, but the gregorian.hpp library is fast.

#include <iostream>
#include "boost/date_time/gregorian/gregorian.hpp"
 
int main(void)
{
using namespace boost::gregorian;
int count = 0;
date_period dp(date(1901 , Jan, 1), date(2000, Dec, 31));
day_iterator iter(dp.begin ());
 
while (iter != dp. end())
{
if (iter->day() == 1 && iter->day_of_week ().as_enum == 0 )
count++;
++iter;
}
 
std::cout << count << std:: endl;
return 0;
}

The answer takes milliseconds, it is just that fast. Right now I would like to replace my gmpxx libraries for big numbers with a boost library and I think all of my Euler answers will be "boosted."

No comments:

tim's shared items

Add to Google Reader or Homepage