Programming Contest Question: Counting Polyominos

后端 未结 7 673
醉酒成梦
醉酒成梦 2020-12-15 11:33

Please see my own answer, I think I did it!


Hi,

An example question for a programming contest was to write a program that finds out ho

7条回答
  •  庸人自扰
    2020-12-15 12:03

    Here's some python that computes the answer. Seems to agree with Wikipedia. It isn't terribly fast because it uses lots of array searches instead of hash tables, but it still takes only a minute or so to complete.

    #!/usr/bin/python                                                                                                                                                 
    
    # compute the canonical representation of polyomino p.                                                                                                            
    # (minimum x and y coordinate is zero, sorted)                                                                                                                    
    def canonical(p):
      mx = min(map(lambda v: v[0], p))
      my = min(map(lambda v: v[1], p))
      return sorted(map(lambda v: (v[0]-mx, v[1]-my), p))
    
    # rotate p 90 degrees                                                                                                                                               
    def rotate(p):
      return canonical(map(lambda v: (v[1], -v[0]), p))
    
    # add one tile to p                                                                                                                                               
    def expand(p):
      result = []
      for (x,y) in p:
        for (dx,dy) in ((-1,0),(1,0),(0,-1),(0,1)):
          if p.count((x+dx,y+dy)) == 0:
            result.append(canonical(p + [(x+dx,y+dy)]))
      return result
    
    polyominos = [[(0,0)]]
    
    for i in xrange(1,10):
      new_polyominos = []
      for p in polyominos:
        for q in expand(p):
          dup = 0
          for r in xrange(4):
            if new_polyominos.count(q) != 0:
              dup = 1
              break
            q = rotate(q)
          if not dup: new_polyominos.append(q)
      polyominos = new_polyominos
      print i+1, len(polyominos)
    

提交回复
热议问题