0
0
Fork 0

paul's sudoku verifier / stream-heavy version

paul
paul 5 years ago
parent 863825ad1a
commit 8a47719e2b

@ -0,0 +1,58 @@
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Board {
final List<String> digits;
public Board(List<String> digits) {
this.digits = digits;
}
public Stream<Stream<String>> rows() {
return IntStream.range(0, 9).boxed()
.map(this::row);
}
Stream<String> row(int row) {
return IntStream.range(0, 9).boxed()
.map(column -> digit(row, column));
}
public Stream<Stream<String>> columns() {
return IntStream.range(0, 9).boxed()
.map(this::column);
}
Stream<String> column(int column) {
return IntStream.range(0, 9).boxed()
.map(row -> digit(row, column));
}
Stream<Stream<String>> squares() {
return IntStream.range(0, 3).boxed()
.flatMap(this::squares);
}
private Stream<Stream<String>> squares(int squareRow) {
return IntStream.range(0, 3).boxed()
.map(squareColumn -> square(squareRow, squareColumn));
}
private Stream<String> square(int squareRow, int squareColumn) {
return IntStream.range(squareRow*3, squareRow*3+3).boxed()
.flatMap(row -> squareDigitsInRow(row, squareColumn));
}
Stream<String> squareDigitsInRow(int row, int squareColumn) {
return IntStream.range(squareColumn*3, squareColumn*3+3).boxed()
.map(column -> digit(row, column));
}
String digit(int row, int column) {
int idx = row * 9 + column;
return digits.get(idx);
}
}

@ -1,20 +1,21 @@
import java.util.*; import java.util.List;
import java.io.*; import java.util.Scanner;
import java.math.*; import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
/** /**
* Template code to help you parse the standard input * Solution involving a Sukdoku Board, a SudokuVerifier, plus some Stream processing.
* according to the problem statement.
**/ **/
class Solution { class Solution {
public static void main( String[] args ) { public static void main( String[] args ) {
Scanner in = new Scanner( System.in ); Scanner in = new Scanner( System.in );
// read values with in.next...() methods Spliterator spliterator = ((Iterable) () -> in).spliterator();
List<String> digits = (List<String>) StreamSupport.stream(spliterator, false)
// code your solution here .collect(Collectors.toList());
Board board = new Board(digits);
// Write result with System.out.println() SudokuVerifier verifier = new SudokuVerifier();
System.out.println( "value" ); System.out.println(verifier.isSolved(board));
} }
} }

@ -0,0 +1,19 @@
import java.util.stream.Stream;
public class SudokuVerifier {
public boolean isSolved(Board board) {
return digitStreams(board)
.allMatch(this::isSolved);
}
Stream<Stream<String>> digitStreams(Board board) {
return Stream.of(board.rows(), board.columns(), board.squares())
.flatMap(s -> s);
}
boolean isSolved(Stream<String> digitStream) {
return digitStream.distinct().count() == 9;
}
}
Loading…
Cancel
Save