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?

13
  • 6
    Are the IDs always laid out that way? If so, can you just use array[id / 6][id % 6]? Commented Feb 19, 2019 at 9:03
  • your points is a 5x5 matrix while the ids are in 4x6. Can you include the actual 2D array variables in your question? Commented Feb 19, 2019 at 9:03
  • 4
    That's a simple math problem, nothing more. You know the amount of "columns", so you also know when to shift to a new row when the id is larger than that amount. You really haven't come up with a solution? Commented Feb 19, 2019 at 9:04
  • 1
    Related: How to flatten 2D array to 1D array?. Search for more. Commented Feb 19, 2019 at 9:05
  • @JonSkeet Yes, are always laid in that ascending order. I'll try this and give you a feed-back. Thanks! Commented Feb 19, 2019 at 9:12

1 Answer 1

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"

Sign up to request clarification or add additional context in comments.

4 Comments

Could you give more information about your edit? I don't see the point of using Math.floor here...
@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"
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. docs.oracle.com/javase/specs/jls/se8/html/…
i thought so. i just wasnt 100% sure if that was really the case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.