Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as Python by onanimous ( 17 years ago )
from __future__ import print_function
from itertools import permutations
import psyco
psyco.full()

def neighbours(pos):
	yield (pos[0] + 1, pos[1]    ) 
	yield (pos[0] - 1, pos[1]    ) 
	yield (pos[0]    , pos[1] + 1) 
	yield (pos[0]    , pos[1] - 1) 

def minshape(s):
	return (s[0][0], min(p[1] for p in s)) 

def maxshape(s):
	return (s[len(s) - 1][0], max(p[1] for p in s))
	

def generateShapes(pieces):
	assert pieces > 0
	if pieces == 1: return [((0, 0),)]
	prevShapes = generateShapes(pieces - 1)
	newShapes = set()
	for shape in prevShapes:
		n2 = set(n for p in shape for n in neighbours(p) if n not in shape)
		for p in n2:
			ns = list(shape)
			ns.append(p)
			ns.sort()
			xmin, ymin = minshape(ns)
			if xmin != 0 or ymin != 0:
				ns = [(p[0] - xmin, p[1] - ymin) for p in ns]
			newShapes.add(tuple(ns))
	return newShapes

def calculateMoves(position, shape, shiftx, shifty):
	return sum(abs(p[0] - s[0] - shiftx) + abs(p[1] - s[1] - shifty)
				for p, s in zip(position, shape))
	
def solve(position, shapes):
	m = 1000000
	solution = None
	for shape in shapes:
		mx, my = maxshape(shape)
		mx, my = (5 - mx, 5 - my)
		for ps in permutations(shape):
			for shiftx in range(mx): 
				for shifty in range(my):
					r = calculateMoves(position, ps, shiftx, shifty) 
					if m > r: 
						m = r
						solution = tuple(sorted((p[0] + shiftx, p[1] + shifty) for p in ps)) 
	return (m, solution)		
	
def str2shape(s):
	sh = ((x, y) for y, l in enumerate(s.strip().split())
				 for x, c in enumerate(l.strip())
				 if c != '.')
	return tuple(sorted(sh))

def shape2str(s):
	lines = [["."] * 5 for _ in range(5)]
	for p in s:
		lines[p[1]][p[0]] = "x"
	return "
".join("".join(l) for l in lines)

question = """
.....
.XX..
.....
.....
..XXX
"""

shape = str2shape(question)
print(shape)
print(shape2str(shape))
shapes = generateShapes(len(shape))
print(len(shape), len(shapes))
m, sol = solve(shape, shapes)
print(m, sol) 
print(shape2str(sol))

 

Revise this Paste

Your Name: Code Language: