r/programmingchallenges • • Jun 01 '11

Coloring a grid

Make a program to color in the squares of an (n x m) grid (with some number of colors > 2) such that no two same colors touch.

There is a 'brute force' way, and (at least one) more 'elegant' solution as well.

Edit: I didn't specify-- try one that will output a different pattern each time. It's a nicer problem, I think :)

21 Upvotes

38 comments sorted by

View all comments

Show parent comment

1

u/StoneCypher Sep 08 '11
iterate over cells as this_cell
    this_color_list = shuffle(all_colors)
    these_neighbors = neighbors_of(this_cell)
    may_continue = false;
    for(this_color_list = 0 to end as this_color) 
        if (this_color in colors_of(these_neighbors)) { next }
        else { this_cell.color = this_color; may_continue; break; }
    if (grid_complete) { yield }
    if (may_continue) { continue }
    backtrack_cell

2

u/kolm Sep 08 '11

Hmmh.. if I understand correctly, you randomly flip every cell to an allowed one (given the neighbours), if possible. Good idea, simple, straightforward.

But, correct me if I'm wrong, it seemse to me that this will not work for all start configurations. if you have only three colors and the starting pattern is, say,

1 2 3 
3 2 1 
2 1 3 

then the first "1" will never be flipped. If you start with a grid consisting of all 1s, OTOH, then you will never get a "1" on the first entry.

I think the solution will work perfectly if one justs randomly swaps all colors (so all "1"s are changed to, say "3"s, etc) as a first step.

1

u/StoneCypher Sep 08 '11

You're pretty close.

They don't get flipped. They are unassigned initially. There is no initial state; all states are always random.

This will be clearer to a programmer from a language where unassigned variables' contents are undefined, such as C or C++: there just wasn't an initial value.

1

u/kolm Sep 08 '11

That makes sense, of course, and is more efficient.

Do you think this will run into problems in higher dimensions, i.e. could you "paint yourself into a corner" with random color assignments where you run out of admissible colors? I am unsure, it naively looks like you have to find a color different from (theoretically at worst) 2dimension - 1 neighbouring colours, which could easily exhaust the number of colors available (not for 2 colors, obviously,and not in dimension 2of course).

1

u/StoneCypher Sep 08 '11

With a map in two dimensions and no discontiguous pieces in play, there always exists at least one coloring in four colors or fewer.

The proof took hundreds of years; this turns out to be a startlingly difficult problem, in the way that Fermat's was, and they ended up canonizing it to several hundred cases which got machine-checked. (It's not, strictly speaking, actually proven; rather, they found several hundred cases which represented every possible configuration, and enumerated them to show the lack of contrary cases. It's exhaustively non-disprovable, and mathematicians argue bitterly about whether that's a real proof.)

In higher dimensions, such a number exists, but gets progressively higher. It's actually more interesting to me to talk about alternative geometries. For example, just putting the map around a doughnut's surface, because of the weird edge joining, raises the needed color count to a minimum of seven, because it's possible to make a geometry where seven shapes all touch each other (not possible without the interior touching loop.)

Wikipedia claims there's a formula for this around the Euler characteristic of the shape - that's getting into topology, the branch of math which claims that doughnuts, coffee cups and the human body are all the same shape - and that's kind of way over my head. However, apparently the number of colors you need to color a surface, given the Euler shape number Chi, is floor( (7+sqrt(49-(24*Chi)))/2 ).

I have ... no idea why. But that's at least non-exponentiating. :D

1

u/kolm Sep 09 '11

With a map in two dimensions and no discontiguous pieces in play, there always exists at least one coloring in four colors or fewer.

That's a vastly more general and harder question than grid coloring, way out of my league. Grid coloring in any dimension works with two colors, cell with coordinates (x1, .., xn) gets colored with color = sum_{i} xi mod 2.

However, this does not guarantee one ends up with an admissible coloring using random color assignment (obviously, for two colors it always works due to lack of choice, you are forced into the one "correct" one). Imagine using three colors in three dimensions, is it not possible that one ends up with all already colored neighbors taking up all three possible colors? Can one find a simple way to avoid that?

