Task: 15 puzzle solver







Python: import random


class IDAStar:
    def __init__(self, h, neighbours):
        

        self.h = h
        self.neighbours = neighbours
        self.FOUND = object()


    def solve(self, root, is_goal, max_cost=None):
        

        self.is_goal = is_goal
        self.path = [root]
        self.is_in_path = {root}
        self.path_descrs = []
        self.nodes_evaluated = 0

        bound = self.h(root)

        while True:
            t = self._search(0, bound)
            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
            if t is None: return None
            bound = t

    def _search(self, g, bound):
        self.nodes_evaluated += 1

        node = self.path[-1]
        f = g + self.h(node)
        if f > bound: return f
        if self.is_goal(node): return self.FOUND

        m = None 
        for cost, n, descr in self.neighbours(node):
            if n in self.is_in_path: continue

            self.path.append(n)
            self.is_in_path.add(n)
            self.path_descrs.append(descr)
            t = self._search(g + cost, bound)

            if t == self.FOUND: return self.FOUND
            if m is None or (t is not None and t < m): m = t

            self.path.pop()
            self.path_descrs.pop()
            self.is_in_path.remove(n)

        return m


def slide_solved_state(n):
    return tuple(i % (n*n) for i in range(1, n*n+1))

def slide_randomize(p, neighbours):
    for _ in range(len(p) ** 2):
        _, p, _ = random.choice(list(neighbours(p)))
    return p

def slide_neighbours(n):
    movelist = []
    for gap in range(n*n):
        x, y = gap % n, gap // n
        moves = []
        if x > 0: moves.append(-1)    
        if x < n-1: moves.append(+1)  
        if y > 0: moves.append(-n)    
        if y < n-1: moves.append(+n)  
        movelist.append(moves)

    def neighbours(p):
        gap = p.index(0)
        l = list(p)

        for m in movelist[gap]:
            l[gap] = l[gap + m]
            l[gap + m] = 0
            yield (1, tuple(l), (l[gap], m))
            l[gap + m] = l[gap]
            l[gap] = 0

    return neighbours

def slide_print(p):
    n = int(round(len(p) ** 0.5))
    l = len(str(n*n))
    for i in range(0, len(p), n):
        print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n]))

def encode_cfg(cfg, n):
    r = 0
    b = n.bit_length()
    for i in range(len(cfg)):
        r |= cfg[i] << (b*i)
    return r


def gen_wd_table(n):
    goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]
    goal[-1][-1] = n - 1
    goal = tuple(sum(goal, []))

    table = {}
    to_visit = [(goal, 0, n-1)]
    while to_visit:
        cfg, cost, e = to_visit.pop(0)
        enccfg = encode_cfg(cfg, n)
        if enccfg in table: continue
        table[enccfg] = cost

        for d in [-1, 1]:
            if 0 <= e + d < n:
                for c in range(n):
                    if cfg[n*(e+d) + c] > 0:
                        ncfg = list(cfg)
                        ncfg[n*(e+d) + c] -= 1
                        ncfg[n*e + c] += 1
                        to_visit.append((tuple(ncfg), cost + 1, e+d))

    return table

def slide_wd(n, goal):
    wd = gen_wd_table(n)
    goals = {i : goal.index(i) for i in goal}
    b = n.bit_length()

    def h(p):
        ht = 0 
        vt = 0 
        d = 0
        for i, c in enumerate(p):
            if c == 0: continue
            g = goals[c]
            xi, yi = i % n, i // n
            xg, yg = g % n, g // n
            ht += 1 << (b*(n*yi+yg))
            vt += 1 << (b*(n*xi+xg))

            if yg == yi:
                for k in range(i + 1, i - i%n + n): 
                    if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:
                        d += 2

            if xg == xi:
                for k in range(i + n, n * n, n): 
                    if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:
                        d += 2

        d += wd[ht] + wd[vt]

        return d
    return h




if __name__ == "__main__":
    solved_state = slide_solved_state(4)
    neighbours = slide_neighbours(4)
    is_goal = lambda p: p == solved_state

    tests = [
        (15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2),
    ]

    slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)

    for p in tests:
        path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)
        slide_print(p)
        print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves))
        print(cost, num_eval)





Ada: with Ada.Text_IO;

