Issue
I have a line, with points at (x1, y1)
and (x2, y2)
.
What I need is a method that will just return every point in between them, in increments of whole numbers.
For example, a line going from (0, 20)
to (0, 40)
would give me [(0, 20), (0, 21), (0, 22), ..., (0, 39), (0, 40))
.
Any help would be much appreciated!
Solution
Assuming that the Line
is horizontal or vertical and has int
coordinates, you can use IntStream
:
public static int[][] getPoints(Line line) {
int startX = (int) Math.round(line.getStartX());
int endX = (int) Math.round(line.getEndX());
int startY = (int) Math.round(line.getStartY());
int endY = (int) Math.round(line.getEndY());
if (startX != endX && startY != endY) {
throw new IllegalArgumentException("Line must be horizontal or vetical");
}
return IntStream.rangeClosed(startX, endX).boxed()
.flatMap(x -> IntStream.rangeClosed(startY, endY)
.mapToObj(y -> new int[]{x, y})).toArray(int[][]::new);
}
Then:
Line line = new Line(0, 20, 0, 40);
int[][] points = getPoints(line);
System.out.println(Arrays.deepToString(points));
Output:
[[0, 20], [0, 21], [0, 22], [0, 23], [0, 24], [0, 25], [0, 26], [0, 27], [0, 28], [0, 29], [0, 30], [0, 31], [0, 32], [0, 33], [0, 34], [0, 35], [0, 36], [0, 37], [0, 38], [0, 39], [0, 40]]
Answered By - Oboe
Answer Checked By - Gilberto Lyons (JavaFixing Admin)