Massimo Ugues
Massimo Ugues

Reputation: 4463

which is the best way to model a matrix in java?

I have to model this table:

--------------------------------------
| range  | X<10  | 10<X<30 | 30<X<50 |
|--------|---------------------------|
|  Y<5   |  HIGH |  MIDDLE | LOW     |
|------------------------------------|   
| 5<Y<10 | MIDDLE|  LOW    | HIGH    |
|____________________________________|

So I have to model it in a method that takes 2 parameters (X and Y) and return the correct value based on this table.

I thought on a map based implementation, but maybe this is not the best way. How would you model it?

Kind regards Massimo

Upvotes: 0

Views: 1138

Answers (2)

aviad
aviad

Reputation: 8278

How about two maps?

Map<Range, Map<Range, String>>()

The Range will hold 2 integers (lower and upper bounds) , you will need to implement equals() and hashcode() in order for the Range to fit the `Map' nature.

So, the first Map will filter by X and the 2nd Map fill get the value (HIGH, LOW, etc)

Upvotes: 1

fangsterr
fangsterr

Reputation: 3820

private int getYIndex(int y) {
    if (y < 5) return 0;
    if (5 < y && y < 10) return 1;
    return -1; // should never reach this case
}

private int getXIndex(int x) {
    if (x < 10) return 0;
    if (10 < x && x < 30) return 1;
    if (30 < x && x < 50) return 2;
    return -1; // should never reach this case
}

So then you could just have a 2D-array of Strings (String[][]), where the indices would be given from the functions above.

Upvotes: 2

Related Questions