Archive for March, 2008

Quiz: Count the ways to find a word by walking on a grid (3)

Monday, March 31st, 2008


/*
 * Author : David Tran
 * Date   : 2008-03-31
 * Quiz   : see  http://davidtran.doublegifts.com/blog/?p=140
 * Note   : Revise previous version, improve it to use less memory and much faster.
 *          Instead of caching neighbors, this time it caches the solutions number. 
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Quiz2 {
    
    public static void main(String[] args) {
        new Quiz2().solve();
    }

    public void solve() {
        loadProblem();
        int solutions = 0;
        for (int index : starts) {
            solutions += findSolution(index / cols, index % cols, 0);
        }
        System.out.println("Total Solution = " + solutions);
    }
    
    private int rows;
    private int cols;
    private int lastNumber;
    private List<Integer> starts;
    private Map<Integer, Integer>[][] grid;  // key=position in goal;value=number solutions
    
    @SuppressWarnings("unchecked")
    private void loadProblem() {
        // to simplify, we hard-coded the problem data for now.
        // and skip all preconditions checking:
        // *   0 < rows, cols, goal’s length, cell’s length <= 50
        // *   all cell have the exact cellLength length
        // *   goal’s length modulo cell’s length == 0
        
        rows = 3;
        cols = 3;
        int cellLength = 2;
        String[][] gridData = {
            {"AA", "BB", "CZ"},
            {"FF", "EE", "DD"},
            {"GX", "AA", "IY"},
        };
        String goal = "AAEEAA";

        // split goal string to build up dictionary
        Map<String, List<Integer>> dictionary = new HashMap<String, List<Integer>>();
        for (int nb = 0, position = 0, length = goal.length(); position < length; nb++, position += cellLength) {
            String substring = goal.substring(position, position + cellLength);
            if (dictionary.containsKey(substring)) {
                dictionary.get(substring).add(nb);
            } else {
                List<Integer> values = new ArrayList<Integer>();
                values.add(nb);
                dictionary.put(substring, values);
            }
        }
        if (dictionary.size() <= 0) {
            throw new IllegalArgumentException("No input data ?!");
        }
        
        lastNumber = (goal.length() / cellLength) - 1;
        starts = new ArrayList<Integer>();
        grid = (Map<Integer, Integer> [][]) new Map[rows][cols];
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                String key = gridData[i][j];
                if (dictionary.containsKey(key)) {
                    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
                    for (int nb : dictionary.get(key)) {
                        map.put(nb, null);
                        if (nb == 0) {
                            starts.add(i * cols + j);
                        }
                    }
                    grid[i][j] = map;
                }
            }
        }
    }
    
    private int findSolution(int i, int j, int nb) {
        int solutions = 0;
        if (nb == lastNumber) {
            solutions = 1;
        } else {
            if (grid[i][j].get(nb) != null) {
                solutions = grid[i][j].get(nb);
            } else {
                for (int index : findNeighbors(i, j, nb)) {
                    solutions += findSolution(index / cols, index % cols, nb + 1);
                }
                grid[i][j].put(nb, solutions);
            }
        }
        return solutions;
    }
    
    private List<Integer> findNeighbors(int i, int j, int nb) {
        int nextNb = nb + 1;
        List<Integer> neighbors = new ArrayList<Integer>();
        addNeighbor(i - 1, j - 1, nextNb, neighbors);
        addNeighbor(i - 1, j    , nextNb, neighbors);
        addNeighbor(i - 1, j + 1, nextNb, neighbors);
        addNeighbor(i    , j - 1, nextNb, neighbors);
        addNeighbor(i    , j + 1, nextNb, neighbors);
        addNeighbor(i + 1, j - 1, nextNb, neighbors);
        addNeighbor(i + 1, j    , nextNb, neighbors);
        addNeighbor(i + 1, j + 1, nextNb, neighbors);
        return neighbors;
    }
    
    private void addNeighbor(int i, int j, int nb, List<Integer> list) {
        if (i >= 0 && i < rows && j >= 0 && j < cols && 
                grid[i][j] != null && grid[i][j].containsKey(nb)) {
            list.add(i * cols + j);
        }
    }
}

Quiz: Count the ways to find a word by walking on a grid (2)

Saturday, March 29th, 2008


/*
 * Author : David Tran
 * Date   : 2008-03-29
 * Quiz   : see  http://davidtran.doublegifts.com/blog/?p=139
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

public class Quiz {
    
    public static void main(String[] args) {
        new Quiz().solve();
    }

    public void solve() {
        loadProblem();
        for (int index : starts) {
            findSolution(index / cols, index % cols, 0);
        }
        System.out.println("Total Solution = " + solutions);
    }
    
    private int rows;
    private int cols;
    private int lastNumber;
    private int solutions;
    private List<Integer> starts;
    private Map<Integer, List<Integer>>[][] grid;
    
    @SuppressWarnings("unchecked")
    private void loadProblem() {
        // to simplify, we hard-coded the problem data for now.
        // and skip all preconditions checking:
        // *   0 < rows, cols, goal’s length, cell’s length <= 50
        // *   all cell have the exact cellLength length
        // *   goal’s length modulo cell’s length == 0
        
        rows = 3;
        cols = 3;
        int cellLength = 2;
        String[][] gridData = {
            {"AA", "BB", "CZ"},
            {"FF", "EE", "DD"},
            {"GX", "AA", "IY"},
        };
        String goal = "AAEEAA";

        /* - - - - - - - - - - - - 
        int cellLength = 1;
        String[][] gridData = {
            {"A", "B", "C"},
            {"D", "E", "F"},
            {"G", "A", "I"},
        };
        String goal = "AEA";
         - - - - - - - - - - - - */
        
        // split goal string to build up dictionary
        Map<String, List<Integer>> dictionary = new HashMap<String, List<Integer>>();
        for (int nb = 0, position = 0, length = goal.length(); position < length; nb++, position += cellLength) {
            String substring = goal.substring(position, position + cellLength);
            if (dictionary.containsKey(substring)) {
                dictionary.get(substring).add(nb);
            } else {
                List<Integer> values = new ArrayList<Integer>();
                values.add(nb);
                dictionary.put(substring, values);
            }
        }
        if (dictionary.size() <= 0) {
            throw new IllegalArgumentException("No input data ?!");
        }
        
        lastNumber = (goal.length() / cellLength) - 1;
        starts = new ArrayList<Integer>();
        grid = (Map<Integer, List<Integer>> [][]) new Map[rows][cols];
        
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                String key = gridData[i][j];
                if (dictionary.containsKey(key)) {
                    Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
                    for (int nb : dictionary.get(key)) {
                        map.put(nb, null);
                        if (nb == 0) {
                            starts.add(i * cols + j);
                        }
                    }
                    grid[i][j] = map;
                }
            }
        }
    }
   
    private Stack<String> stack = new Stack<String>();
    private void findSolution(int i, int j, int nb) {
        stack.push("(" + i + "," + j + ") ");
        if (nb == lastNumber) {
            solutions++;
            System.out.println(stack);
        } else {
            if (grid[i][j].get(nb) == null) {
                findNeighbors(i, j, nb);
            }
            for (int index : grid[i][j].get(nb)) {
                findSolution(index / cols, index % cols, nb + 1);
            }
        }
        stack.pop();
    }
    
    private void findNeighbors(int i, int j, int nb) {
        int nextNb = nb + 1;
        List<Integer> neighbors = new ArrayList<Integer>();
        addNeighbor(i - 1, j - 1, nextNb, neighbors);
        addNeighbor(i - 1, j    , nextNb, neighbors);
        addNeighbor(i - 1, j + 1, nextNb, neighbors);
        addNeighbor(i    , j - 1, nextNb, neighbors);
        addNeighbor(i    , j + 1, nextNb, neighbors);
        addNeighbor(i + 1, j - 1, nextNb, neighbors);
        addNeighbor(i + 1, j    , nextNb, neighbors);
        addNeighbor(i + 1, j + 1, nextNb, neighbors);
        grid[i][j].put(nb, neighbors);
    }
    
    private void addNeighbor(int i, int j, int nb, List<Integer> list) {
        if (i >= 0 && i < rows && j >= 0 && j < cols && 
                grid[i][j] != null && grid[i][j].containsKey(nb)) {
            list.add(i * cols + j);
        }
    }
}

