The United States has a unique love of gerrymandering––the deliberate manipulation of an electoral district to predict certain voting results. Just recently there was a gerrymandering case brought before the Supreme Court. Gerrymandering, especially when related to race, is ruled illegal and results in the requirement to redraw the district lines.

Given a rectangular map of a municipality (2d array), you will draw district lines to help your party get the most representation. That is, you will gerrymander. Every municipality has two parties, 0 and 1. The map will be comprised of squares with either 0 or 1 on them. Here is an example map:


You will group the map into districts so that the 1 party will get at least the number of districts specified by the Input.


The input will consist of a map, the number of districts to draw, and the minimum number of districts the 1 party needs to win (the minimum score).


The output will be a map of the districts. Each district will be uniquely comprised of a capitalized letter of the alphabet. Yes, this means that there will not be more than 26 districts.

If there is no possible output where the inputted party wins enough districts, either:

  1. Print “We tried...”
  2. Fatally error because the party was irreparably injured by the election results
  3. Or both

Rules (also very important)

  1. All districts must be contiguous
  2. Districts may not have other districts in them
  3. Each district must have at least four nodes in it. The input will be consistent with the rules, meaning that there will be at least number_of_districts * 4 nodes in the map
  4. The score of each party is the number of districts it has a majority in
  5. If a district has the same number of 0s and 1s, then neither party benefits from it
  6. Normal no-cheating rules
  7. This is , so shortest code in bytes wins.

Test cases

1. Input       1. Output       2. Input       2. Output     3. Input      3. Output
districts: 5   Image and map   districts: 3   Image below   districts: 3  fatal error
min wins: 3                    min wins: 3                  min wins: 3
map:                           map:                         map:
00000110000    AAAAAAAAAAA     101101                       101101
10000010000    AAAAAAAAAAA     100000                       100000
10010000011    AAAAAAAAAAA     011011                       011011
11001110000    BBBBBBBAAAA     111111                       100111
00111111000    BBBBBBBAAAA     
01111111000    CCCCCDDDAAA     
01111111001    CCCCCDDDAAA     
01000111100    EEEEEDDDDDD     
00000001000    EEEEEDDDDDD     

Of course, your program should work for any valid test case, not just these ones.

  • \$\begingroup\$ @Arnauld, yes they are only illustrative. The real output should be like in the first test case with the letters of the alphabet. I changed the tag to reflect this. \$\endgroup\$
    – Daniel
    Commented Nov 29, 2017 at 22:39
  • \$\begingroup\$ A simple partition of the first test case would be something like this. Is that correct? \$\endgroup\$
    – Arnauld
    Commented Nov 29, 2017 at 22:53
  • \$\begingroup\$ @Arnauld, yes, that's valid. \$\endgroup\$
    – Daniel
    Commented Nov 29, 2017 at 23:00
  • \$\begingroup\$ So for the 3rd example, if we divided it into horizontal rows, each 1 district tall, then the 1s would win 3 to 1 yes? \$\endgroup\$ Commented Nov 29, 2017 at 23:20
  • 3
    \$\begingroup\$ This reminds me a whole lot of what had to be done for char based graphics on Nintendo handhelds from DMG up to DS. You were given specific shapes to cut graphics into and had to minimize the number of shapes used as you could only have a hardware defined number of sprites (shapes) in use. That was not an easy problem. \$\endgroup\$ Commented Nov 29, 2017 at 23:39

2 Answers 2


R, 938 896 858 952 bytes

function(N,M,m){U="We tried...
if((K(m)<M&(N-M)<1)|K(m>0)<(3*M))cat(U) else{j=max(1,nrow(m))
if(K(m[r==p]>1))r[Y[1]]=p else r[Y[L(Y)]]=p}}
if(a<(k^2)){for(v in 1:R){if(K(m[r==v])>0){r[r==v]=max(k,max(r))+1
for(v in 1:R)r[r==v]=max(k,max(r))+1
for(v in G(c(r)))g=g|(K(r==v)<4)|(L(G(r[H(W(r==v))]))+C(v))<3}}
if(g)cat(U) else{u=G(c(r))
for(v in 1:L(u))r[r==u[v]]=v

Try it online!

A massive >900 >800 (nope!) >900 bytes solution. The code works as follows. Let N be the number of electoral districts and M the minimum number of district where 1 wishes to have a majority.

First, the code randomly assigns N districts to different groups. Next, it randomly expands them, i.e. adds a district to a randomly selected group, ensuring that the district is next to a district already belonging to that group. In the expansion process, it gives precedence to a district with a 1 majority, if the district group is not yet a full 1 majority; if the group is already a certain 1 majority, then it gives precedence to a 0 district. It continues until all districts have been assigned.

Every group where there is a majority for the 1 party is stored, and its districts are locked. If there are at least M groups with a majority of 1, then everything is good and we can print the result we can check whether there are at least 4 districts in each group. If the cutoff of 4 districts is met, then we can happily print the result. Otherwise, the code tries to reassign the districts that are not locked to as many groups as available, i.e. N - #stored-groups.

The codes tries a few times (9 times). If it fails, it resets everything and starts again. It does so for other 9 times before giving up and printing "we tried...".

If the code does not succeed at first, try again a few times. I tuned the number of repetitions such that it can run in TIO under a minute. However if there is a solution, this code can (eventually) find it. The randomness part of the algorithm gives a non-zero probability that, if there is a solution, it can find it. The limited number of trials is the only limiting factor to success.

EDIT: added the control that no district group can be fully surrounded by just another one, unless the district group has districts on the edge of the given square. I think I missed it at first.

  • \$\begingroup\$ Can you remove any newlines? \$\endgroup\$ Commented Dec 1, 2017 at 1:57
  • \$\begingroup\$ I did. I also assigned longer function names to single letters, and replaced a few ==0 with <1 when the variable was strictly integer and positive. \$\endgroup\$
    – NofP
    Commented Dec 1, 2017 at 11:55
  • 1
    \$\begingroup\$ There's a lot of stuff here that can be trivially golfed but this is a good first attempt at an answer, so +1, and I'll be suggesting edits I a couple hours once I'm not on my phone! \$\endgroup\$
    – Giuseppe
    Commented Dec 1, 2017 at 12:32
  • 1
    \$\begingroup\$ 858 bytes -- "regular" golfs, cleaning up the use of braces with if...else statements, swapping c for as.vector, changing "\n" with literal newlines, and using the fact that > will automatically coerce numbers to characters silently and compare their codepoints. There's probably some other golfs I did that I can't remember but this is a start. I think there are a few more things we can tweak down but I'm not 100% sure I understand the code... \$\endgroup\$
    – Giuseppe
    Commented Dec 1, 2017 at 15:15
  • \$\begingroup\$ Nice one! I took inspiration. By comparing to your code I also found a bug in mine that would sometimes lead to very small district groups (less than 4 districts). It is now fixed. \$\endgroup\$
    – NofP
    Commented Dec 1, 2017 at 18:20

Python3, 1067 bytes:

def P(b):
 c=[(x,y)for x,r in E(b)for y,_ in E(r)]
 while c:
  while q:
   for X,Y in[(0,1),(0,-1),(-1,0),(1,0)]:
    if T in c and T not in s and b[x+X][y+Y]==b[x][y]:q+=[T];s+=[T]
  yield s;c=[*{*c}-{*s}]
def S(b,g):
 for x,y in g:k[b[x][y]]+=1
 return k[1]>k[0]
def F(n,m,b):
 for G in P(B):
  if len(G)<4:
   for x,y in G:B[x][y]=int(not B[x][y])
 q=[(B,L:=[*P(B)],sum(S(b,i)for i in L))]
 while 1:
  O=max(j for k in B for j in k)+1
  if len(G)==n and sum(S(b,i)for i in G)>=m:
   for Y,i in E(G,65):
    for x,y in i:B[x][y]=chr(Y)
   return B
  for x in R(len(b)+1):
   for y in R(len(b[0])+1):
    for X in R(x+1,len(b)+1):
     for Y in R(y+1,len(b[0])+1):
      if(X-x)*(Y-y)>=4 and S(b,T:=[(j,k)for j in R(x,X)for k in R(y,Y)]):
       for U,I in T:Q[U][I]=O
       if len(W:=[*P(Q)])<=n and len(W)>=len(G)and W not in H and all(len(i)>=4 for i in W)and(N_C:=sum(S(b,i)for i in W))>=C:q+=[(Q,W,N_C)];H+=[W]

Try it online!


  1. A little longer than the other solution, but deterministic and runs in ~3.65 seconds
  2. Fatally-errors if there is no possible output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.