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

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)

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

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));
            }
        }
    }
}

PIH ex.7.9

January 14th, 2008

import EX_7_8 hiding (channel, transmit)

channel :: [Bit] -> [Bit]
channel = tail

-- need to redefine transmit to force it use this new verion of channel
transmit :: String -> String
transmit = decode . channel . encode

main = do 
       putStrLn $ transmit "Haskell is fun!"

{-
$> ghci
GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
Loading package base ... linking ... done.
Prelude> :l ex.7.9  ex.7.8
[1 of 2] Compiling EX_7_8           ( ex.7.8.hs, interpreted )
[2 of 2] Compiling Main             ( ex.7.9.hs, interpreted )
Ok, modules loaded: EX_7_8, Main.
*Main> main
*** Exception: Parity checking fail.
*Main>
-}

PIH ex.7.8

January 14th, 2008

module EX_7_8 where

import Data.Char

type Bit = Int

bin2int :: [Bit] -> Int
bin2int = foldr (\x y -> x + 2 * y) 0

int2bin :: Int -> [Bit]
int2bin 0 = []
int2bin n = n `mod` 2 : int2bin (n `div` 2)

make8 :: [Bit] -> [Bit]
make8 bits = take 8 (bits ++ repeat 0)

addParityBit :: [Bit] -> [Bit]
addParityBit bits = bits ++ [parity]
                    where parity = length (filter (==1) bits) `mod` 2

checkParityBit :: [Bit] -> [Bit]
checkParityBit bits =
  if last bits == length (filter (==1) (init bits)) `mod` 2
  then init bits
  else error "Parity checking fail."

encode :: String -> [Bit]
encode = concat . map (addParityBit . make8 . int2bin . ord)

chop :: Int -> [Bit] -> [[Bit]]
chop _ []   = []
chop n bits = take n bits : chop n (drop n bits)

decode :: [Bit] -> String
decode = map (chr . bin2int . checkParityBit) . (chop 9)

transmit :: String -> String
transmit = decode . channel . encode

channel :: [Bit] -> [Bit]
channel = id

PIH ex.7.7

January 14th, 2008

import Prelude hiding(map, iterate)

unfold :: (t -> Bool) -> (t -> a) -> (t -> t) -> t -> [a]
unfold p h t x | p x        = []
               | otherwise  = h x : unfold p h t (t x)


--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- chop8 :: [a] -> [[a]]
-- chop8 [] = []
-- chop8 xs = take 8 xs : chop8 (drop 8 xs)

chop8 = unfold null (take 8) (drop 8)

--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- map :: (a -> b) -> ([a] -> [b])
-- map f xs = [ f x1, f x2, ... f xn ]

map f = unfold null (f.head) tail

--~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- iterate :: (a -> a) -> a -> [a]
-- iterate f x = [ x, f x, f (fx), ... ]

iterate f = unfold (\-> False) id f

PIH ex.7.6

January 14th, 2008

import Prelude hiding (curry, uncurry)

curry ::  ((a,b) -> c) -> (a -> b -> c)
curry f = \x y -> f (x, y)

uncurry ::  (a -> b -> c) -> ((a, b) -> c)
uncurry f = \(x,y) -> f x y


{-
 -
Prelude definition:

curry f x y = f (x,y)
-- uncurry f (x, y) = f x y
uncurry f p = f (fst p) (snd p)


Like PIH page#68 f.= \-> f (g x)  instead of (f.g) x = f (g x)
I prefer use lambd expression to define curry/uncurry.

-}

PIH ex.7.5

January 14th, 2008

sumsqreven = compose [ sum, map (^2), filter even ]
is invalid because:
all elements on the list must have the same type.
( For example: [a] is type of list, where all element are the type a ).

map (^2) :: (Num a) => [a] -> [a]
filter even :: (Integral a) => [a] -> [a]
sum :: (Num a) => [a] -> a

So, (map (^2)) and (filter even) are type like [a] -> [a];
the result is type list, but the result of sum is not type list.

PIH ex.7.4

January 14th, 2008

dec2int :: Num a => [a] -> a
-- dec2int xs = foldl (\x y -> x * 10 + y) 0 xs
dec2int = foldl ((+).(*10)) 0

PIH ex.7.3

January 11th, 2008

map f xs = f x1 : f x2 : ... : f xn : []
         = ( x1 # ( x2 # ... (xn # []) ... ))
           where (#) x xs = f x : xs

==> map f xs = foldr (x xs -> f x : xs) [] xs
==> map f = foldr (x xs -> f x : xs) []
==> map f = foldr (x -> (:) (f x)) []
==> map f = foldr ((:).f) []

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

filter p xs = filter p (x1 : x2 ... : xn : [])
  = (x1 # ( x2 # ... (xn # []) ... ))
  = ( (if p x1 then [x1] else []) ++ ... ((if p xn then [xn] else []) ++ []) ... )

==> (#) x xs = (if p x then [x] else []) ++ xs
==> filter p = foldr (x -> (++) (if p x then [x] else [])) []

or  (#) x xs = if p x then (x:xs) else xs
==> filter p = foldr (x xs -> if p x then (x:xs) else xs) []