Quiz: Count the ways to find a word by walking on a grid

Friday, March 28th, 2008


/* ============================================================================
 
The problem: count the ways to find a word by walking on a grid

You are given a rectangular grid of letters and a word to find. 
You must compute the number of ways to find the word within the grid using the following rules:

* start at any cell within the grid
* from there, move to any of the cell’s eight neighboring cells
* continue moving from that neighbor to its neighbors, and so on, until you have spelled out the word
* you may visit cells more than once, but you cannot visit the same cell twice in a row (i.e., you must move for each turn)

Constraints:
* grid will contain between 1 and 50 elements, inclusive.
* Each element of grid will contain between 1 and 50 uppercase (’A’-’Z’) letters, inclusive.
* Each element of grid will contain the same number of characters.
* find will contain between 1 and 50 uppercase (’A’-’Z’) letters, inclusive.  
 
 
For instance, consider the following grid, taken from the examples in the problem statement:

ABC
FED
GAI

If you were asked to find the word “AEA” on this grid, you could do it in four ways:

1:
*BC ABC *BC
FED F*D FED
GAI GAI GAI

2:
*BC ABC ABC
FED F*D FED
GAI GAI G*I

3:
ABC ABC *BC
FED F*D FED
G*I GAI GAI

4:
ABC ABC ABC
FED F*D FED
G*I GAI G*I

If you were asked to find “ABCD”, you could do it in only one way:

1:
*BC A*C AB* ABC
FED FED FED FE*
GAI GAI GAI GAI

If you were asked to find “AAB”, you could not: 
there are no “A” cells on the grid that have other “A” cells as neighbors. 
  
============================================================================ */

