Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alex-popov-tech/cf1fd154609b6b746933e2fa64d604b1 to your computer and use it in GitHub Desktop.
Save alex-popov-tech/cf1fd154609b6b746933e2fa64d604b1 to your computer and use it in GitHub Desktop.
import java.util.*;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toSet;
final class Matrix {
private final List<List<Integer>> matrix;
public Matrix(List<List<Integer>> matrix) {
this.matrix = matrix;
}
public Collection<MatrixCoordinate> getSaddlePoints() {
return IntStream.range(0, matrix.size())
.mapToObj(
i -> IntStream.range(0, matrix.get(i).size())
.filter(j -> matrix.get(i).get(j) <= columnMin(j))
.filter(j -> matrix.get(i).get(j) >= rowMax(i))
.mapToObj(j -> new MatrixCoordinate(i, j))
.collect(toSet()))
.flatMap(Set::stream).collect(toSet());
}
private int columnMin(final int number) {
return matrix.stream().map(row -> row.get(number)).min(Integer::compareTo).orElseThrow(RuntimeException::new);
}
private int rowMax(final int number) {
return matrix.get(number).stream().max(Integer::compareTo).orElseThrow(RuntimeException::new);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment