/**
 * Class the models a keypad of characters.
 *   @author Dave Reed
 *   @version 9/19/16
 */
public class KeypadB3 {
    private String keys;
    private int numCols;
    
    /**
     * Default constructor for 4x3 keyboard (0-9, *, #)
     */
    public KeypadB3() {
        this("123456789*0#", 3);
    }
    
    /**
     * Constructor for keyboard with specified keys and number of columns.
     *   @param keys a String containing the key characters in row-major order
     *   @param cols the number of columns on the keyboard
     */
    public KeypadB3(String keys, int cols) {
        this.keys = keys;
        this.numCols = cols;        
    }
    
    /**
     * Determines the row # for the specified key (starting at row 0).
     *   @param key the key being searched for
     *   @return the row number for that key
     */
    public int getRow(char key) {
        return this.keys.indexOf(key) / numCols;
    }
 
    /**
     * Determines the column # for the specified key (starting at column 0).
     *   @param key the key being searched for
     *   @return the column number for that key
     */
    public int getCol(char key) {
        return this.keys.indexOf(key) % numCols;        
    }
    
    /**
     * Determines if two keys are adjacent (horizontal or vertical) on the keypad.
     *   @param key1 the first key
     *   @param key2 the second key
     *   @return true if key1 and key2 are adjacent horizontally or vertically
     */
    public boolean areAdjacent(char key1, char key2) {
        int r1 = this.getRow(key1);   int c1 = this.getCol(key1);
        int r2 = this.getRow(key2);   int c2 = this.getCol(key2);               
        return ((r1 == r2 && Math.abs(c1-c2) == 1) ||
                (c1 == c2 && Math.abs(r1-r2) == 1));
    }
}
