java - Check for adjacent cells in a 5x6 matrix -


i have 5x6 matrix have created using individual buttons in java swing.

i have named them similar chess board, a1 f5 top left bottom right.

now, want allow user click given number of adjacent buttons, either horizontally or vertically.

say, value 4. so, user must able select 4 buttons anywhere in matrix next each other vertically or horizontally.

for eg. d2, c2, b2, a2 if chosen vertically. or, maybe d1, d2, d3, d4 if chosen horizontally.

what algorithmic way of achieving functionality set of buttons in matrix?

here's code, added comments make more clear.

please note array in code should sorted

logic

horizontal

a1 => 01 a2 => 02 a3 => 03 a4 => 04  a2 - a1 = 1 

vertical

a1 => 01 b1 => 11 c1 => 21 d1 => 31  b1 - a1 = 10 

code:

    public static void main(string[] args) {         string[] spots0 = { "a1", "b1", "c1", "d1" };         string[] spots1 = { "a1", "a2", "a3", "a4" };         string[] spots2 = { "a1", "b1", "b2", "b3" };          system.out.println(iscorrect(spots0) ? "correct" : "incorrect");         system.out.println(iscorrect(spots1) ? "correct" : "incorrect");         system.out.println(iscorrect(spots2) ? "correct" : "incorrect");     }      public static boolean iscorrect(string[] spots) {         int none = -1;         int horizontal = 1;         int vertical = 2;          int pattern = none; //by default none          (int = 0; < spots.length - 1; i++) {              //difference between 2 consecutive element in spots[]. if a2 - a1 = 1, , b1 - a1 = 10             int diff = tonum(spots[i + 1]) - tonum(spots[i]);              if (diff == 1) { // if horizontal                 if (pattern == none) // if first time                     pattern = horizontal; // set pattern vertical, used later check if illigal change happen                 else if (pattern == vertical) { //if vertical , changed, error                     return false;                 }             } else if (diff == 10) { // if vertical                 if (pattern == none) // if first time                     pattern = vertical; // set pattern horizontal, used later check if illigal change happen                 else if (pattern == horizontal) { //if horizontal , changed, error                     return false;                 }              } else {                 return false;             }         }         return true;     }      public static int tonum(string s) {         // a1 => 01 , b1 => 11, c2 => 22         return integer.parseint("" + ((int)s.charat(0) - 'a') + s.charat(1));     } 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -