Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 10 months ago

How to search a 2d array of coordinates?

Update:

I have an array in Java. Each entry of array is a pair of numbers (x and y coordinates).

Technically, an example of my array is:

setOfPoints = {(1,2), (3,4), (5,6), (1,9), (7,4)}

How can I search that list and check whether (3,4) is part of that set?

Update 2:

I would also like to calculate the slope for every pair of coordinates in that set. Can someone show me or direct me to a reference that can teach me how to access each x/y point for every pair of coordinates so I can use it to calculate slope?

Update 3:

For an example if I needed to access 3 from the coordinate (3,4) in that array, how would I do that?

Update 4:

I know these are a lot of questions, sorry for the trouble. I'm just new to programming and need a little bit of help.

1 Answer

Relevance
  • 10 months ago
    Best Answer

    One way to represent a point is a two-element array, and one way to represent a set of n points is as an array of n of those two-element arrays.

    int[] point = {3, 4};

    int[][] setOfPoints = {{1, 2}, {3, 4}, {5, 6}, {1, 9}, {7, 4}};

    Now, setOfPoints[k] is point number (k), for k=0-4, and you can compare point for being equal to setOfPoints[k] with:

    if (point[0] == setOfPoints[k][0] && point[1] == setOfPoints[k][1])) { ... }

    That's necessary because Java's == operator only compares values for primitive types like int, char or double. For all object types, == will compare object references, telling you whether two variables refer to the same object or not. An object is supposed to compare values using the .equals() method in its class definition, but not all classes implement .equals. Java arrays are objects, but array types do not implement a meaningful .equals().

    As a sort of remedy, Java provides the Arrays class with many static methods for working with arrays. Using this class (add "import java.util.Arrays;" to the top of your program) then you can compare with:

    if (Arrays.equals(point, setOfPoints[k])) { ... }

    Java has Set types in it's collection class framework, but there's no easy Java syntax for constructing them, and you need to be careful to only put objects whose values don't change into a set.

    PS: Reading again, since you want to compute slopes, you probably want to use double[] instead of int[] for the point type, and double[][] for the set of points.

Still have questions? Get your answers by asking now.