test: NQueensTest (#5378)

This commit is contained in:
Alex Klymenko 2024-08-24 10:27:39 +02:00 committed by GitHub
parent ce4eb55e0e
commit 44d7cbbaf4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 52 additions and 7 deletions

View File

@ -36,13 +36,10 @@ public final class NQueens {
private NQueens() { private NQueens() {
} }
public static void main(String[] args) { public static List<List<String>> getNQueensArrangements(int queens) {
placeQueens(1); List<List<String>> arrangements = new ArrayList<>();
placeQueens(2); getSolution(queens, arrangements, new int[queens], 0);
placeQueens(3); return arrangements;
placeQueens(4);
placeQueens(5);
placeQueens(6);
} }
public static void placeQueens(final int queens) { public static void placeQueens(final int queens) {

View File

@ -0,0 +1,48 @@
package com.thealgorithms.backtracking;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
public class NQueensTest {
@Test
public void testNQueens1() {
List<List<String>> expected = Arrays.asList(Arrays.asList("Q"));
assertEquals(expected, NQueens.getNQueensArrangements(1));
}
@Test
public void testNQueens2() {
List<List<String>> expected = new ArrayList<>(); // No solution exists
assertEquals(expected, NQueens.getNQueensArrangements(2));
}
@Test
public void testNQueens3() {
List<List<String>> expected = new ArrayList<>(); // No solution exists
assertEquals(expected, NQueens.getNQueensArrangements(3));
}
@Test
public void testNQueens4() {
List<List<String>> expected = Arrays.asList(Arrays.asList(".Q..", "...Q", "Q...", "..Q."), Arrays.asList("..Q.", "Q...", "...Q", ".Q.."));
assertEquals(expected, NQueens.getNQueensArrangements(4));
}
@Test
public void testNQueens5() {
// Only the number of solutions is tested for larger N due to the complexity of checking each board configuration
List<List<String>> result = NQueens.getNQueensArrangements(5);
assertEquals(10, result.size()); // 5x5 board has 10 solutions
}
@Test
public void testNQueens6() {
List<List<String>> result = NQueens.getNQueensArrangements(6);
assertEquals(4, result.size()); // 6x6 board has 4 solutions
}
}