Saturday, May 30, 2015

Out of codejam : The curse of the dp sense

That was it for me in the code jam. I really think the whole outcome centers around how badly I've dealt with problem D. The 11 extra points from D small would have made me advance and get a t-shirt. Honestly what I really don't like is that you needed to be in top 500 for round 2 for the distributed codejam, which is a completely different contest format. I don't see the point for this restriction.

Bad omen

The first demoralization of the day was learning that the codejam-commandline tool no longer works. Google finally deprecated the authentification used by this tool, which was not updated in a looooong while. I really wonder if anyone other than me actually used this tool...

Problem statements

Problem A: pegs

The trick is to notice that peg man can pick any cell. So if there is any cell that takes you out of the board, pegman will pick that cell. Why is this important? Consider the arrows that point directly to the outside of the map. You NEED to change them. Because pegman can always start at that arrow and exit the map. So it is necessary that these arrows point elsewhere.

Once all arrows that point to the outside of the map point somewhere else. They will each point to another arrow. And this is sufficient. Because no arrow in the map points to the outside of the map. So it really doesn't matter if we point to an arrow, this other arrow will never take us to theo utside of the map.

So the solution (for both A-small and A-large) is to just take each arrow that points to the outside of the map. If you can pick any new direction to it that makes it point to another arrow, increase cost by 1. Else it is impossible.

Problem B: pool

I read the first paragraphs and seemed a bit too mathy, I felt that it was likely the other small problems were more approachable so I decided to skip it to read the other problems.

Problem C-small: sentences

There are at most 18 sentences with unknown language, we can try each of the `2^18` combinations of English/French assignments and just simulate it. Or so you'd think...

A small blunder: I didn't notice that the number of words was a bit large so just naively doing the simulation was a bad idea. Even with my trick to use 4 cores so that each core runs each case separately, my first solution still needed around 10 minutes to clear a A-small input.

You don't need to parse and compare the words every time, you only care about which words are common to the two languages, so for example just replace each word with an integer, you need at most 2180 integers (although a case with 2180 distinct words is trivially 0). An extra improvement is to use bitsets from STL or something similar. Basically, you represent each sentence by 2180 / 64.0 bit masks, if the i-th bit is 1 then the i-th word is included in the sentence. Doing union / intersection operations with bit operations so that you can do the stuff rather fast (2180 / 64.0) steps.

Here is the code for the sub-problem, once you assign English or French to each sentence:

int N;
vector<string> sentences;
vector<bitset<2180>> word_masks;

int sub_problem(vector<bool> &eng)
{
    bitset<2180> english_words, french_words, inter;
    for (int i = 0; i < N; i++) {
        if (eng[i]) {
            english_words |= word_masks[i];
        } else {
            french_words |= word_masks[i];
        }
    }
    inter = english_words & french_words;
    return inter.count();
}

You'd need to initialize the bitsets before simulating all assignments:

   int word_ids = 0;
   map<string, int> word_id;
   
    
   word_masks.resize(N);
   for (int i = 0; i < N; i++) {
       word_masks[i].reset();
   }
   for (int i = 0; i < N; i++) {
       istringstream st(sentences[i]);
       string x;
       while (st >> x) {
           int j = 0;
           if (word_id.count(x)) {
               j = word_id[x];
           } else {
               j = word_ids++;
               word_id[x] = j;
           }
           word_masks[i][j] = true;
       }
   }

The rest is the usual bruteforce for the assignments.

When I got correct in this problem I felt confident. There was quite a lot of time for the match but I was 400-th -ish. I thought that just solving D-small would put me in top 500. I was right...

Problem D-small

For some reason I instantly thought dynamic programming was the way. You can certainly fill the cells using dynamic programming. Remembering the previous row and some other stuff. Well, seems hard at first except when you notice:

  • Numbers larger than 4 are clearly never usable. A cell can't have 5 neighbors.
  • Turns out 4 is also never usable. You cannot have a 4 in the top or bottom rows. If you place a 4 elsewhere, all 4 cells adjacent to that cell must be 4 too. If you repeat this logic, you'll eventually need the top or bottom row to contain a 4, which would be wrong.
  • So you only need numbers 1-3 for the cells.

