Here is an approach utilizing Java8 Streams/Predicates.
- Start with the X,Y Point
- Generate the List of points surrounding the center to test -- using the predefined BOX
- Apply a predicate function to validate that the point you want to test is within the bounds of your grid.
- If so, get the value at that location and test if it is 1 [or apply any predicate here].
By defining the static logic upfront the code really just boils down to
Stream<Point> results=
BOX.stream()
.map(p -> Point.of(p.X + centerPoint.X, p.Y + centerPoint.Y))
.filter(p -> inBounds.test(p) && a6x6.get(p.X).get(p.Y) == 1);
I am sure the same logic could be applied with a few more functions in Java7 and you could use this for any grid size.
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
import java.util.stream.Stream;
public class Main {
public static class Point {
public final Integer X;
public final Integer Y;
public Point(Integer X, Integer Y){
this.X = X;
this.Y = Y;
}
public static Point of(Integer x, Integer y){
return new Point(x,y);
}
@Override
public String toString() {
return String.format("[%s,%s]", X, Y);
}
}
//Bounds of grid
private static final Point MIN = Point.of(0,0);
private static final Point MAX = Point.of(5,5);
/**
* [-1,-1][-1,0][-1,1]
* [ 0,-1][ _,_][ 0,1]
* [ 1,-1][ 1,0][ 1,1]
**/
private static final List<Point> BOX = new ArrayList<Point>(){{
add(Point.of(-1,-1));
add(Point.of(-1,0));
add(Point.of(-1,1));
add(Point.of(0,-1));
add(Point.of(0,1));
add(Point.of(1,-1));
add(Point.of(1,0));
add(Point.of(1,1));
}};
public static final Predicate<Point> inBounds =
p -> {
if (p.X < MIN.X || p.Y < MIN.Y) return false;
if (p.X > MAX.X || p.Y > MAX.Y) return false;
return true;
};
public static void main(String[] args) {
final Random rand = new Random();
final List<List<Integer>> a6x6 = new ArrayList<List<Integer>>(){{
for(int i=0;i<6;i++)
add(new ArrayList<Integer>(){{
for(int i=0;i<6;i++)
add(rand.nextInt(2) + 1);
}});
}};
final Point centerPoint = Point.of(2,2);
System.out.println("Grid = ");
a6x6.forEach(System.out::println);
System.out.println("Point = " + centerPoint.toString());
Stream<Point> results=
BOX.stream()
.map(p -> Point.of(p.X + centerPoint.X, p.Y + centerPoint.Y))
.filter(p -> inBounds.test(p) && a6x6.get(p.X).get(p.Y) == 1);
System.out.println("Results = ");
results.forEach(System.out::println);
}
}
results:
Grid =
[2, 2, 1, 2, 1, 1]
[1, 1, 1, 1, 1, 2]
[1, 2, 1, 1, 2, 1]
[2, 1, 1, 2, 1, 2]
[1, 1, 1, 1, 1, 1]
[1, 2, 2, 2, 1, 2]
Point = [2,2]
Results =
[1,1]
[1,2]
[1,3]
[2,3]
[3,1]
[3,2]