If you have a rectangular 2d array of known dimensions m×n
, then you can supplement it with the getValue
and setValue
methods and access its elements using one variable position
in the range from 1
to m×n
.
Assignment, Arithmetic, and Unary Operators
/
- Division operator
%
- Remainder operator
public class Test {
static int m = 3, n = 4;
static int[][] array = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};
public static void main(String[] args) {
System.out.println(getValue(5)); // 5
System.out.println(setValue(5, 90)); // true
System.out.println(getValue(5)); // 90
System.out.println(Arrays.deepToString(array));
// [[1, 2, 3, 4], [90, 6, 7, 8], [9, 10, 11, 12]]
}
public static int getValue(int pos) {
if (pos >= 1 && pos <= m * n) {
int i = (pos - 1) / m; // row
int j = (pos - 1) % n; // column
return array[i][j];
} else {
return 0;
}
}
public static boolean setValue(int pos, int value) {
if (pos >= 1 && pos <= m * n) {
int i = (pos - 1) / m; // row
int j = (pos - 1) % n; // column
array[i][j] = value;
return true;
} else {
return false;
}
}
}
See also: Easier way to represent indicies in a 2D array