Ku Nole - 7 months ago 38

Java Question

I'd would like to implement a check to see if a sudoku is valid in Java, and came across (http://leetcode.tgic.me/valid-sudoku/index.html).

I understand how it is validating rows and columns, but for the 3x3 grids validator:

`34 for(x = 0; x < mx; x += 3){`

35 for(y = 0; y < my; y += 3){

36

37 HashSet<Character> block = new HashSet<Character>();

38

39 for(int offset = 0; offset < 9; offset++){

40 int ox = offset % 3;

41 int oy = offset / 3;

42

43 char c = board[x + ox][y + oy];

44 if(c != '.'){

45 if(block.contains(c)) return false;

46

47 block.add(c);

48 }

49 }

50 }

51 }

What is

`offset`

`x=0, y=0`

`offset=0`

`offset=1`

`offset=1`

`int ox = 1%3 = 1;`

`int oy = 1/3`

`board[0 + 1][0+(1/3)] = board[1][1/3]`

`[1/3]`

Answer

when you divide n by m, both are int's (either literals or variables) the result is also an int, so 1/3 -> 0 Hence when offset == 0 => ox=0, oy=0 offset == 1 => ox=1, oy=0 offset == 2 => ox=2, oy=0 offset == 3 -> ox=0, oy=1 ... hence you will loop nicely of the 3 rows and 3 columns

Source (Stackoverflow)