Hi
I have written this code that with output you can get that .remove() method doesn't work. a, b, c, and d are some Points Objects that have x and y members.
Here are a and b and c and d values, which in the if statement must be deleted for upper but it doesn't.
X :59 Y: 143
X :165 Y: 140
X :59 Y: 143
X :165 Y: 140
System.out.println(upper.toString());
for(int i =0;i<upper.size();i++)
if(upper.get(i)==a||upper.get(i)==b||upper.get(i)==c||upper.get(i)==d){
upper.remove(i);
}
for(int i =0;i<lower.size();i++)
if(lower.get(i)==a||lower.get(i)==b||lower.get(i)==c||lower.get(i)==d){
upper.remove(i);
}
System.out.println(upper.toString());
System.out.println(lower.toString());
first println : [X :108 Y: 89, X :165 Y: 140]
second println: [X :108 Y: 89, X :165 Y: 140]
third println : [X :105 Y: 191]
If I'm reading your question right, you're assuming that == will compare the properties of two objects. It doesn't, that's what equals does. == tells you whether two references are to the same object instance, not to equivalent ones.
So for example:
public class Foo {
public Foo(int x, int y) {
this.x = x;
this.y = y;
}
#override
public boolean equals(Object other) {
Foo otherFoo;
if (other == null || !(other instanceof Foo)) { // or you might be more restrictive
return false;
}
otherFoo = (Foo)other);
return otherFoo.x == this.x && otherFoo.y == this.y;
}
#override
public int hashCode() {
// ...appropriate implementation of hashCode...
}
}
Foo a = new Foo(0, 0);
Foo b = new Foo(0, 0);
System.out.println(a == b); // "false"
System.out.println(a.equals(b)); // "true"
Separately: Consider what happens when you have two consequtive matching objects in the ArrayList that you have to remove. Say they're at indexes 8 and 9 in the list. So when i == 8, you remove the item at index 8, and the one that used to be at 9 is now at 8. But then you increment i in the for loop and continue with the new item at index 9, leaving the second one untouched. If you want to modify the list while you're looping through it, consider looping backward to avoid that, or using an Iterator.
Two problems here. Firstly, you're removing objects from a list while you iterate it. That's not a good idea.
Secondly, I think you're misunderstanding the == operator in Java, as mentioned by #T.J. Crowder.
This is a better way of doing what you're trying to do (after you've fixed the equals issue):
List<Point> mypoints = new ArrayList();
mypoints.add(a);
mypoints.add(b);
mypoints.add(c);
mypoints.add(d);
List<Point> otherPoints = new ArrayList();
for(Point p: upper)
for(Point myPoint: mypoints)
{
if(p.equals(myPoint))
break;
otherPoints.add(p);
}
upper = otherPoints;
Another implementation (which only works if upper is a Set, as it will not catch duplicates):
List<Point> mypoints = new ArrayList();
mypoints.add(a);
mypoints.add(b);
mypoints.add(c);
mypoints.add(d);
for(Point myPoint: mypoints)
{
upper.remove(myPoint);
}
As Eric implies, the length of the list changes as items are removed from it, and so do the indices of all of the values after the element that has just been removed.
I'm not sure what the significance of "lower" is. I did notice that the loop that iterates through "lower" attempts to remove elements from "upper". Is this intentional?
This is my solution based on a "remove" list of points that should be removed from "upper". It is also possible to use the style of your original test except that each == check has to to be replaced by an equals() check.
If the equals(...) implementation is removed from the Point class, nothing will be removed from "upper" because the test case deliberately uses clones of the original a,b,c and d values.
import java.util.ArrayList;
import java.util.List;
import junit.framework.Assert;
import org.junit.Test;
public class TestArrayList
{
#Test
public void testRemove()
{
// Test fixture:
Point a = new Point(115, 70);
Point b = new Point(139, 66);
Point c = new Point(195, 111);
Point d = new Point(144, 165);
List<Point> upper = new ArrayList<Point>();
upper.add(a.clone());
upper.add(b.clone());
upper.add(c.clone());
upper.add(d.clone());
List<Point> remove = new ArrayList<Point>();
remove.add(a.clone());
remove.add(b.clone());
remove.add(c.clone());
remove.add(d.clone());
// Assertions:
Assert.assertTrue(upper.size() == 4);
Assert.assertTrue(remove.size() == 4);
// Modified code:
System.out.println(upper.toString());
System.out.println(remove.toString());
for (Point p : remove)
{
upper.remove(p);
}
System.out.println(upper.toString());
System.out.println(remove.toString());
// Assertions:
Assert.assertTrue(upper.isEmpty());
Assert.assertTrue(remove.size() == 4);
}
}
class Point implements Cloneable
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
#Override
public Point clone()
{
return new Point(x, y);
}
#Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
else if (o instanceof Point)
{
Point p = (Point) o;
return x == p.x && y == p.y;
}
else
{
return false;
}
}
#Override public String toString()
{
return "X: " + x + " Y: " + y;
}
}
Related
I have a Point list that stores (x, y) values. The list is this
List<Point> path = new ArrayList<>();
However, I want to be able to get the previous index of a specific index from that list. For example I have this Point list :
[(4,4), (1,4), (2,3), (0,1)]
How can I get the previous index of (2,3), that would the (1,4),(4,4)?
Any help?
You need to override the equals(Object obj) method so that we can perform search.
class Point {
public int x, y;
public Point(int x, int y){ this.x=x; this.y=y;}
public boolean equals(Object o){
if (o instanceof Point){
Point p = (Point) o;
return x == p.x && y == p.y;
}
return false;
}
public String toString(){
return String.format("(%d,%d)", x,y);
}
}
indexOf() will return the index where p is found. Or you could use List.indexOf() instead.
static int indexOf(List<Point> path, Point p){
for(int i=0; i<path.size(); i++)
if (path.get(i).equals(p)) return i;
return -1;
}
Find the index of the point
Every point before that point are previous points.
public static void main(String[] args) {
List<Point> path = new ArrayList<>(
List.of(new Point(0,0), new Point(1,1),
new Point(2,2), new Point(3,3)));
int index = indexOf(path, new Point(2,2));
List<Point> prevs = new ArrayList<>();
for(int i=0; i<index; i++)
prevs.add(path.get(i));
System.out.println(prevs);
}
Output:
[(0,0), (1,1)]
You could do something like this:
// Define the point or get the point that you are searching for some different way
Point x = Point(2,3)
int previousIndex = path.indexOf(x) - 1;
// Make sure we are not out of bounds
if (previousIndex >= 0){
return path.get(previousIndex)
// Would return (1, 4)
}
Make use of indexOf and make sure you are not out of bounds. That is pretty much all there is to it. If you want to get all previous points you could do something like this
new ArrayList(paths.subList(0 ,previousIndex+1))
I am trying to find a method countVertices() which needs to returns the number of vertices in the same connected component of the given vertex using DFS.
I am not able to understand why am I always getting 2 when there are 3 connected components (including parent) for my graph. It's going wrong for all of the tests I tried
My code for the method looks like this:
public static int countVertices(Graph g, Graph.Vertex v) {
Set<Graph.Vertex> known = new HashSet<>();
int num = 0;
if(g == null || v == null)
return 0;
for(Graph.Vertex u : g.getAllVertices()) {
if(!known.contains(u)) {
num++;
DFS(g, u, known);
}
}
return num;
}
public static void DFS(Graph g, Graph.Vertex v, Set<Graph.Vertex> known) {
known.add(v);
for(Graph.Vertex vertex : g.getNeighbours(v)) {
if(!known.contains(vertex))
DFS(g, vertex, known);
}
}
I tried the following in my main() method:
public static void main(String[] args){
Graph g = new Graph();
Graph.Vertex v = new Graph.Vertex(1);
Graph.Vertex w = new Graph.Vertex(2);
Graph.Vertex x = new Graph.Vertex(3);
Graph.Vertex y = new Graph.Vertex(4);
g.addVertex(v);
g.addVertex(w);
g.addVertex(x);
g.addVertex(y);
g.addEdge(v, w);
g.addEdge(w, y);
System.out.println(countVertices(g, v)); // this outputs 2, it should be 3
System.out.println(countVertices(g, x)); // this outputs 2, it should be 1
}
I am not able to figure out what am I doing wrong? I would appreciate any help.
Edit:
public static int countVertices(Graph g, Graph.Vertex v) {
Set<Graph.Vertex> known = new HashSet<>();
int num = 1;
if(g == null || v == null)
return 0;
//for(Graph.Vertex u : g.getNeighbours(v)) {
if(!known.contains(v)) {
num++;
DFS(g, v, known);
}
//}
return num;
}
v-w and w-y are 2 edges that belong to the same component. x is the only isolated vertex. Therefore, the correct output is 2 connected components and not 3.
EDIT: If you remove either the edge between v-w OR w-y, you will have 3 connected components.
A method that I used recently is to check if two vertices have the same root. In your case, if we take v as the root then w is child to v and y is child to w => y is child to v and therefore is one component. x is a root vertex with no children therefore another component. I hope this gives some insight on connected components.
As for the number of vertices, your int num = 0 should probably be int num = 1. This is because if the graph is not null, then the graph has at least one vertex.
// after a short discussion, we found the solution
// return the size of HashSet known
public static int countVertices(Graph g, Graph.Vertex v) {
Set<Graph.Vertex> known = new HashSet<>();
int num = 0;
if(g == null || v == null)
return 0;
// no loop, call DFS method and it will call itself recursively
// and it will call the get neighbors()
if(!known.contains(v)) {
num++;
DFS(g, v, known);
}
return known.size();
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I was given this question in a programming test for an IT company.
I will try my best to explain it.
The problem is as follows:
Given an Ant at origin (0,0) which moves only in clockwise direction( takes only right turns) on a given path array. so for example if the path array is {2,3,4,5,7} the ant moves 2 units left, then moves 3 units down , then moves 4 units right, then moves 5 units up and then 7 units left so on and so forth.
So write a code which displays the ant's final position(coordinates) and state if the ant intersects it's path in the format:
Ant: (x1,y1) :(yes / no)
for example:
(1) array={1,6,3,5,4}
output: Ant: (2,-1) :yes
showing it graphically
(0, 0)__(1,0)
|
(-2,-1) __ __ __ __(2,-1)
| |
| |
| |
| |
| |
(-2,-6) __ __ __ (1,-6)
here the ant is intersecting its path at (1,-1)
(2) array={2,2,2,1}
output: Ant: (0,-1) :no
showing it graphically
(0, 0)__ __(2,0)
.(0,-1) |
| |
(0,-2)__ __(2,-2)
here the ant doesn't intersect its path.
I wrote a code to find the final position:
public class Ant {
static void findAnt(int arr[])
{
int count = 0;
int x=0,y=0;
for(int element: arr){
if(count>3)
count = 0;
switch(count++){
case 0: x=x+element;
break;
case 1: y=y-element;
break;
case 2: x=x-element;
break;
case 3: y=y+element;
break;
}
}
System.out.println("Ant: "+x+" "+y);
}
public static void main(String[] args)
{
int arr[] = new int[]{2,2,2,1};
findAnt(arr);
}
}
However I cannot devise an algorithm that shows if the ant intersects or not.
Please advise.
It will horizontally intersect if arr[1] <= arr[3] and vertically if arr[0] <= arr[2] you just need to check these positions.
for (int i = 0; i < arr.length; i++){
if (i == arr.length-2)
return false;//prevents indexoutofbounds
if (arr[i] <= arr[i+2])
return true;//intersects
}
this should check to see if p0 is less than p2, p1, is less than p3, and p2 is less than p4, and so on.
boolean intersect = false;
for (int i = 0; i < arr.length; i++){
if (arr[i] == arr[arr.length-2]){//i changed this
intersect = false;//prevents indexoutofbounds
break;
}
if (arr[i] <= arr[i+2])
intersect = true;//intersects
break;
}
and then print out intersect
One solution that doesn't keep a grid in memory, is to keep a set of visited locations in memory. This has the advantage that you don't need to know the boundary of the ant's potential path in advance. Whether it takes more or less memory than a grid, depends on the size of the grid, and the length of the ant's journey.
public class VisitedTileLog {
Set visitedTiles = new HashSet<Coordinates>();
boolean hasIntersected = false;
public void logVisit(Coordinates c) {
if(! visitedTiles.add(c)) {
hasIntersected = true;
}
}
public boolean hasIntersected() {
return hasIntersected;
}
}
Of course you need a Coordinates class with equals() and hashCode():
public class Coordinates {
private int x,y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public boolean equals(Object o) {
// Let your IDE write this, or read up on best practice.
}
public int hashCode() {
// Let your IDE write this, or read up on best practice.
}
// Examples of other methods this might have...
public int getX() { ... }
public int getY() { ... }
public Coordinates move(int distance, Direction direction);
}
Now you can take your ant for a walk, and each time it moves, update hasIntersected:
VisitedTileLog log = new VisitedTileLog();
for(int distance : distances) {
...
log.logVisit(...);
...
}
This class could be enhanced with convenience methods that log a whole step's line -- logVisit(Coordinates from, Coordinates to) or logVisit(Coordinates start, int distance, CompassPoint direction).
Depending on the interviewer, a solution like this might get you extra credit for being object-oriented. Indeed, this class could be enhanced to solve the whole of the problem, if it also maintained a currentPosition field.
One way to achieve this is to draw the line during each move for reference. And check before every move that if it is encountering the same coordinate that is already drawn. Below is the code for this approach. You can definitely fine tune it , but here is one way to tackle it.
Steps :
Create Coordinate type to store coordinates.
Create Ant that can hold :
current coordinate: this will hold the Ant Current Coordinate at any time
Direction to Move next : right , left , up or down
data set to keep track of traversed coordinate
data structure to hold all coordinates that are revisited
Now on every move of ant, it knows what direction to move next. And in each move , we draw all coordinates in between the current coordinate and the end point , and store them in traversed coordinate set. If there is hit, we store it in intersected coordinate set instead.
At the end, current coordinate of ant gives us the final coordinate and the line crosses over if the intersected set is not empty.
Here is the long code , that I assume is working fine.
public class PathCross {
public static void main(String[] args) {
int[] movementArray = { 2, 2, 2, 1 };// {1,6,3,5,4};
PathCross driver = new PathCross();
Ant ant = driver.new Ant();
for (int i : movementArray) {
ant.move(i);
}
System.out.println("Ant: (" + ant.currentCoordinate.getX() + "," + ant.getCurrentCoordinate().getY() + ") :"
+ !ant.getIntersectingCoordinates().isEmpty());
}
class Ant {
Coordinate currentCoordinate = new Coordinate(0, 0);
Direction nextDirection = Direction.RIGHT;
Set<Coordinate> intersectingCoordinates = new HashSet<>();
Set<Coordinate> traversedCoordinateSet = new HashSet<>();
public Ant() {
traversedCoordinateSet.add(new Coordinate(0, 0));
}
public Coordinate getCurrentCoordinate() {
return currentCoordinate;
}
public void setCurrentCoordinate(Coordinate currentCoordinate) {
this.currentCoordinate = currentCoordinate;
}
public Direction getNextDirection() {
return nextDirection;
}
public void setNextDirection(Direction nextDirection) {
this.nextDirection = nextDirection;
}
public Set<Coordinate> getIntersectingCoordinates() {
return intersectingCoordinates;
}
public void setIntersectingCoordinates(Set<Coordinate> intersectingCoordinates) {
this.intersectingCoordinates = intersectingCoordinates;
}
public Set<Coordinate> getTraversedCoordinateSet() {
return traversedCoordinateSet;
}
public void setTraversedCoordinateSet(Set<Coordinate> traversedCoordinateSet) {
this.traversedCoordinateSet = traversedCoordinateSet;
}
public void move(int distance) {
Coordinate newCoordinate = null;
switch (nextDirection) {
case RIGHT:
newCoordinate = new Coordinate(currentCoordinate.getX() + distance, currentCoordinate.getY());
for (int i = currentCoordinate.getX() + 1; i <= (currentCoordinate.getX() + distance); i++) {
if (!traversedCoordinateSet.add(new Coordinate(i, currentCoordinate.getY()))) {
intersectingCoordinates.add(new Coordinate(i, currentCoordinate.getY()));
}
}
nextDirection = Direction.DOWN;
break;
case DOWN:
newCoordinate = new Coordinate(currentCoordinate.getX(), currentCoordinate.getY() - distance);
for (int i = currentCoordinate.getY() - 1; i >= (currentCoordinate.getY() - distance); i--) {
if (!traversedCoordinateSet.add(new Coordinate(currentCoordinate.getX(), i))) {
intersectingCoordinates.add(new Coordinate(currentCoordinate.getX(), i));
}
}
nextDirection = Direction.LEFT;
break;
case LEFT:
newCoordinate = new Coordinate(currentCoordinate.getX() - distance, currentCoordinate.getY());
for (int i = currentCoordinate.getX() - 1; i >= (currentCoordinate.getX() - distance); i--) {
if (!traversedCoordinateSet.add(new Coordinate(i, currentCoordinate.getY()))) {
intersectingCoordinates.add(new Coordinate(i, currentCoordinate.getY()));
}
}
nextDirection = Direction.UP;
break;
case UP:
newCoordinate = new Coordinate(currentCoordinate.getX(), currentCoordinate.getY() + distance);
for (int i = currentCoordinate.getY() + 1; i <= (currentCoordinate.getY() + distance); i++) {
if (!traversedCoordinateSet.add(new Coordinate(currentCoordinate.getX(), i))) {
intersectingCoordinates.add(new Coordinate(i, currentCoordinate.getY()));
}
}
nextDirection = Direction.RIGHT;
break;
default:
System.err.println("ERRor");
}
this.currentCoordinate = newCoordinate;
}
}
enum Direction {
LEFT, DOWN, RIGHT, UP;
}
class Coordinate {
int x;
int y;
public Coordinate() {
}
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + x;
result = prime * result + y;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Coordinate other = (Coordinate) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
private PathCross getOuterType() {
return PathCross.this;
}
#Override
public String toString() {
return "x=" + x + ", y=" + y;
}
}
}
The problem is hard to find out whether it intersect the previous paths. I create a boolean to record whether it is increase the circle or not. if it is always increasing, it will not intersect the previous paths. If it change to the decreasing, once it began to increasing again, it will intersects the paths. Otherwise, it will not intersects the path
def ant(arr):
length = len(arr)
x = sum(arr[::4]) - sum(arr[2:][::4])
y = sum(arr[3:][::4]) - sum(arr[1:][::4])
if length < 4:
return x, y, False
t1, (t2, t3, t4) = 0, arr[:3]
increase = (t2 < t4)
for i in xrange(3, length):
t5 = arr[i]
if increase and t3 >= t5:
if t1 + t5 - t3 < 0 or i+1 < length and arr[i+1] + t2 - t4 < 0:
increase = False
elif i + 1 < length:
return x, y, True
elif not increase and t3 <= t5:
return x, y, True
t1, t2, t3, t4 = t2, t3, t4, t5
return x, y, False
Having some trouble building an equals method that compares two dimensional coordinate points in a list based on distance from point zero (0,0) -equation included.
public double distanceToOrigin() {
return distance(zero);
}
public double distance(Point that) {
return Math.sqrt(Math.pow((x - that.getX()), 2) + Math.pow((y - that.getY()), 2));
}
boolean equals(List<Point> lst){
boolean eq = true;
for (int i=0; i<lst.size(); i++)//accounts for first element-to-compare.
{
for (int q = 1; q < lst.size(); q++)//accounts for second element-to-compare.
{
if(lst.distanceToOrigin(i) == (lst).distanceToOrigin(q)))
{
eq = false;
}
}
}
return eq;
}
I may be over-interpreting the if statement: is there a more efficient way to compare both elements (in a single line of code)?
For reference:
static Point zero = new Point(0, 0);
public int getX(){
return x;
}
public int getY(){
return y;
}
Assistance heartily appreciated.
Examples of lists:
List<Point> lst = new ArrayList<Point>();
The corrected equals method would appear similar to the following (somewhat clumsy implementation currently):
boolean equals(List<Point> lst){
boolean eq = true;
for (int i=0; i<lst.size(); i++)//accounts for first element-to-compare.
{
for (int q = 1; q < lst.size(); q++)//accounts for second element-to-compare.
{
if(lst.get(i).distanceToOrigin() == lst.get(q).distanceToOrigin()){
eq = false;
}
}
}
return eq;
}
The equals method should return boolean true or false based on whether or not element-to-compare(1) is identical to element-to-compare(2).
If you are looking for equal distances of two points you are likely better off just comparing the sum of the squares of the coordinates. That avoids comparing floats and is more efficient:
class Point {
public boolean isSameDistanceFromOrigin(Point other) {
return x * x + y * y == other.x * other.x + other.y * other.y;
}
}
If I'm interpreting your loop correctly you want to return false if any two points in a list are the same distance from the origin. Here's an algorithm for doing that in one line (sort of) using Java 8:
public boolean areAllDifferentDistancesFromOrigin(List<Point> points) {
return points.stream().noneMatch(point ->
points.stream().filter(p -> p != point)
.anyMatch(p-> point.isSameDistanceFromOrigin(p)));
}
There's a group:
S = {(xi,yi)|1 ≤ i ≤ n}
of n points. There are no 2 points (xi,yi) (xj,yj) where xi = xj and yi = yj.
It means the x and y values are unique. I need to find a data structure that supports the functions:
Given x, return the value of y where (x,y) is in S. If it doesn't exist return "not exist".
Given y, return the value x where (x,y) is in S. If it doesn't exist return "not exist".
A simple solution will be to create two sorted arrays (one sorted according to the x values and the second sorted according to the y values). To find y with a given x will take O(logn), by using binary search. The same for finding x.
I can't use more than one array (of n elements) and each element is a point.
I need to find an efficient data structure that can do those actions in an optimal time. I need to find:
T(first function)+T(second action).
Which data structure is the most efficient in this case?
Thank you very much.
Fundamentally, you just need a pair of maps:
Map<TypeOfX, TypeOfY> mapXtoY;
Map<TypeOfY, TypeOfX> mapYtoX;
You can use any concrete implementation of Map, e.g. HashMap, TreeMap, LinkedHashMap...
To add a point, you simply add it to both:
void addPoint(TypeOfX x, TypeOfY y) {
mapXtoY.put(x, y);
mapYtoX.put(y, x);
}
And you can get the y for an x by using:
TypeOfY y = mapXtoY.get(x);
and vice versa.
Libraries such as Guava provide BiMap implementations, which maintain this two-directional mapping for you.
Note: I dont read your condition '(xi, yi), (xj, yj) => xi != xj && yi != yj' as you do, to me this only means that the coordinates are unique (not each x and each y).
So you first must create a Point object
public class Point {
public int x;
public int y;
public Point(int x, int y) { this.x = x; this.y = y; }
}
Then store all your points into a unique array (you said you need it)
Point[] POINTS = ... // fill your array depending on your input
Finally wrap ths array into a class that provides the methods you need
public class PointCollection {
public Point[] points;
public Map<Integer, List<Integer>> mapX = new HashMap<Integer; List<Integer>>();
public Map<Integer, List<Integer>> mapY = new HashMap<Integer; List<Integer>>();
public PointCollection(Points[] points) {
this.points = points;
for (Point p : points) {
mapX.getOrDefault(p.x, new ArrayList<Integer>()).add(p.y);
mapY.getOrDefault(p.y, new ArrayList<Integer>()).add(p.x);
}
}
public int[] getMatchingY(int x) {
List<Integer> result = new ArrayList<Integer>();
for (Point p : this.points)) {
if (p.x == x) result.add(p.y);
}
return result.toArray(new int[result.size()]);
}
public int[] getMatchingX(int y) {
List<Integer> result = new ArrayList<Integer>();
for (Point p : this.points)) {
if (p.y == y) result.add(p.x);
}
return result.toArray(new int[result.size()]);
}
public int[] getMatchingYFromMap(int x) {
List<Integer> result = mapX.getOrDefault(x, new ArrayList<Integer>());
return result.toArray(new int[result.size()]);
}
public int[] getMatchingXFromMap(int y) {
List<Integer> result = mapY.getOrDefault(y, new ArrayList<Integer>());
return result.toArray(new int[result.size()]);
}
}
edit: added solution based on map