Algorithm to insert words into a 2D Matrix

About
The following algorithm can be used to put some selected words to a matrix without a specific order. Initially the matrix will be empty. Once we put the selected words, we put random alphabets to the empty cells. So by doing this we can hide these words in random position. The same can be used to generate the Find Word puzzles

There are total eight possible directions possible, they are NORTH(0), NORTH-EAST(1), EAST(2), SOUTH-EAST(3), SOUTH(4), SOUTH-WEST(5), WEST(6), NORTH-WEST(7)

The algorithm is given below

global matrix[10, 10]

procedure insert_word_to_matrix(word)
  directions <- [0, 1, 2, 3, 4, 5, 6, 7]
  completed <- NO
  tries <- 5
  while not completed
    if tries reached 0
      exit this while loop
    (x_position, y_position) <- Locate an empty box randomly
    shuffle(directions)
    next_direction <- 0
    while next_direction is less than 8
      (x_increment, y_increment) <- get_direction_increment(directions[next_direction])
      if possible_to_insert((x_position, y_position), (x_increment, y_increment), word)
        do_insert_word((x_position, y_position), (x_increment, y_increment), word)
        completed <- YES
        exit this while loop
      next_direction <- next_direction + 1
    tries <- tries - 1
  if completed
    return YES
  return NO

procedure get_direction_increment(direction)
  if direction = 0 return (-1, 0)  
  else if direction = 1 return (-1, 1)
  else if direction = 2 return (0, 1)
  else if direction = 3 return (1, 1)
  else if direction = 4 return (1, 0)
  else if direction = 5 return (1, -1)
  else if direction = 6 return (0, -1)
  else if direction = 7 return (-1, -1)

procedure possible_to_insert((x_position, y_position), (x_increment, y_increment), word)
  word_length_counter <- 1
  while word_length_counter is less than length(word)
    (next_x_position, next_y_position) <- (x_position + x_increment, y_position + y_increment)
    if (next_x_position, y_position) is outside the matrix
      return NO
    else if matrix[next_x_position, next_y_position] have no value
      word_length_counter <- word_length_counter + 1
      continue while loop
    else if matrix[next_x_position, next_y_position] is not equal to word[word_length_counter]
      return NO
    word_length_counter <- word_length_counter + 1
    continue this while loop
 return YES

procedure do_insert_word((x_position, y_position), (x_increment, y_increment), word)
  word_length_counter <- 1
  matrix[x_position, y_position] <- word[0]
  while word_length_counter is less than length(word)
    (next_x_position, next_y_position) <- (x_position + x_increment, y_position + y_increment)
    matrix[next_x_position, next_y_position] <- word[word_length_counter]
    word_length_counter <- word_length_counter + 1
    continue this while loop

Note: Here we try to fit the word by taking each direction from the list for a selected position. This is some times time consuming. So we can try another method. First find the best fit directions (at least three) for the selected word using the matrix boundary and word length. Check if it is possible to fill in any of the selected direction.So by doing this we can improve the performance

Hope this tutorial was helpful ūüôā

Thanks for Reading

SQLite Programming in Java (Part 1)

Introduction
This tutorial is an introduction to SQLite programming in Java and it explains how we can establish a connection to SQLite database from Java application.

About SQLite
SQLite is a software library which implements SQL database engine, which is self-contained and serverless means no server that needs to be started, stopped or configured and is zero configuration means no setup or installation required.

Using SQLite with Java
The below given program demonstrate the steps required to establish connection to the sqlite database. For the sake of simplicity i have divided the program into different parts.

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

About DriverManager class
It is responsible for managing Java DataBase Connectivity (JDBC) drivers.

About Connection class
To establish connection with the database, java applications which make use of JDBC API has to obtain instance of Connection class first. The DriverManager class provides getConnection(String url) method which will create and return a Connection object. The url provides a way to identify the database using a protocol. The URL format for SQLite is given below.

jdbc:sqlite:dbname

In the above url you can replace string “dbname” with your database¬†name. SQLite database is a file which ends with a “.db” extension and it¬†will be cross platform.

About Statement class
Once you obtain connection to database, your next job is to create an instance of Statement class. Statement objects are used to obtain results by executing static SQL statements and they can be used to execute both Data Definition Language (DDL) commands and Data Manipulation Language (DML) commands. Statement class provides executeQuery(command) method to execute DML commands and executeUpdate(command) method to execute DDL commands.Simply statement object send the commands to the database and get results back.

The below given code block shows, how we can integrate this two together.

Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:test.db");
statement = connection.createStatement();

Why do we use forName(url) method
The forName(url) method is used to load any class whose complete name is specified as the url at run time. Here this will load the JDBC class from org.sqlite package.

What goes wrong and how should we treat them

  • When we call the forName(url) method, if the class is not available at run time it will throw ClassNotFoundException
  • When we call getConnection() method, if the url is null or any access error occur this will throw SQLException
  • When we call createStatement() method, if there are any access error occur or a¬†closed connection this will throw SQLException

So we must write this three statements inside the try-catch-finally block.

How to close the connection and quite the application
Its simple, we close active statement and connection. Both Connection class and Statement class have a method called close() which releases connection or statement object’s JDBC and database resources once called. First you should close the statement by calling¬†close() method of statement object and then close() method of connection object. The reverse order is not recommended.

Please find below the complete sample program

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;

public class SQLiteJavaDemo {
    public static void main(String[] args) {
        try {
            Class.forName("org.sqlite.JDBC");
            Connection con = DriverManager.getConnection("jdbc:sqlite:demo.db");
            Statement st = con.createStatement();
            System.out.println("Connection created.");
            st.close();
            con.close();
            System.out.println("Connection closed.");
        } catch (SQLException | ClassNotFoundException ex) {
            System.err.println(ex);
        }
    }
}

In Part-2 we will see how to use statement object to execute sql commands.