There is more, much more. But I really wish these 3 facts where the ONLY ones I noticed, because then I would have been discouraged to think of the bad dynamic programming solution I thought of...

  • If you place a 3 in a cell in the top row, then all cells in the row must be 3, which also means that the cells in the top-second row must be 3. (Same happens with the last two bottom rows). In fact, after this filling the rest is similar to filling the same problem but with R-2 rows. With the exception that you cannot place 3 in the third row anymore. So yeah this hints a dynamic programming solution.
  • The only time you are allowed to place a 3 elsewhere is when all the cells in the row above the row are matched to cells above the row. So really, whenever a 3 appears, it means that you need to fill 2 consecutive rows with 3s and the rows surrounding them cannot have any 3.
  • So usually you only need to decide between 1 and 2.

This led me to a dynamic programming solution and rushed to start to code. It was a mistake. For starters just dealing with bitmasks (and you needed three sets of bit masks in this solution) introduces so much debugging time to coding something. What's worse is that I completely underestimated the difficulty in dealing with the rotations. My initial strategy was to just code without caring about duplicate rotations and then just do something like dividing the result by C or something? I didn't really have enough hindsight for what to do there. Once I noticed how non-trivial the rotations were in this dynamic programming solution it was too late. I put some (wrong) patch work to make the rotations work. It passed examples, but not the small tests.

That was the blunder: A much finer strategy was to try and solve the problem using bruteforce. In hindsight it should have been obvious to me, so this hurts. Here's the logic you (me) need to remember in the future to know not to miss the chance of using bruteforce in the key-to-solve bruteforce problem in your next significant match:

  • The requirements for the values of the cells are VERY restrictive. Just a single decision removes plenty of later decisions. It's very likely that `6 times 6` grids and smaller the results should be very small. There would be very few valid ways. A big hint is that the results in the examples are both very small : 1 and 2. And the examples are very weak, so it shows the problem setter didn't want to make things too noticeable...
  • Even if after coding the brute force, it turns out that doing all the brute forces is too slow for 4 minutes. It's very unlikely it would be too slow for 20 minutes (again, the cases are quite small and the restrictions very restrictive). "But vexorian, why would I want to solve them in 20 minutes when there is a 4 minutes limit?" You ask. There are only 20, TWENTY different inputs for this problem (D-small), so you can just precalculate them all off-line and just submit the precalculated solutions after you donwload the input.
  • Even in the remote case somehow there are way too many valid assignments for some of the cases. This might be very helpful to learn more about the problem. Being able to visualize the solutions for `4 times 4` might help you notice some patterns. I am fairly sure that when you learn the patterns, you can solve D-large.
  • Fancy dynamic programming is way riskier than brute force. It's far more likely you'll have bugs in the mega complicated bit mask stuff than your brute force would be too slow to be of ANY use. It is at least far easier to deal with rotations if you use the brute force.

So yeah, you (me) really should have used brute force in this problem. It is very important to detect wrong assignments as quickly as possible so there are few invalid branchings. This is what my code would have looked like if I did the right choice. It passes the D-small input and is incredibly fast:

    int R, C;
    vector<string> board;
    
    set<vector<string>> seenBefore;

    bool cellCheck(int x, int y)
    {
        // check if cell (x,y) matches requirements 
        int dx = 0, dy = 1;
        bool unknown = false;
        int c = 0;
        int t = 0;
        for (int i = 0; i < 4; i++) {
            int nx = x + dx, ny = (y + dy + C) % C;
            if (0 <= nx && nx < R) {
                t++;
                if (board[nx][ny] == '?') {
                    // an unknown cell, if there are still unknown cells then
                    // the number of adjacent equal cells doesn't HAVE to be equal
                    // but if it is larger it is still invalid.
                    unknown = true;
                } else if (board[nx][ny] == board[x][y]) {
                    c++;
                }
            }
            tie(dx,dy) = make_tuple(dy, -dx);
        }
        int m = board[x][y] - '0';
        if ( (c == m) || ( (c < m) && unknown) ) {
            return true;
        } else {
            return false;
        }
    }
    
    bool check_rotation()
    {
        // rotate the board C-1 times , if any of those was found before, return false
        vector<string> board2 = board;
        for (int k = 1; k < C; k++) {
            for (int i = 0; i < R; i++) {
                for (int j = 0; j < C; j++) {
                    board2[i][j] = board[i][ (j + k) % C ];
                }
            }
            if (seenBefore.count(board2)) {
                return false;
            }
        }
        // else add it to the seenBefore set
        seenBefore.insert(board);
        return true;
    }
    
    int count_valid = 0;
    void backtrack(int x, int y)
    {
        if (x == R) {
            if (cellCheck(R-1,C-1) && cellCheck(R-1,0)) {
                // valid
                if (check_rotation()) {
                    count_valid++;
                }
            }
        } else if (y == C) {
            // finished fillign the row
            // don't forget to verify also the beginning of the row
            if (cellCheck(x,C-1) && cellCheck(x,0)) {
                backtrack(x + 1, 0);
            }
        } else {
            for (char ch = '1'; ch <= '3'; ch++) {
                board[x][y] = ch;
                bool valid = true;
                if (x > 0) {
                    valid = valid && cellCheck(x-1,y);
                }
                if (y > 0) {
                    valid = valid && cellCheck(x,y-1);
                }
                if (valid) {
                    backtrack(x,y+1);
                }
                board[x][y] = '?';
            }
        }
    }
    
    int solve()
    {
        board.resize(R);
        for (string &x : board) {
            x = string(C,'?');
        }
        seenBefore.clear();
        count_valid = 0;
        backtrack(0,0);
        return count_valid;
    }

Saturday, May 16, 2015

Cloudy Conway

I like twitter bots. Did you know that there's a sizable amount of twitter bots generating pictures algorithmically?

There's @fractweet , for example, keeps posting random mandelbrot pictures. Some of them can be pretty nice.

Another of my favorites is @greatartbot, it plays an art game by itself and posts the results. This generates a ton of colorful random pixel art.

A good thing about these twitter bots is they just work without your supervision and without you even remembering to run them. They keep making random pictures and posting them in twitter. When they have a following, there's even humans that can curate the resulting pictures for you.

I wanted to make some random art bot of my own. The big problem with these things is, if the method to generate them is too random and not interesting, the results will be a mess. If it is not random enough , the results might be very pretty but usually the same. You need some good balance.

Something that seems to generate hard-to-predict randomness that looks nice is Conway's game of life. So I wondered how to use its randomness for my silly at bot objective. Okay, most of the times you put a bunch of random live cells in a Conway simulation the eventual result looks like this:

But the interesting part is all the movement that results in this rather stable state. There's a good example in this page: http://knusper.net/knusperblog/2013/conway-s-game-of-life-in-python-numpy-matplotlib/

So I made a program, basically besides of the state of the cells, it also remembers the number of iterations that passed since each cell died. So we know the last iteration number in which each cell alive. Live cells have 0 in this value. So imagine that the total number of iterations was T. And the number of iterations a cell has been dead is X, if we divide X by T, we will get a number from 0 to 1. Now we will assign a different shade of gray to each cell. If the cell's value was 0, it would be black, if the value was 1, it would be white, but if the value was 0.5, it would be neutral gray...

It seems like a bunch of clouds. Apparently not very impressive. But to me this was perfect because it generates strange shapes and shades. We just need to add color. To add color, we turn this gray shade from 0.0 to 1.0 into a color spectrum. For example, let's make 0.0 Red, 0.5 Green and 1.0 Blue. This way 0.25 is Yellow and 0.75 is... a bluer green, I guess. This spectrum trick is what the Mandelbrot fractal from fractweet up there uses. Mandelbrot fractals are basically a fraud: All the beauty comes not from math but from picking colors for the values...


And this is really all of it. Just making different random choices for the number of colors in the spectrum and the initial live cells. Maybe also experiment with different sizes of Conway grids. Some additional parameters too. The result is a program that can generate fairly interesting pictures... A twitter bot that goes by the name @CloudConway.

So my first objective of making a twitter bot seems accomplished. But I think there's more to this whole method of generating interesting shapes from Conway's game of life. In the meantime, I plan to release source code for this bot when the code stops being embarrassing...