*still*use xmonad as my main window manager :-)).

In the past few months, I have taken up the habit of solving problems from the project euler website. Today, I stumbled across Problem 24, which is pretty simple in principle. Find the 1000000th permutation of the first 10 natural numbers. I usually solve these problems with as much STL as possible because the generic style it forces on you really fits me, so the phrase

*"lexicographical permutation"*struck me as something I have read recently - in an entirely different context. Sure enough, after a bit of poking around, I have found it.

This essentially makes a (brute force) solution three lines of logic in C++, which - let's be honest - is not a common sight. So here's my solution to the problem:

int ints[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; for (int i = 1; i < 1000000; ++i) std::next_permutation(ints, ints+10); for (int i = 0; i < 10; ++i) std::cout << ints[i];I just wanted to share this little piece of code since I find it beautiful and self-explanatory and that can not often be said about C++ source code. I might share more of these when I get some time and motivation, so stay tuned ;-)

Geez, I totally forgot that you have a blog until this post showed up in my rss reader...

ReplyDeleteAnyway, In Haskell the solution would be way more beautiful.