1

u/StoneCypher Sep 09 '11

Exhaustive randomized depth first search will always find a coloring if a coloring exists.

Yes, there are dimensionalities for which certain color counts are too low. An easy way to display this in three dimensions is to display it in two dimensions then extend that, so, start with any example map which requires four colors, and put a hat on it.

It feels like I might be answering the wrong question.

2

u/manias Sep 08 '11

This seems wrong, wrt. the same probability part. Say You have 2x2 grid, 3 colors: R,G,B. You have currently:

RG
XX

You can complete 3 valid grids:

RG RG RG
GB GR BR

So somehow You'd have to ensure You choose G for the lower left corner 2 times as often as B

1

u/StoneCypher Sep 08 '11

Nah. The germane point is that the likelihood of that top corner being (color label 1) is identical to that of being (color label 2). If you start with BR instead of RG, you get the same stats with G in the corner instead of B.

If you think of it in terms of a canonical presentation - reflections, rotations, and colors reduced to first-seen - then seeing it as equally likely becomes trivial, because they're just the various expansions of the canonization, and each occur with identical frequency.

The probability of a legal board need not match the probability of an illegal board; therefore, the probabilities of individual cells cannot match, because corners, edges and centers have different fundamental distributions.

This was an interesting line of thought, and I enjoyed reading it. Thanks :)

3

u/manias Sep 08 '11

Nah :) Analyze my post again. The point You are missing is that by choosing a color for a cell, You choose among DIFFERENT SIZED subsets of solution space.

