0

I have a simple class:

public class XYPoint {
    public int x, y;
}

And a 2D array that contains arrays of Point objects:

(-2,  2)(-1,  2)(0,  2)(1,  2)(2,  2)
(-2,  1)(-1,  1)(0,  1)(1,  1)(2,  1)
(-2,  0)(-1,  0)(0,  0)(1,  0)(2,  0)
(-2, -1)(-1, -1)(0, -1)(1, -1)(2, -1)
(-2, -2)(-1, -2)(0, -2)(1, -2)(2, -2)

The correspond ids are:

 0  1  2  3  4 
 5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24

Let's say I want to get the element at id 0, then it will return -2, 2. If I want to get from 6, it will return -1, 1 and so on.

Is there any way I can get an element without looping the entire array?

Johans Bormman
  • 855
  • 2
  • 11
  • 23

1 Answers1

1

you essentially imagine a 1d array, structured in a 2d manner. with that in mind you can map the 1d coordinate (in your case 7 for instance) onto 2d like this:

[1d/width][1d mod width]

1d being your "id" and width being the 2d array length

1d/width results in the corresponding "row" of your id, and 1d mod width in the corresponding "column"

Alan
  • 949
  • 8
  • 26
  • Could you give more information about your edit? I don't see the point of using `Math.floor` here... – Jon Skeet Feb 19 '19 at 09:40
  • @JonSkeet because with id = 14, you would do 14/5 = 2,8. You can see from his post, that 14 belongs into the row at index 2. so you would want to floor the result of the division, to result in your required index. i was not sure wether that happens automatically or not so i added a math.floor "to be on the safe side" – Alan Feb 19 '19 at 09:46
  • 1
    There's no need for that - you're performing integer division, so the result would just be 2. Java's integer division rounds towards zero. https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.17.2 – Jon Skeet Feb 19 '19 at 09:54
  • i thought so. i just wasnt 100% sure if that was really the case – Alan Feb 19 '19 at 09:55