import itertools

# List of columns, not rows.
# First column, first letter. Second column, second letter, etc
table = ["stuvö", "iktka", "ergaa", "nmlan"]
# table = ["uhsa","vtev","mäfs","ysär","nrts","oada","nedd","ssse"]
# table = ["nkpsnshy","nuöpuåaö","cmsnpiid","pmklpved","amrailea","rdakdneå","nlandeee","ndestssa"]
# table = ["afmskhc","eonpöhi","isimdlr","oifsntl","vfniaat","megeäal","rtrtrrn"]

word_length = len(table) # Number of columns

print("Remember to download a swedish wordlist!")
words = open("swedish-words.txt")
candidates = set()
for word in words:
    if len(word.strip()) == word_length:
        # -1 since word contains a newline
        candidates.add(word[:-1])


def f(prefixes, columns, candidate_prefixes):
    if not columns:
        return [prefixes]

    solutions = []

    next_column = columns[0]
    perms = itertools.permutations(next_column, len(next_column))
    for perm in perms:
        new_prefixes = [ prefix+[column_letter] for (prefix, column_letter) in zip(prefixes, perm) ]
        all_possible = True
        for prefix in new_prefixes:
            if not "".join(prefix) in candidate_prefixes:
                # print("No word", str(word_length)+"-letter word starts with: ", "".join(prefix))
                all_possible = False
                break

        if all_possible:
            solution =  f(new_prefixes, columns[1:], candidate_prefixes)
            if solution:
                solutions.extend(solution)

    return solutions


print(len(candidates), "words of length", word_length)
candidate_prefixes = set()
for word in candidates:
    prefix = ""
    for c in word:
        prefix += c
        candidate_prefixes.add(prefix)

print(len(candidate_prefixes), "possible prefixes from word list")

solutions = f([[c] for c in table[0]], table[1:], candidate_prefixes)

print()
print("Unique solutions: ")

distinct_strings = set()
for solution in solutions:
    distinct_strings.add( ",".join([ "".join(word) for word in solution]) )
print("\n".join(distinct_strings))