If You still don`t believe me, Your program for 2x2 should not be more than 20 lines of code. Count the frequencies of occurences of different solutions. Remeber that each time You run Your function You are only allowed to use the first result of the function (i.e. first "yield")

1

u/StoneCypher Sep 08 '11

The probability of a legal board need not match the probability of an illegal board; therefore, the probabilities of individual cells cannot match, because corners, edges and centers have different fundamental distributions.

The probability of a legal board need not match the probability of an illegal board; therefore, the probabilities of individual cells cannot match, because corners, edges and centers have different fundamental distributions.

These are the same thing said two different ways.

It's not the cells that need to be equally chosen from amongst; that's not possible. It's the boards.

3

u/manias Sep 08 '11

Now You owe me a beer:

http://pastebin.com/A1tWrdTz

3

u/igoro Sep 09 '11 edited Sep 09 '11

Manias is right. Some partly-filled boards have more valid completions than other boards, as the RG|G? vs RG|B? example shows. That's why randomly choosing one cell at a time is not correct.

Edit: It's not necessarily a small effect either. For example, consider the case with 3 colors, two-row grid, where the first row is (RGB) repeated:

RGBRGBRGBRGB
............

If you start the second row with a B, there is only one possible way to complete the grid. But if you start the second row with a G, there are many more completions (#columns-1, I believe).

1

u/StoneCypher Sep 09 '11

Please focus more on understanding what I said before chiming in that I'm incorrect. He's agreeing with me without realizing it.

The point of the canonization comment was that for every board starting RG, there's an equivalent board starting RB, one starting BG, one staring GB, one starting GR and one starting BR.

Every board has color duals; therefore they're all equally likely. Yes, you can construct one in a vacuum and observe that it has a different likelihood than another you construct in a vacuum; the duals even the probabilities out.

Uncontrolled sub-samplings do not represent the sample set.

1

u/StoneCypher Sep 09 '11

I'm sorry, but you seem to be misunderstanding me. When I said "these are the same thing said two different ways," that was me telling you that I agreed, and had already said that.

1

u/artanis2 Sep 13 '11

awap's implementation is bad, though I suspect you know that. Here is mine, and the results: ~/src/coloring_grid # time echo 2 2 2 | ./a.out 1 0 0 1 real 0m0.004s user 0m0.000s sys 0m0.000s

~/src/coloring_grid # time echo 5 5 2 | ./a.out
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
0 1 0 1 0
1 0 1 0 1
real    0m0.007s
user    0m0.000s
sys     0m0.004s

~/src/coloring_grid # time echo 25 25 5 | ./a.out
0 3 1 2 0 4 2 1 0 1 4 0 3 0 1 0 4 3 1 3 2 0 3 1 4
1 0 2 1 4 1 0 2 3 4 2 4 1 2 0 4 0 4 3 2 0 1 0 4 2
3 2 1 3 1 3 4 0 2 0 3 2 3 0 1 0 2 0 1 3 4 0 3 2 3
2 3 0 4 3 1 3 1 0 4 0 4 2 4 2 3 1 4 3 0 2 4 2 0 4
1 2 3 2 4 2 4 2 1 2 1 2 1 3 0 4 3 2 4 3 1 3 4 1 3
0 4 1 0 2 1 3 4 3 4 2 3 4 1 3 0 2 4 1 2 3 4 0 4 2
4 1 3 1 0 3 0 1 0 2 0 4 0 4 2 3 4 0 4 1 4 1 4 0 3
3 2 1 3 1 2 3 4 1 3 1 2 1 2 1 4 1 2 0 2 0 4 2 4 1
2 1 4 2 0 4 2 0 2 4 2 4 3 0 4 2 0 4 1 4 1 2 4 2 0
3 2 0 1 3 1 4 2 3 2 1 3 4 3 0 1 4 1 0 3 0 3 0 4 2
4 1 3 0 2 0 3 1 0 1 3 2 1 4 3 0 2 4 1 2 1 4 3 1 3
1 3 2 3 4 3 2 4 1 0 4 3 0 2 0 2 4 0 4 0 4 0 4 3 1
0 1 4 0 2 1 4 3 0 2 1 0 4 3 4 1 3 2 1 2 0 2 3 0 3
3 4 1 2 4 2 3 0 3 4 0 3 1 0 3 4 2 0 3 0 1 4 1 2 4
1 2 4 3 0 1 2 3 1 3 4 0 3 2 0 2 3 4 1 3 2 3 2 1 2
4 1 2 4 3 2 4 1 4 0 2 4 1 0 4 3 4 2 4 2 1 4 1 3 1
3 2 0 1 4 1 3 0 2 3 0 1 4 1 0 2 3 0 2 3 0 3 4 0 2
4 0 2 3 1 3 4 3 4 2 1 3 1 2 1 0 1 4 1 0 4 2 0 3 0
3 2 3 1 2 1 2 1 2 1 3 2 0 1 0 2 4 2 0 1 3 0 3 4 3
0 3 4 2 3 4 1 3 4 0 2 4 3 0 4 0 1 3 1 3 4 1 2 1 2
4 0 2 3 0 3 2 1 0 3 4 1 0 3 0 1 2 0 2 1 3 2 4 0 3
2 3 1 2 3 2 3 0 2 1 3 0 2 1 2 0 3 1 3 0 4 0 3 1 4
4 1 4 0 2 0 1 4 1 2 0 3 1 3 0 4 0 2 0 2 3 4 0 4 3
1 0 1 3 4 1 2 3 0 4 1 4 0 4 3 1 3 1 2 1 0 1 2 1 4
3 1 4 0 2 4 0 2 3 2 0 3 4 2 4 3 1 2 3 2 3 4 0 4 1
real    0m0.008s
user    0m0.000s
sys     0m0.004s

100x100 5 color 0.028s
100x200 5 color 0.062s
100x400 5 color 0.110s
100x800 5 color 0.200s
200x800 5 color 0.348s
400x800 5 color 0.720s

Pretty clearly linear. Disabling the output saves a significant amount of time as well.

0

u/julesjacobs Sep 08 '11

Yup, that's an optimization of brute force rejection sampling, but might still be extremely slow. Can you compute the expected running time?

1

u/igoro Sep 09 '11

If I understand the algorithm right, it should never backtrack, assuming that you iterate over cells in a row-major or column-major order.

Whenever you are coloring a cell, no more than two of its neighbors already have colors assigned. Since there are at least 3 colors available, there must be at least one color available to assign to the current cell. Hence, the algorithm is 'greedy' and never reaches the point where it needs to backtrack. So, the complexity is O(N x M), which is optimal.

As mentioned on another part of this thread, though, there is an issue with the randomness of this algorithm: some boards are more likely to be generated than other boards.

1

u/StoneCypher Sep 08 '11

Yup, that's an optimization

No, it isn't.

of brute force rejection sampling, but might still be extremely slow

No, it won't be. This is a depth first search of an extremely sparse tree. In the grid example context of the original article, it will backtrack zero times per run. It takes a very complicated map to get even a trivial number of backtracks, and even with a relatively large number of backtracks, the work is log proportional.

This is going to be lightning fast on gigantic maps on trivial hardware. Stop pretending to see difficulties that aren't actually there and just try running it.

Can you compute the expected running time?

Why would I want to? You should be able to color a 20k cell hex map this way on a GameBoy Advance (16mHz ARM7, ~800 cycles/cell) in under a second.

1

u/julesjacobs Sep 08 '11

Yup, that's an optimization No, it isn't. of brute force rejection sampling

Yes, it is. It is exactly rejection sampling with early stopping.

This is going to be lightning fast on gigantic maps on trivial hardware. Stop pretending to see difficulties that aren't actually there and just try running it.

It highly depends on which order you iterate over the cells, which you didn't specify in your code. I can easily find an order of iteration that gives you a substantial probability of taking a billion years to fill a 20x20 grid. I can also easily give you a map on which any iteration order will take a billion years with substantial probability.

1

u/StoneCypher Sep 08 '11

I love how you run two different things I said together, to make it look like I said something different than what I said.

Yup, that's an optimization

No, it isn't. [of brute force rejection sampling]

Yes, it is. It is exactly rejection sampling with early stopping.

No, it isn't. This is simple depth-first search. There is no sampling process other than metaphor, and there is no "early stopping," only search.

This is not an "optimization." This is a rudimentary description of unoptimized depth first search.

Please stop arguing now. This can very easily be refined from where it is; calling it optimized and referring to it by radically the wrong names just makes you look like a novice.

Pretending that something is optimized brute force merely because it doesn't do any brute forcing is stupid.

It highly depends on which order you iterate over the cells, which you didn't specify in your code.

Since you don't appear to know much about computer science, I'll remind you that iteration is ordered first to last, which is what makes it different than random or unordered access. The first to last order of a grid is quite clear, and reflection and rotation don't make any difference.

So unless you're pretending that scatter or spiral or something stupid are legitimate interpretations of iteration, I'd wager that you're just desperately scrambling to invent technicalities to cover for the rudimentary error you made.

I can easily find an order of iteration that gives you a substantial probability of taking a billion years to fill a 20x20 grid.

No. You can't. You're just making up big-sounding numbers. The worst possible ordering will take less than five minutes on a gameboy advance.

You don't actually understand this problem as deeply as you seem to imagine that you do.

I can also easily give you a map on which any iteration order will take a billion years with substantial probability.

No. You can't.

I invite you to prove your own claim now. I'm getting tired of amateur hour at the big-sounding claims podium.

There isn't enough hard drive space on earth to make a map I can't four-color in a matter of hours; the only way to make this slow is to make things so absurdly large that you start hitting machine limits, which is on the order of mapping every city block on earth as a discrete polygon.

You don't know what you're talking about.

2

u/julesjacobs Sep 08 '11

No, it isn't. This is simple depth-first search. There is no sampling process other than metaphor, and there is no "early stopping," only search.

Please stop arguing now. This can very easily be refined from where it is; calling it optimized and referring to it by radically the wrong names just makes you look like a novice.

Right well. I do mathematics, and the well known technique to solve this class of problems mathematicians call rejection sampling. It seems that you are from a different field, so sorry to have confused you with this terminology.

Since you don't appear to know much about computer science, I'll remind you that iteration is ordered first to last, which is what makes it different than random or unordered access. The first to last order of a grid is quite clear, and reflection and rotation don't make any difference.

No need to resort to ad-hominems, it just makes one seem stupid. Since the order of iteration is the crucial element of your algorithm, you should not leave the critical part out of the description.

No. You can't. You're just making up big-sounding numbers. The worst possible ordering will take less than five minutes on a gameboy advance.

You don't actually understand this problem as deeply as you seem to imagine that you do.

Okay, I'll show you. If you first iterate over all the even columns, and then all the odd columns, chances are good that your algorithm will take exponential time. If you don't believe me then try it. Or iterate over the grid randomly, nearly all iteration orders will result in exponential runtime of your algorithm.

No. You can't.

I invite you to prove your own claim now. I'm getting tired of amateur hour at the big-sounding claims podium.

Since this problem is NP-complete, take any reasonably sized graph coming from the reduction of a hard SAT instance to graph coloring.

You don't know what you're talking about.

If your algorithm really works as well as you think it does, go collect your Turing award and $1M Clay prize.

1

u/StoneCypher Sep 08 '11

Right well. I do mathematics

Not enough to know the difference between optimized brute force and never-was-brute-force-in-the-first-place, apparently.

You strike me as one of those people who thinks that everything is a specialized case of random brute force sampling. The equivalent kind of idiot in computer science will point out that essentially everything is turing complete; it's as meaningless a non-observation as yours is.

Let me be perfectly clear with you. You're looking at a simple iteratative algorithm with the shuffle button turned on. THAT IS NOT WHAT BRUTE FORCE MEANS. Brute force means trying every possible end result, not taking one measured step at a time.

and the well known technique to solve this class of problems mathematicians call rejection sampling

Just because there's a technique which is well known to mathematicians doesn't mean you have correctly identified its use.

Here is a case example where you have not.

so sorry to have confused you with this terminology.

That you have made a mistake is not a case of my having gotten confused. You're just making a pile of unjustified assertions then presuming superiority when someone points out the critical logical errors underpinning your claim.

This is not rejection sampling because:

  1. No answers are ever sampled under any circumstances
  2. There is no envelope distribution
  3. There is no instrument distribution
  4. There is no target distribution
  5. There is no unconditional acceptance probability
  6. The set of answers is never generated
  7. No individual complete answer is ever rejected
  8. This is not a monte carlo generation, on which rejection sampling is reliant
  9. The envelope principle makes no sense in this context
  10. U(0,1) is geometrically larger than your grandchildren's computer will be able to handle for real-world maps
  11. The unit interval makes no sense in combinatorics
  12. You pretend to be a mathematician on TV, but actually are operating entirely in the realm of pretentious metaphor, where mathematicians frequently learn that the reason software engineers don't take them seriously is they don't actually understand the software engineering they think they're describing in metaphor but are not

Rejection sampling is where you generate a complete answer at random, then measure it, and either throw it back into the pool or accept it. Its purpose is not to find answers, but rather to see the rate of rejection as a ratio.

You are 100% full of crap.

No need to resort to ad-hominems

Logic: another field you shouldn't be pretending to understand. Ad hominem is not a fancy way to say insult, and I have not made any logic which is reliant on insults. This is simply incorrect.

it just makes one seem stupid

Funny how you complain about insults, then insult in the same sentence. I have a word. It starts with "hypocri" and ends with "e". Can you find the missing letters?

Since the order of iteration is the crucial element of your algorithm

Actually, it isn't. What you may have meant was "since the order of iteration can impact the neighbor workload." The critical (not crucial, get an english book please) element is actually the single-pass scan. Consider reading a book by Dijkstra.

I find this particularly hilarious since you tried to ask me if I could compute the workload of the algorithm, and it's becoming apparent that you cannot.

you should not leave the critical part out of the description.

  1. I did not
  2. Crucial != critical
  3. That you don't know the basics of what the word means, and therefore assume incorrectly that information which is there is not, doesn't affect me any more than if someone talked about the school year and you said "you left out that it starts in September." No, dear, I didn't leave that out; your education did. (Notably, this was discussed in a number of books an actual mathematician would have read, and is a critical part of number theory.)

Okay, I'll show you. If you first iterate over all the even columns, and then all the odd columns, chances are good that your algorithm will take exponential time.

No it won't. Please take a breath and try it, instead of hand-waving about imaginary trap cases you set. In either of those cases there are a worst case of two neighbors; every cell can be filled with zero backtracking.

Maybe you missed that part where I told you the worst case wasn't a problem. Maybe you just are too far from being a mathematician to know how to find the worst case. Maybe for all your talk of what I don't get, you don't actually know how to measure the worst case and figure out how much work it is.

Does it bother you that you're wildly speculating about a well defined, easily bounded thing which earlier you were haughtily challenging others to find, then giving hilariously easy to beat examples which, if you had bothered to think them through, don't actually support you in any way?

I mean hell, if you just do a checkerboard then fill in the rest you're in a way worse position than the silly case you described, and it's still an under-one-second scan.

You just don't know what you're talking about.

If you don't believe me then try it.

I don't need to. I just found the worst case and tried that, which I told you before this response.

You aren't reading what's being said to you very successfully.

Or iterate over the grid randomly, nearly all iteration orders will result in exponential runtime of your algorithm.

It's funny how you keep saying this, apparently blissfully unaware that it is completely wrong, and that the reason for that was already explained to you.

Since this problem is NP-complete

Looooolooooool.

You think this is SAT?

You aren't even enough of a mathematician to know the difference between the complexity of coloring contiguous maps and coloring arbitrary graphs?

C'mon, Jean-Claude. You said you could easily provide an example. I pulled your card, because you can't.

Instead of giving an example, you gave a link to an unrelated math problem that you think is the same thing, and thought you succeeded.

I'll say it again.

You made the claim that you can give a map on a square grid which produces exponential growth that will take billions of years to complete.

I laughed in your face and told you to do it.

You failed.

Show me one such grid and I'll solve it after work. Hell, show me three.

You don't know what you're talking about, and you made multiple claims of ability which, when challenged, you are backing away from.

If your algorithm really works as well as you think it does, go collect your Turing award and $1M Clay prize.

Randomized depth first search is not my algorithm, and there are no clay prizes it satisfies. The Turing award would never be handed out for an algorithm which was well understood more than two hundred years before Turing was born.

Go on. Show me that billion year grid, since you're so certain you can produce it easily, and held that up as proof of your position.

Holding up an unrelated thing and waiting for the chance to say "it's not unrelated, you just don't get it" is not actually a case of your having shown that billion year grid you claimed you could make so easily.

For all your talk, you still have no idea what you're talking about, and you can't produce the things you claim you can.

Not A Real Mathematician (tm).

2

u/julesjacobs Sep 08 '11

This is not rejection sampling because: [snip] Rejection sampling is where you generate a complete answer at random, then measure it, and either throw it back into the pool or accept it. Its purpose is not to find answers, but rather to see the rate of rejection as a ratio.

Nice cutting and pasting words from wikipedia. I think you missed the word "sampling" in rejection sampling. What you're describing is generally called "inference", and indeed you can use rejection sampling as a subroutine to do approximate inference.

No it won't. Please take a breath and try it, instead of hand-waving about imaginary trap cases you set. In either of those cases there are a worst case of two neighbors; every cell can be filled with zero backtracking.

Maybe you missed that part where I told you the worst case wasn't a problem. Maybe you just are too far from being a mathematician to know how to find the worst case. Maybe for all your talk of what I don't get, you don't actually know how to measure the worst case and figure out how much work it is.

You claiming that the worst case isn't a problem doesn't change the facts. Fact is it is a problem. With 2 colors and filling in even columns first then odd columns can lead to exponential backtracking. For example, if the algorithm happens to select the first cell in the top row as "red" and the third cell in the top row as "blue". Then your algorithm with happily continue filling in the grid until it has to fill in the second cell in the first row. At that point it will backtrack an exponential number of times all the way back up to the third cell in the first row.

You aren't even enough of a mathematician to know the difference between the complexity of coloring contiguous maps and coloring arbitrary graphs?

You said arbitrary map, and it would be most logical to assume that you meant arbitrary map not just a map on a grid. A map on a grid is obviously a trivial problem since it is strictly simpler than a full grid, and I dismissed the possibility that you'd make such a trivial claim.

I'm still confused about whether you're an educated troll or not.

→ More replies (5)