C++: mt19937 Example

C++11 introduces several pseudo-random number generators designed to replace the good old rand from the C standard library. I’ll show basic usage examples of std::mt19937, which provides random number generation based on the Mersenne Twister algorithm. Using the Mersenne Twister implementation that comes with C++11 has advantages over rand(), including:

  1. mt19937 has a much longer period than rand, e.g. it will take much longer for its random sequence to repeat itself.
  2. It has much better statistical behavior.
  3. Several different random number generator engines can be initialized simultaneously with different seeds, compared with the single “global” seed srand() provides.

The downside is that mt19937 is a bit less straightforward to use. However, I hope this post will help with that point :-).
Continue reading C++: mt19937 Example

Enabling C++11 (C++0x) in CMake

Going over some CMakeLists.txt files I’ve written, I came across the following snippet:

include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
elseif(COMPILER_SUPPORTS_CXX0X)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
else()
        message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

Various versions of gcc and clang use different flags to specify C++11 support; namely, older ones accept -std=c++0x and newer ones accept -std=c++11. The above snippet detects which one is the right one for the compiler being used and adds the flag to CXX_FLAGS.

Using std::chrono::high_resolution_clock Example

5 years ago I’ve shown how to use clock_gettime to do basic high-resolution profiling. The approach there is very useful, but unfortunately, not cross-platform. It works only on POSIX-compliant systems (especially not Windows).

Luckily, the not-so-new C++11 provides, among other things, an interface to high-precision clocks in a portable way. It’s still not a perfect solution, as it only provides wall time (clock_gettime can give per-process and per-thread actual CPU time as well). However, it’s still nice.

#include <iostream>
#include <chrono>
using namespace std;
 
int main()
{
    cout << chrono::high_resolution_clock::period::den << endl;
    auto start_time = chrono::high_resolution_clock::now();
    int temp;
    for (int i = 0; i< 242000000; i++)
        temp+=temp;
    auto end_time = chrono::high_resolution_clock::now();
    cout << chrono::duration_cast<chrono::seconds>(end_time - start_time).count() << ":";
    cout << chrono::duration_cast<chrono::microseconds>(end_time - start_time).count() << ":";
    return 0;
}

I’ll explain the code a bit. chrono is the new header file that provides various time- and clock-related functionality in the new standard library. high_resolution_clock should be, according to the standard, the clock with the highest precision.

cout << chrono::high_resolution_clock::period::den << endl;

Note that there isn’t a guarantee of how many ticks per second it has, only that it’s the highest available. Hence, the first thing we do is get the precision by printing how many times a second the clock ticks. My system provides 1000000 ticks per second, which is microsecond precision.

Getting the current time using now() is self-explanatory. The possibly tricky part is

cout << chrono::duration_cast<chrono::seconds>(end_time - start_time).count() << ":";

(end_time - start_time) is a duration (a newly defined type), and the count() method returns the number of ticks it represents. As we said, the number of ticks per second may change from system to system, so in order to get the number of seconds we use duration_cast. The same goes for microseconds in the next line.

The standard also provides other useful time units, such as nanoseconds, milliseconds, minutes, and even hours.

Conditional Compilation in Autoconf and Automake

While working on my audio-based random password generator (you can view the source in GitHub), I wanted to do some conditional compilation: compiling certain parts of the program only if some option is passed to the configure script. As it usually happens with GNU’s autotools, it’s kind of hell to do it. Documentation is spread across dozens of sources, and each provides only a specific part of what to do. I’m writing it here on the blog, in the hope I’ll never have to search for how to do so again.
Continue reading Conditional Compilation in Autoconf and Automake

Bye Bye OmniCppComplete, Hello Clang Complete

For years OmniCppComplete has been the de facto standard for C++ completion in Vim. But as time progressed, I got more and more annoyed by its shortcomings. OmniCppComplete is based on tokenizing provided by ctags. The ctags parsing of C++ code is problematic; you can’t even run it on libstdc++ headers (you need to download modified headers). You want to use an external library? You’ll need to run ctags separately on each library. Not to mention its inability to deduce types of anything more than trivial code. The core of the problem is that OmniCppComplete isn’t a compiler, and you can’t expect something that isn’t a compiler to fully understand code. This is what makes Visual Studio’s IntelliSense so great: it uses the Visual C++ compiler for parsing. It isn’t making wild guesses at types or what the current scope is – it knows it.
Continue reading Bye Bye OmniCppComplete, Hello Clang Complete

spass-2.0 – Secure Password Generator

This is a complete rewrite of my secure password generator. The new version uses my true random number generator (and here).

The major change was using the new true random number generator in order to ensure strong passwords. Less significant changes include an easy way to specify password strips and some calling convention changes.

Usage examples:

$ ./spass
E5pT35Fg
$ ./spass -l 14
R$tfOm4g_yRQ2J
$ ./spass -s 0-9a-f -l 32
8b5f14a1eeaabe58c2878ab5416a9ebb

Download the tarball spass-2.0.tar.bz2. The program depends on Boost‘s program_options (it was tested against versions 1.37 and 1.42 and should work with other versions too).

Statistical Tests for My Audio Based Random Number Generator

In May, I’ve written about a way to generate random numbers from audio noise. Basically, it went like this:

  1. Get an audio sample from the microphone.
  2. Push the least significant bit to a buffer.
  3. Repeat steps 1-2 until the buffer is full (buffer size == block size for the hash function).
  4. Apply the hash function to the buffer.
  5. Get random bits from the digest.

In order to continue developing this random number generator (RNG), I’ve written a C++ class that simplifies working with it.
Continue reading Statistical Tests for My Audio Based Random Number Generator

Simple AI Engine for the Oware Game

Some time ago I worked with a friend on building an Oware game. I was supposed to build the AI engine, and he was supposed to build the user interface for it. Unfortunately, while the AI engine interface I designed and a simple alpha-beta pruning engine were implemented, the project was never completed.

Screenshot of game session
Screenshot of game session

Continue reading Simple AI Engine for the Oware Game

Simple Histogram Widget for wxWidgets

When working on Open Yahtzee 1.10 (or whatever I’ll call the version after 1.9), I wrote a simple histogram widget to be part of the new statistics dialog. I should emphasize the simple part: this widget was meant to display a simple histogram without requiring any special, bloated plotting libraries. It doesn’t support all the fancy stuff, just a plain histogram.

I figured that a simple pie plot would better serve Open Yahtzee’s needs, so unfortunately this code will not be released as part of the program. While the code is not perfect, it’s functional and serves as a good example of a custom widget. So I felt pity at letting it fall into oblivion in Open Yahtzee’s SVN repository, and I thought it might come in handy to someone else (or at least to me) if it were easily accessible.

simple_histogram

Continue reading Simple Histogram Widget for wxWidgets

Convert int to string (As Well As Almost Anything)

This is a little code snippet from Open Yahtzee‘s code base that converts all the built-in types and many custom classes (ones that override the << operator) to string.

template <class T> inline std::string stringify(T x)
{
    std::ostringstream o;
    o << x;
    return o.str();
}

I first wrote it to convert ints to strings, but later I templatized it so it would work with other types as well. It’s a clean, elegant snippet that I thought others might find useful too.