8 puzzle solver using A* algorithm

 8-puzzle is a very interesting and a well known problem in the field of Artificial Intelligence. It always has been an important subject in articles, books and become a part of course material in many universities. The 8-puzzle is also known as the sliding-block puzzle or tile-puzzle and is meant for a single user. 8-puzzle consists of 8 square tiles numbered 1 through 8 and one blank space on a 3  by 3 board. Moves of the puzzle are made by sliding an adjacent tile into the position occupied by the blank space, which has the effect of exchanging the positions of the tile and blank space. Only tiles that are horizontally or vertically adjacent (not diagonally adjacent) may be moved into the blank space. The objective of the game is to start from an  initial configuration and end up in a configuration which the tiles are placed in ascending number order as shown in: figure 1 below.



                                                        Figure 1   Goal state of the 8-puzzle

HOW TO PLAY

The game can be played using the arrow keys. Up arrow slides a tile up into the empty space, left arrow slides a tile left into the empty space and so on. You can choose to solve it automatically by program. It will display the animation sliding the tiles and solve the 8 puzzle in least possible moves using AI.

METHODOLOGY

According to the authors  Russel  and  Norvig  in their book titled  Artificial Intelligence: A Modern Approach, the average solution for a randomly generated 8-puzzle instance is about 22 steps. This figure  is obtained by estimating the branching factor which is about 3 (when the empty tile is in the middle, there are four possible moves; when it is in a corner there are two; and when it is along an edge there are three). This means that an exhaustive search to depth 22 would look at about 322 ~ 3.1 x 1010 states. By keeping track of repeated states, it is possible to cut this down by a factor of about 170,000, because there are only 9!/2 = 181,440 distinct states that are reachable.


ALGORITHM

After a preliminary investigation of the heuristic search strategies we were able to figure out that A* algorithm is the best for the 8-puzzle problem. A* is the most widely used form of best first search algorithm which is an instance of Tree-Search or Graph-Search where a best node is expanded on the basis of an evaluation function f(n). Here, the evaluation function of each node is calculated as a sum of two functions g(n) and h(n) where, g(n) refers to the cost to reach the node n while h(n) is the cost to get from node n to the goal. A* algorithm is both optimal and complete. It is optimal in that sense h(n) is admissible and is never overestimated
to reach the goal and it is complete in that sense it guarantees to reach a solution whenever there is one.

The following pseudo code describes the A* algorithm:


function A*(start,goal)
     closedset := the empty set                 // The set of nodes already  evaluated.     
     openset := set containing the initial node // The set of tentative nodes to be evaluated.
     g_score[start] := 0                        // Distance from start along optimal path.
     h_score[start] := heuristic_estimate_of_distance(start, goal)
     f_score[start] := h_score[start]           // Estimated total distance from start to goal through y.

while openset is not empty
         x := the node in openset having the lowest f_score[] value
         if x = goal
             return reconstruct_path(came_from[goal])
         remove x from openset
         add x to closedset
         foreach y in neighbor_nodes(x)
             if y in closedset
                 continue


 tentative_g_score := g_score[x] + dist_between(x,y)
 
             if y not in openset
                 add y to openset
                 tentative_is_better := true
             elseif tentative_g_score < g_score[y]
                 tentative_is_better := true
             else
                 tentative_is_better := false
             if tentative_is_better = true
                 came_from[y] := x
                 g_score[y] := tentative_g_score
                 h_score[y] := heuristic_estimate_of_distance(y, goal)
                 f_score[y] := g_score[y] + h_score[y]
     return failure
 
 function reconstruct_path(current_node)
     if came_from[current_node] is set
         p = reconstruct_path(came_from[current_node])
         return (p + current_node)
     else
         return current_node


REFERENCE

1.  Rich and Knight, Artificial Intelligence.
2.  Russell and Norvig, Artificial Intelligence: A Modern approach,
3.  A* search algorithm - Wikipedia, the free encyclopedia
4.  Description and a solution strategy for the 8-puzzle from http://www.8puzzle.com/
5.  G. Novak, CS 381K: Heuristic Search: 8 Puzzle, 26 Sep 07
6.  An appealing Java applet from www.permadi.com/java/puzzle8/

JSP basics - Java Server Pages

 The JSP - Java Server Pages

  • JSP extension of the servlet technology which offers both scripting ( as in HTML) as well as programming (as in Servlets) 
  • When a JSP page is requested, the JSP container ( also called page compiler) compiles the jsp page into a servlet class. 
  • The JSP API that handles all the JSP technology has been bundled under the following two packages: 
    • javax.servlet.jsp 
    • javax.servlet.jsp.tagext 

JSP Syntax

A JSP page is all about JSP tags and some template data ( such as HTML tags). That's pretty much of it. It always feels good learning about JSP as we get to see the very well-know HTML tags (I presumed that you already know HTML at this point).

JSP consists of three types of elements.
  • Directive elements 
  • Scripting elements 
  • Action elements 

DIRECTIVES

<%@ directiveName (attributeName="atrributeValue") %>

These are the messages/information to the JSP container on how it should translate the JSP page into the corresponding servlet.

Again, there are three types of directives:

  • Page directives
  • Include directives
  • Tag library directives 

1. Page Directive
<%@ page (attributeName="atrributeValue") %>

