## 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.

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;

int sub_problem(vector<bool> &eng)
{
bitset<2180> english_words, french_words, inter;
for (int i = 0; i < N; i++) {
if (eng[i]) {
} else {
}
}
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;

for (int i = 0; i < N; i++) {
}
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;
}
}
}


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;
}


Ann Kilzer said...

These are gorgeous. I bet it would be fun to make them into tiling patterns. Please let me know if you ever release the code, I'd love to play with it. :)

blackle said...

This is my favourite art bot on twitter. I see that recent updates have experimented with interpolating the gradient over the larger scale as well. It looks amazing. Keep up the good work!!!

blackle said...

It appears that the generated images are tileable

Peter Renshaw said...

beautiful work

vexorian said...

That's a good idea but I am doing something else with backgrounds I think I will have to make a whole new post to explain.