mardi 1 septembre 2015

Dots in printf in C++

I encountered this snippet but couldn't understand how it works, especially the printf statements. Can someone explain

void remove_trailing_zeroes()
{
    int a,b; 
    bool f1,f2;
    f1=a%2;
    f2=b%2;
    if (f1==f2) {
        printf("%.0lf\n",(a*1.+b)/2.);
    }
    else {
        printf("%.1lf\n",(a*1.+b)/2.);
    }

}

EDIT: I have rephrased my question, help me improve it

C++11 std::cout << "string literal in UTF-8" to Windows cmd console? (Visual Studio 2015)

Summary: What should I do to print correctly a string literal defined in the source code that was stored in UTF-8 encoding (Windows CP 65001) to a cmd console using std::cout stream?

Motivation: I would like to modify the excellent Catch unit-testing framework (as an experiment) so that it would display my texts with accented characters. The modification should be simple, reliable, and should be also useful for other languages and working environments so that it could be accepted by the author as an enhancement. Or if you know Catch and if there is some alternative solution, could you post it?

Details: Let's start with the Czech version of the "quick brown fox..."

#include <iostream>
#include "windows.h"

using namespace std;

int main()
{
    cout << "\n-------------------------- default cmd encoding = 852 -------------------\n";
    cout << "Příšerně žluťoučký kůň úpěl ďábelské ódy!" << endl;

    cout << "\n-------- Windows Central European (1250) set for the cmd console --------\n";
    SetConsoleOutputCP(1250);
    std::cout << "Příšerně žluťoučký kůň úpěl ďábelské ódy!" << std::endl;

    cout << "\n------------- Windows UTF-8 (65001) set for the cmd console -------------\n";
    SetConsoleOutputCP(CP_UTF8);
    std::cout << "Příšerně žluťoučký kůň úpěl ďábelské ódy!" << std::endl;
}

It prints the following (font set to Lucida Console): enter image description here

The cmd default encoding is 852, the default windows encoding is 1250, and the source code was saved using 65001 encoding (UTF-8 with BOM). The SetConsoleOutputCP(1250); changes the cmd encoding (programmatically) the same way as the chcp 1250 does.

Observation: When setting the 1250 encoding, the UTF-8 string literal is printed correctly. I believe it can be explained, but it is really strange. Is there any decent, human, general way to solve the problem?

Is there a C++11 CSPRNG?

As we know, the Mersenne Twister is not crytographically secure1:

Mersenne Twister is not cryptographically secure. (MT is based on a linear recursion. Any pseudorandom number sequence generated by a linear recursion is insecure, since from sufficiently long subsequence of the outputs, one can predict the rest of the outputs.)

But many sources, like Stephan T. Lavavej2 and even this website3. The advice is almost always (verbatim) to use the Mersenne Twister like this:

auto engine = mt19937{random_device{}()};

They come in different flavors, like using std::seed_seq or complicated ways of manipulating std::tm, but this is the simplest approach.

Even though std::random_device is not always reliable4:

std::random_device may be implemented in terms of an implementation-defined pseudo-random number engine if a non-deterministic source (e.g. a hardware device) is not available to the implementation. In this case each std::random_device object may generate the same number sequence.

The /dev/urandom vs /dev/random debate rages on5.

But while the standard library provides a good collection of PRNGs, it doesn't seem to provide any CSPRNGs. I prefer to stick to the standard library rather than using POSIX, Linux-only headers, etc. Can the Mersenne Twister be manipulated to make it cryptographically secure?

Links

  1. <http://ift.tt/1JJhnsb;

  2. rand() Considered Harmful, Going Native 2013

    <http://ift.tt/1NUKcYY;

  3. Random number generation in C++11 , how to generate , how do they work?

    <http://ift.tt/1JJhnsh;

  4. <http://ift.tt/1JJhlR5;

  5. Myths about /dev/urandom

    <http://ift.tt/1JJhlR7;

Knapsack algorithm, How to get better performance?

Openmp outperforms the serial code by factor x2, but I would like to have a better performance if it is possible.

Here is the serial code in c++:

for (int k = 0; k < numelem[i]; k++)
    {

      sumK = sumK - weight[k];
      int cmax = 0;
      cmax = max(capacity - sumK, weight[k]);

      for (int c = capacity; c >= cmax; c--)
        {

          if (f[c] < f[c - weight[k]] + value[k])
          {
            f[c] = f[c - weight[k]] + value[k];
            M[capacity * k + c] = 1;
          }
        }
    }

For the openmp version, I use two f0,f1 arrays which are swapped at each iteration. This helps me to prevent the race condition, but I suppose that false sharing is still present (not sure). Other my supposition is that, the conditional statements inside pragma for slow down the execution.