procedure Puzzle_15 is

   type Direction is (Up, Down, Left, Right);
   type Row_Type is range 0 .. 3;
   type Col_Type is range 0 .. 3;
   type Tile_Type is range 0 .. 15;

   To_Col : constant array (Tile_Type) of Col_Type :=
     (3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2);
   To_Row : constant array (Tile_Type) of Row_Type :=
     (3, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3);

   type Board_Type is array (Row_Type, Col_Type) of Tile_Type;

   Solved_Board : constant Board_Type :=
     ((1,   2,  3,  4),
      (5,   6,  7,  8),
      (9,  10, 11, 12),
      (13, 14, 15, 0));

   type Try_Type is
      record
         Board : Board_Type;
         Move  : Direction;
         Cost  : Integer;
         Row   : Row_Type;
         Col   : Col_Type;
      end record;

   Stack : array (0 .. 100) of Try_Type;
   Top             : Natural := 0;
   Iteration_Count : Natural := 0;

   procedure Move_Down is
      Board   : Board_Type         := Stack (Top).Board;
      Row     : constant Row_Type  := Stack (Top).Row;
      Col     : constant Col_Type  := Stack (Top).Col;
      Tile    : constant Tile_Type := Board (Row + 1, Col);
      Penalty : constant Integer   :=
        (if To_Row (Tile) <= Row then 0 else 1);
   begin
      Board (Row,     Col) := Tile;
      Board (Row + 1, Col) := 0;
      Stack (Top + 1) := (Board => Board,
                          Move  => Down,
                          Row   => Row + 1,
                          Col   => Col,
                          Cost  => Stack (Top).Cost + Penalty);
   end Move_Down;

   procedure Move_Up is
      Board   : Board_Type         := Stack (Top).Board;
      Row     : constant Row_Type  := Stack (Top).Row;
      Col     : constant Col_Type  := Stack (Top).Col;
      Tile    : constant Tile_Type := Board (Row - 1, Col);
      Penalty : constant Integer   :=
        (if To_Row (Tile) >= Row then 0 else 1);
   begin
      Board (Row,     Col) := Tile;
      Board (Row - 1, Col) := 0;
      Stack (Top + 1) := (Board => Board,
                          Move  => Up,
                          Row   => Row - 1,
                          Col   => Col,
                          Cost  => Stack (Top).Cost + Penalty);
   end Move_Up;

   procedure Move_Left is
      Board   : Board_Type         := Stack (Top).Board;
      Row     : constant Row_Type  := Stack (Top).Row;
      Col     : constant Col_Type  := Stack (Top).Col;
      Tile    : constant Tile_Type := Board (Row, Col - 1);
      Penalty : constant Integer :=
        (if To_Col (Tile) >= Col then 0 else 1);
   begin
      Board (Row, Col)     := Tile;
      Board (Row, Col - 1) := 0;
      Stack (Top + 1) := (Board => Board,
                          Move  => Left,
                          Row   => Row,
                          Col   => Col - 1,
                          Cost  => Stack (Top).Cost + Penalty);
   end Move_Left;

   procedure Move_Right is
      Board   : Board_Type         := Stack (Top).Board;
      Row     : constant Row_Type  := Stack (Top).Row;
      Col     : constant Col_Type  := Stack (Top).Col;
      Tile    : constant Tile_Type := Board (Row, Col + 1);
      Penalty : constant Integer :=
        (if To_Col (Tile) <= Col then 0 else 1);
   begin
      Board (Row, Col)     := Tile;
      Board (Row, Col + 1) := 0;
      Stack (Top + 1) := (Board => Board,
                          Move  => Right,
                          Row   => Row,
                          Col   => Col + 1,
                          Cost  => Stack (Top).Cost + Penalty);
   end Move_Right;

   function Is_Solution return Boolean;

   function Test_Moves return Boolean is
   begin
      if
        Stack (Top).Move /= Down and then
        Stack (Top).Row  /= Row_Type'First
      then
         Move_Up;
         Top := Top + 1;
         if Is_Solution then return True; end if;
         Top := Top - 1;
      end if;

      if
        Stack (Top).Move /= Up and then
        Stack (Top).Row  /= Row_Type'Last
      then
         Move_Down;
         Top := Top + 1;
         if Is_Solution then return True; end if;
         Top := Top - 1;
      end if;

      if
        Stack (Top).Move /= Right and then
        Stack (Top).Col  /= Col_Type'First
      then
         Move_Left;
         Top := Top + 1;
         if Is_Solution then return True; end if;
         Top := Top - 1;
      end if;

      if
        Stack (Top).Move /= Left and then
        Stack (Top).Col  /= Col_Type'Last
      then
         Move_Right;
         Top := Top + 1;
         if Is_Solution then return True; end if;
         Top := Top - 1;
      end if;

      return False;
   end Test_Moves;

   function Is_Solution return Boolean is
      use Ada.Text_IO;
   begin
      if Stack (Top).Board = Solved_Board then
         Put ("Solved in " & Top'Image & " moves: ");
         for R in 1 .. Top loop
            Put (String'(Stack (R).Move'Image) (1));
         end loop;
         New_Line;
         return True;
      end if;
      if Stack (Top).Cost <= Iteration_Count then
         return Test_Moves;
      end if;
      return False;
   end Is_Solution;

   procedure Solve (Row   : in Row_Type;
                    Col   : in Col_Type;
                    Board : in Board_Type) is
   begin
      pragma Assert (Board (Row, Col) = 0);
      Top := 0;
      Iteration_Count := 0;
      Stack (Top) := (Board => Board,
                      Row   => Row,
                      Col   => Col,
                      Move  => Down,
                      Cost  => 0);
      while not Is_Solution loop
         Iteration_Count := Iteration_Count + 1;
      end loop;
   end Solve;

begin
   Solve (Row   => 2,
          Col   => 0,
          Board => ((15, 14, 1, 6),
                    (9, 11, 4, 12),
                    (0, 10, 7, 3),
                    (13, 8, 5, 2)));
end Puzzle_15;