lots of exercises in java... from https://github.com/exercism/java

Matrix.java 1.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import java.util.Collections;
  2. import java.util.HashSet;
  3. import java.util.List;
  4. import java.util.Set;
  5. final class Matrix {
  6. private final List<List<Integer>> values;
  7. Matrix(final List<List<Integer>> values) {
  8. this.values = values;
  9. }
  10. Set<MatrixCoordinate> getSaddlePoints() {
  11. final Set<MatrixCoordinate> result = new HashSet<>();
  12. if (values.isEmpty()) {
  13. return result;
  14. }
  15. for (int row = 0; row < values.size(); row++) {
  16. for (int column = 0; column < values.get(0).size(); column++) {
  17. final int coordinateValue = values.get(row).get(column);
  18. if (coordinateValue == getRowMax(row) && coordinateValue == getColumnMin(column)) {
  19. result.add(new MatrixCoordinate(row, column));
  20. }
  21. }
  22. }
  23. return result;
  24. }
  25. private int getRowMax(final int row) {
  26. return Collections.max(values.get(row));
  27. }
  28. private int getColumnMin(final int column) {
  29. return values.stream()
  30. .map(row -> row.get(column))
  31. .min(Integer::compareTo)
  32. .orElseThrow(() -> new IllegalArgumentException("Column cannot be empty"));
  33. }
  34. }