You might have encountered some "import" statements at the beginning of some JSP pages. Those import statements falls under this category. E.g.

<%@ page import="java.util.Date, java.util.Enumeration" language="java" %>
where,
          page => represents directiveName
          import/language => represents attributeName
          and the values enclosed by quotes represents atrributeValue

The following is the list of available Page directive attributes:
Attribute
Value Type
Default Value
language
Scripting language name
"java"
info
String
Depends on the JSP container
contentType
MIME type, character set
"text/html;charset=ISO-8859-1"
extends
Class name
None
import
Fully qualified class name or package name
None
buffer
Buffer size or false
8Kb
autoFlush
Boolean
"true"
session
Boolean
"true"
isThreadSafe
Boolean
"true"
errorPage
URL
None
isErrorPage
Boolean
"false"

NOTE:
  • Except for the import attribute, JSP does not allow to repeat the same attribute within a page directive or in multiple directives on the same page. 

Page Attributes a little in-depth:
  • language 
    • <%@ page language="java" %>
    • The only supported language by Tomcat JSP Container
    • Other JSP containers might accept different languages
  • info 
    • <%@ page info="any string here" %>
    • Can be retrieved by calling the method getServletInfo() from anywhere withing the page
  • contentType 
    • <%@ page contentType="application/json; charset=UTF-8" %> 
    • Defines MIME type of the HTTP response sent to the client 
  • extends 
    • <%@ page extends="yourClass" %>
    • Defines the parent class that will be inherited by the generated servlet of the current page
    • This attribute is less common
  • import 
    • <%@ page import="java.io.*" %>
    • One of the most common attributes used
    • Same as we do in java classes/interfaces
    • By default, tomcat imports the following packages:
      • javax.servlet.* 
      • javax.servlet.http.* 
      • javax.servlet.jsp.* 
      • javax.servlet.jsp.tagext.*
      • org.apache.jasper.runtime.*
  • buffer 
    • <%@ page buffer="none" %>
    • <%@ page buffer="20kb" %>
    • <%@ page buffer="20" %>
    • buffer="20" is the same as "20kb"
    • But it's up to the JSP container to use its discretion to increase the buffer in order for the improved performance
  • autoFlush 
    • <%@ page autoFlush="false" %>
    • If true, the JSP container automatically flushes the buffer when it's full.
    • If false, the buffer can be flushed manually by the following statement: 
      • out.flush()
  • session 
    • <%@ page session="true" %>
    • By default, the session is set "true", meaning the JSP page takes part in session management
    • It is wise and strongly advised not to set it true unless you specifically require it because this consumes resources.
  • isThreadSafe 
    • <%@ page isThreadSafe="true" %>
    • True indicates that the simultaneous access to this page is safe
    • False indicates that the simultaneous access to this page is not safe. In that case, the JSP container puts multiple requests in a queue and serves them only one at a time.
  • errorPage 
    • <%@ page errorPage="MyErrorPage.jsp" %>
    • Indicates the error page which is displayed if an uncaught exception occurs in the current page
    • The error page must have the page attribute isErrorPage="true"
  • isErrorPage 
    • <%@ page isErrorPage="true" %>
    • If true, then only be set as an error page in other JSP pages
    • If true, this page has an access to the exception implicit object

2. Include directives
<%@ include file="includes/Footer.html" %>
  • As the name suggest, Include Directive enables us to include the contents of other files in the current JSP page.
  • The included page can be static HTML page as well as dynamic JSP page.
  • Very commonly used to include Header page, Footer page or a page containing import statements and so on.

2. Taglib directives
  • The taglib, or tag library, directive can be used to extend JSP functionality. It's a broad topic so it's not covered here at this moment. It will be covered under it's own topic later soon.

SCRIPTING ELEMENTS

Scripting elements allow you to insert Java code in your JSP pages. There are three types of scripting elements:
  • Scriptlets
  • Declarations
  • Expressions 

1. Scriptlets
<% ... %>
  • Syntax looks similar to Directives. But don't get confused, Directives starts with <%@ i.e. <%@ ... %>

<%
  try {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("JDBC driver loaded");
  }
  catch (ClassNotFoundException e) {
    System.out.println(e.toString());
  }
%>

...
...

<%
out.println("You can do anything here");

String str = "some string";
str = str + " string concatenation";
out.println( str );

%>


2. Declarations
<%! ... %>
  • Used to declare methods and variables that can be used from any point in the JSP page.
  • Can appear anywhere throughout the page. For instance, a method declaration can appear above a page directive that imports a class, even though the class is used in the method.
<%!
  String getSystemTime() {
    return Calendar.getInstance().getTime().toString();
  }
%>

<%@ page import="java.util.Calendar" %>

<%
  out.println("Current Time: " + getSystemTime());
%>

3. Expressions 
<%= ... %>
  • Expressions get evaluated when the JSP page is requested and their results are converted into a String and fed to the print method of the out implicit object. 
  • If the result cannot be converted into a String, an error will be raised at translation time. If this is not detected at translation time, at request-processing time, a ClassCastException will be raised.
  • Don't need to add a semicolon at the end of an expression

Below is the two equivalent statements:


<!-- Expression -->

<%= java.util.Calendar.getInstance().getTime() %>

<!-- Equivalent Scriptlet -->

<% out.print(java.util.Calendar.getInstance().getTime()); %>