private static boolean solveNQueen(int[][] board, int column) {
int boardLength = board[0].length;
if (column >= boardLength)
return true;
for (int i = 0; i < boardLength; ++i) {
if (isQueenSafe(board, i, column)) {
board[i][column] = 1;
if (solveNQueen(board, column + 1))
return true;
else
board[i][column] = 0;
}
}
return false;
}
Lo que había antes
private static boolean isQueenSafe(int[][] board, int row, int column) {
int i;
int j;
int boardLength = board[0].length;
for (i = 0; i < column; ++i)
if (board[row][i] == 1)
return false;
for (i = row, j = column; i >= 0 && j >= 0; --i, --j)
if (board[i][j] == 1)
return false;
for (i = row, j = column; j >= 0 && i < boardLength; ++i, --j)
if (board[i][j]==1)
return false;
return true;
}
Lo que había antes
public static void main(String[] args) {
int boardLength = 8;
int[][] board = new int[boardLength][boardLength];
if (!solveNQueen(board, 0)) {
System.out.println("No solution");
} else {
for (int i = 0; i < boardLength; ++i) {
System.out.println(Arrays.toString(board[i]));
}
}
}
Lo que había antes
public static void main(String[] args) {
NQueenProblem queens = new NQueenProblem(5);
for (Solution s : queens) {
System.out.println(s);
}
}
public static class Solution {
private final List<Integer> board;
private static char QUEEN = 'Q';
private static char EMPTY_SQUARE = '.';
private static String NEW_LINE = String.format("%n");
private Solution(final List<Integer> board) {
this.board = board;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < board.size(); ++i) {
for (int j = 0; j < board.size(); ++j) {
if (board.get(i) == j) {
builder.append(QUEEN);
} else {
builder.append(EMPTY_SQUARE);
}
}
builder.append(NEW_LINE);
}
return builder.toString();
}
}
private class NQueenIterator implements Iterator<Solution> {
// más código
@Override
public boolean hasNext() {
while (!queue.isEmpty()) {
List<Integer> current = queue.removeLast();
if (current.size() == size) {
this.next = new Solution(current);
return true;
}
int column = current.size();
for (int row = 0; row < size; ++row) {
if (isValid(current, column, row)) {
List<Integer> next = new ArrayList<>(current);
next.add(row);
queue.addLast(next);
}
}
}
return false;
}
@Override
public Solution next() {
return next;
}
}
public class NQueenProblem
implements Iterable<NQueenProblem.Solution> {
private final int size;
public NQueenProblem(final int n) {
this.size = n;
}
@Override
public Iterator<Solution> iterator() {
return new NQueenIterator();
}
public static class Solution {
// implementación
}
private class NQueenIterator
implements Iterator<Solution> {
// implementación
}
}
public void execute(String query)
public void execute(Query query)
En vez de
usar
public CribaDeEratóstenes() {
destacharTodosLosNúmeros();
tacharNúmerosObvios();
tacharMúltiplosDePrimosConocidos();
}
public boolean esPrimo(int n) {
return noEstáTachado(n);
}
Criba de Eratóstenes
private void tacharNúmerosObvios() {
tachar(0);
tachar(1);
}
private void tacharMúltiplosDePrimosConocidos() {
for (int n = 2;
menorMúltiploPosiblementeNoTachado(n) <= MAX_PRIMO; ++n) {
if (esPrimo(n)) {
tacharMúltiplosDe(n);
}
}
}
private void tacharMúltiplosDe(int n) {
for (int x = menorMúltiploPosiblementeNoTachado(n);
x <= MAX_PRIMO; x = siguienteMúltiplo(x, n)) {
tachar(x);
}
}
private void heapify() {
int index = size;
while (hasParent(index)
&& greater(parentIndex(index)), index) {
swap(parentIndex(index), index);
index = parentIndex(index);
}
}
}
Min Heap
private void makeHeap() {
swap(0, size);
int index = 0;
while (hasLeftChild(index)) {
int minChildIndex = getMinChildIndex(index);
if (less(parentIndex(index), minChildIndex) {
return;
}
swap(parentIndex(index), minChildIndex);
index = minChildIndex;
}
}
public static String ellipsify(String s) {
if (s.length() < 210) {
return s;
}
return s.subtring(0, 210) + "...";
}
public static String ellipsify(String s) {
if (s.length() < 210) {
return s;
}
int cut = s.indexOf(' ', 210);
if (cut == -1 || cut == s.length() - 1) {
return s;
}
return s.subtring(0, cut) + "...";
}
public final class WordSplitter {
private static final
Predicate<Character> IS_WHITESPACE = Character::isWhitespace;
private static final
Predicate<Character> IS_NOT_WHITESPACE = isWhitespace.negate();
private final String text;
private Predicate<Character> predicate;
private int i = 0;
public WordSplitter(final String text) {
this.text = java.util.Objects.requireNonNull(text);
this.predicate = isNotWhitespace.test(text.charAt(0))
? isNotWhitespace
: isWhitespace;
}
// más código
}
public final class WordSplitter {
// más código
public boolean hasNext() {
return i < text.length();
}
public String next() {
int end = next(i);
String chunck = text.substring(i, end);
i = end;
predicate = (predicate == IS_WHITESPACE
? IS_NOT_WHITESPACE
: IS_WHITESPACE);
return chunck;
}
private int next(int start) {
while (start < text.length()
&& predicate.test(text.charAt(start))) {
++start;
}
return start;
}
}
public static int count(String s, char c) {
return count(s, Character.toString(c));
}
public static int count(String s, String sub) {
int total = 0;
int idx = s.indexOf(sub);
while (idx != -1) {
++total;
idx = s.indexOf(sub, idx + 1);
}
return total;
}
private static int discountMarks(int marks) {
return marks == 0
? 0
: marks * 2;
}
private static int discountSpecialCharacters(int chars) {
return chars == 0
? 0
: chars / 2;
}
private int countChars(String s) {
return next.length()
- discountMarks(count(next, "(C)"))
- discountMarks(count(next, "(R)"))
- discountSpecialCharacters(count(next, '^'))
- discountSpecialCharacters(count(next, '~'));
}
public static String ellipsify(String text, int maxChars) {
if (text.length() <= maxChars) {
return text;
}
WordSplitter splitter = new WordSplitter(text);
StringBuilder builder = new StringBuilder();
int charCount = 0;
while (charCount < maxChars && splitter.hasNext()) {
String next = splitter.next();
if (charCount + next.length() > maxChars) {
break;
}
charCount += countChars(next);
builder.append(next);
}
return builder.append(" ...").toString();
}
public static void sort(List<T> list, Comparator<T> c)
public Thread(Runnable target)
public void addActionListener(ActionListener l)
public static Optional<Resource> getFirstChild(Resource resource,
Predicate<Resource> keep) {
for (Resource child : resource.getChildren()) {
if (keep.test(child)) {
return Optional.of(child);
}
}
return Optional.empty();
}
¡La solución, parametrizada!
assertThat(isPalindrome(""), is(true));
assertThat(isPalindrome("a"), is(true));
assertThat(isPalindrome("ab"), is(false));
assertThat(isPalindrome("radar"), is(true));
assertThat(isPalindrome("reader"), is(false));
assertThat(isPalindrome("Radar"), is(true));
assertThat(isPalindrome("A man a plan a canal Panama"), is(true));
assertThat(isPalindrome("A man, a plan, a canal - Panama"), is(true));
Pruebas Unitarias
como especificaciones
public final class Tablero {
private final int[][] tablero;
private final int filas;
private final int columnas;
private Coordenada hueco;
public Tablero() {
this.filas = 4;
this.columnas = 4;
this.tablero = new int[filas][columnas];
ordenarTablero();
this.hueco = buscar(0);
desordenar(); // utiliza Random
}
// más código
}
public final class Tablero {
// más código
public Tablero mover(int n) {
if (n < 0 || n >= filas * columnas) {
throw new IllegalArgumentException();
}
Tablero copia = new Tablero(this);
Coordenada número = copia.buscar(n);
copia.mover(número, n);
return copia;
}
}
Tablero(int[][] tablero) {
this.tablero = tablero;
this.columnas = tablero.length;
this.filas = tablero[0].length;
this.hueco = buscar(0);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Tablero other = (Tablero) obj;
if (!Arrays.deepEquals(tablero, other.tablero))
return false;
return true;
}
@Test
public void puedoMoverLaFichaAbajoDelHueco() {
Tablero inicial = new Tablero(new int[][] {{1, 2, 3},
{4, 0, 5},
{6, 7, 8}});
Tablero siguiente = new Tablero(new int[][] {{1, 2, 3},
{4, 7, 5},
{6, 0, 8}});
assertThat(inicial.mover(7), equalTo(siguiente));
}