Post Reply 
Fifteen puzzle solvability, Numworks Python
04-09-2020, 03:19 PM (This post was last modified: 04-25-2020 02:15 PM by Albert Chan.)
Post: #8
RE: Fifteen puzzle solvability, Numworks Python
It may be best if the code return (Xrows, inversions), rather than Xrows + inversions

Inversion count are unaffected if the X is removed from the list.
To generalize for nxn board, we have:

Code:
def board(a, n=4):      # default 4x4 board
    a=list(a)           # copy
    x=a.index(0)        # locate X
    b=a.pop(x)          # remove X
    for i,ai in enumerate(a):
        for aj in a[i+1:]:
            if aj<ai: b += 1
    return 1+x//n, b    # Xrows, inversions

>>> board([11,0,3,8,1,6,15,10,7,14,2,13,4,12,9,5])     # even n and even sum → solvable
(1, 51)
>>> board([15,9,2,14,4,6,0,8,11,1,13,3,7,12,5,10])     # even n and even sum → solvable
(2, 56)

For a 3x3 board, example from https://www.geeksforgeeks.org/check-inst...-solvable/

>>> board([1,8,2,0,4,3,7,6,5], n=3)                            # odd n and even inversions → solvable
(2, 10)
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Fifteen puzzle solvability, Numworks Python - Albert Chan - 04-09-2020 03:19 PM



User(s) browsing this thread: 1 Guest(s)