/*
 *  Author :  David Tran
 *  Date   :  2008-03-28
 */
using System;
using System.Collections.Generic;
using System.Text;

namespace Quiz
{
    class Quiz
    {
        static void Main(string[] args)
        {
            new Quiz().Solve();
        }

        public void Solve()
        {
            LoadProblem();
            foreach (Index index in starts)
            {
                FindSolution(index.i, index.j, 0);
            }
            Console.WriteLine("Total Solution = {0}", solutions);
        }

        struct Index
        {
            public readonly int i;
            public readonly int j;
            public Index(int i, int j)
            {
                this.i = i;
                this.j = j;
            }
        }

        int rows;
        int cols;
        Dictionary<int, List<Index>>[,] grid;
        int lastNumber;
        List<Index> starts;
        int solutions = 0;

        private void LoadProblem()
        {
            // to simplify, we hard-coded the problem data for now.
            rows = 3;
            cols = 3;
            int cellLength = 2;
            string[,] gridData = {
                {"AA", "BB", "CZ"},
                {"FF", "EE", "DD"},
                {"GX", "AA", "IY"},
            };
            string goal = "AAEEAA";

            // split goal string to build up dictionary
            IDictionary<string, List<int>> dictionary = new Dictionary<string, List<int>>();
            for (int nb = 0, position = 0; position < goal.Length; nb++, position += cellLength)
            {
                string substring = goal.Substring(position, cellLength);
                if (!dictionary.ContainsKey(substring))
                {
                    dictionary[substring] = new List<int>();
                }
                dictionary[substring].Add(nb);
            }

            if (dictionary.Count <= 0)
            {
                throw new Exception("No input data ?!");
            }

            lastNumber = (goal.Length / cellLength) - 1;
            starts = new List<Index>();
            grid = new Dictionary<int, List<Index>>[rows, cols];

            // build up grid and starts
            for (int i = 0; i < rows; i++)
            {
                for (int j = 0; j < cols; j++)
                {
                    string key = gridData[i, j];
                    if (dictionary.ContainsKey(key))
                    {
                        grid[i, j] = new Dictionary<int, List<Index>>();
                        foreach (int nb in dictionary[key])
                        {
                            grid[i, j].Add(nb, null);
                            if (nb == 0)
                            {
                                starts.Add(new Index(i, j));
                            }
                        }
                    }
                }
            }
        }

        private void FindSolution(int i, int j, int nb)
        {
            if (nb == lastNumber)
            {
                solutions++;
            }
            else
            {
                // build neighbors when needed, and memorize after builded.
                if (grid[i, j][nb] == null)
                {
                    FindNeighbors(i, j, nb);
                }

                foreach (Index index in grid[i, j][nb])
                {
                    FindSolution(index.i, index.j, nb + 1);
                }
            }
        }

        private void FindNeighbors(int i, int j, int nb)
        {
            int nextNb = nb + 1;
            List<Index> neighbors = new List<Index>();
            AddNeighbor(i - 1, j - 1, nextNb, neighbors);
            AddNeighbor(i - 1, j    , nextNb, neighbors);
            AddNeighbor(i - 1, j + 1, nextNb, neighbors);
            AddNeighbor(i    , j - 1, nextNb, neighbors);
            AddNeighbor(i    , j + 1, nextNb, neighbors);
            AddNeighbor(i + 1, j - 1, nextNb, neighbors);
            AddNeighbor(i + 1, j    , nextNb, neighbors);
            AddNeighbor(i + 1, j + 1, nextNb, neighbors);
            grid[i, j][nb] = neighbors;
        }

        private void AddNeighbor(int i, int j, int nb, List<Index> list)
        {
            if (i >= 0 && i < rows &&
                j >= 0 && j < cols &&
                grid[i, j] != null &&
                grid[i, j].ContainsKey(nb))
            {
                list.Add(new Index(i, j));
            }
        }
    }
}