#pragma omp parallel
    {
        for (int k = 0; k < numelem[i]; k++) {

            sumK = sumK - weight[k];
            int cmax = 0;
            cmax = max(capacity - sumK, weight[k]);
            int c = capacity;

            if (k % 2 == 0) {

#pragma omp for
                for (c = capacity; c >= cmax; c--) {

                    //FALSE SHARING???

                    if (f0[c] < f0[c - weight[k]] + value[k]) {
                        f1[c] = f0[c - weight[k]] + value[k];
                        M[capacity * k + c] = 1;
                    } else {
                        f1[c] = f0[c];
                    }
                }
            } 

            else {

#pragma omp for
                for (c = capacity; c >= cmax; c--) {

                    //FALSE SHARING???

                    if (f1[c] < f1[c - weight[k]] + value[k]) {
                        f0[c] = f1[c - weight[k]] + value[k];
                        M[capacity * k + c] = 1;
                    } else {
                        f0[c] = f1[c];
                    }
                }

            }

        }
    }   

Here you can find the full code for serial c++ and openmp c++

This work is based on this article:

C++ Topographic Maps with OpenGL

I've done my studying, and I read through a lot of the Stackoverflow questions that were answered on the topic, but I did not come across anything, here or on the internet, that could give me the extra push. I've read on the subject enough that if I put in the time, I could definitely make it, but it feels like I am missing something, and my lack of knowledge on the subject motivates me to ask you, fellow programmers, as your collective knowledge exceeds mine.

I want to use noise to generate terrain, but instead of drawing it in 3D, I wish to use it as a 2D military map, with contour lines and everything. The contour lines are important because I'd like to use them to draw efficient and believable roads on the map, and houses, etc. I'd be using a custom engine and my own libraries, other than libnoise or similar noise libraries, and of course, openGL. The purpose of this project is for me to learn this stuff, instead of using finished tools.

I am using standard C++, but I am also considering using C++11, so don't hold back!

EDIT: For clarification, any online resource I missed on drawing topographic maps with C++ is welcome as are any straight answers regarding methods of accomplishing my goals.

Beating binary search using CPU cache line

For educational purposes, I am trying to beat binary search using CPU cache line.

http://ift.tt/1JuoQw4

If you uncomment #define EXIT_ONLY, the search works like normal binary search, except if there are few elements, the search became linear search.

As expected this performs faster than binary search.

However I want to improve future, so if you comment #define EXIT_ONLY, then "small" linear search is made instead of accessing just the "middle" element.

In theory the values for linear search must be in CPU cache line and access must be "free of charge".

However in practice this search is way too slow than the normal binary search.

If I hardcode CACHE_COUNT_2 to be equal to 1, then speed is comparable, but still slower.

Note I never tried to unroll the for cycle in _linear().

What could be explanation of the slower execution?

Repo with all files is here:
http://ift.tt/1LQxQla

C++ boost Tuple Serialization/Deserialization

it is probably really simple but I am stock on this. I am trying to serialize and deserialize boost::tuple. I wrote a "serialize" function and it perfectly serializes the tuple. However, I do not have any "deserialize" function. I am not even sure do I need one. Most of the examples do not even have one. Here is my code,

namespace boost
{
    namespace serialization
    {
        template<typename Archive, typename T1, typename T2>
        void serialize(Archive & ar, boost::tuple<T1, T2> & t,
                    const unsigned int)
        {
            ar & t.get<0>();
            ar & t.get<1>();
        }

    }
}

using namespace std;
using namespace boost;

int main() {
    std::ofstream os("archive.txt");
    {

        boost::tuple<int, int> t = boost::make_tuple(1, 5);
        boost::archive::text_oarchive ar(os);
        ar & boost::serialization::make_nvp("first", t.get<0>() );
        ar & boost::serialization::make_nvp("second", t.get<1>() );
    }

    {
        std::ifstream file("archive.txt");
        boost::archive::text_iarchive ia(file);
        boost::tuple<int, int> t;
            ia >> t;
            std::cout << "First: " << t.get<0>() << "\n" << "Second: " << t.get<1>() << std::endl;
    }
    return 0;
}

I get below error,

Undefined symbols for architecture x86_64: "boost::archive::text_iarchive_impl
<boost::archive::text_iarchive>::load_override(boost::archive::class_name_type&, int)", referenced from: boost::archive::text_iarchive& boost::archive::detail::interface_iarchive
  <boost::archive::text_iarchive>::operator>>
    <boost::archive::class_name_type>(boost::archive::class_name_type&) in cc4Y8n8F.o ld: symbol(s) not found for architecture x86_64 collect2: error: ld returned 1 exit status

How can I overcome this error?

boost::archive::text_iarchive ia(file); line causes the error