#!/usr/bin/env python

# Copyright (c) 2012-2013, Christopher R. Wagner
#  
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#  
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#  
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""Pickle ball doubles matchup problem.

How to optimally choose matchups for a mixed doubles tournament of n
women and n men, where each person plays n-1 matches, to optimize
pairing so that each sex plays against all of the other members of
each sex, and is never teamed with the same person.

Convention is that men are 'ABCD...' and women are '1234...'

This can be cast as a sudoku style problem, where a grid needs to be
filled in with pairs, excluding the diagonal.
"""

from itertools import product
from copy import deepcopy


def initgrid(n):
    """Returns the grid of possibilities and the is_placed matrix."""
    pm = [False] * n * n
    for i in xrange(n):
        pm[i + n*i] = True

    men   = [chr(i+65) for i in xrange(n)]
    women = [str(i+1) for i in xrange(n)]
    g = []
    for irow in xrange(n):
        row = []
        other_men = list(men)
        del other_men[irow]
        for icol in xrange(n):
            if irow == icol:
                row.append('XX')
            else:
                other_women = list(women)
                del other_women[icol]
                row.append(''.join(''.join(t) for t in product(other_men, other_women)))
        g.extend(row)
    return g, pm


def unable_to_solve(g):
    return any(not c for c in g)


def is_solved(g, pm):
    return all(len(c) == 2 for c in g) and all(pm)

    
def has_choices(g):
    return any(len(c) > 2 for c in g)


def remove_from_grid(g, v):
    for i, choices in enumerate(g):
        g[i] = choices.replace(v, '')
    return g


def canplace(g, pm):
    for i, choices in enumerate(g):
        if len(choices) == 2 and not pm[i]:
            return i
    return None


def solve(n):
    g, pm = initgrid(n)
    return chooser(g, pm, n)


def findfirst(vals, fn):
    try:
        return (i for i, v in enumerate(vals) if fn(v)).next()
    except StopIteration:
        return None


def aschoices(choicestr):
    return (choicestr[2*i:2*i+2] for i in xrange(len(choicestr)/2))


def chooser(g, pm, n):
    if unable_to_solve(g):
        return None
    if is_solved(g, pm):
        return g
    iplace = canplace(g, pm)
    if iplace is not None:
        return chooser(*place(iplace, g[iplace], g, pm, n))
    # Have to make a choice
    ichoice = findfirst(g, lambda x: len(x) > 2)
    for v in aschoices(g[ichoice]):
        gcopy = chooser(*place(ichoice, v, deepcopy(g), deepcopy(pm), n))
        if gcopy:
            return gcopy
    return None
    

def place(i, v, g, pm, n):
    """Place both the site and the conjugate"""
    g, pm, n = _place(i, v, g, pm, n)
    conj_r = ord(v[0]) - 65
    conj_c = int(v[1]) - 1
    conj_i = conj_r * n + conj_c
    conj_v = chr((i / n) + 65) + str((i % n) + 1)
    return _place(conj_i, conj_v, g, pm, n)
    

def _place(i, v, g, pm, n):
    remove_from_grid(g, v)
    pm[i] = True
    man = v[0]
    woman = v[1]
    # Remove man and woman from row
    ir = i/n
    for ic in xrange(n):
        ichoice = ir*n + ic
        g[ichoice] = ''.join(c for c in aschoices(g[ichoice]) if (c[0] != man and c[1] != woman))
    # Remove man and woman from column
    ic = i % n
    for ir in xrange(n):
        ichoice = ir*n + ic
        g[ichoice] = ''.join(c for c in aschoices(g[ichoice]) if (c[0] != man and c[1] != woman))
    # Apply correct value
    g[i] = v
    return g, pm, n


def grid_to_str(g, n):
    return '\n'.join(' '.join(g[(i*n):(i+1)*n]) for i in xrange(n))


def usage():
    print ('pickleball.py n\n'
           'Solve mixed doubles tournament for n women and n men')


if __name__ == '__main__':
    import sys
    if len(sys.argv) != 2:
        usage()
    else:
        n = int(sys.argv[1])
        print grid_to_str(solve(n), n)


    
