// CSE 143, Winter 2011, Marty Stepp // This program uses recursive backtracking to solve the problem of whether // a group of dominoes can be lined up to produce a chain that starts and ends // with a particular number. import static org.junit.Assert.*; import org.junit.*; import java.util.*; public class DominoesTest { // Returns true if a chain of dominoes can be made from the given list // that starts and ends with the given numbers. Otherwise returns false. // Assumes that if start == end, it's trivial, so we should return true. // Precondition: 0 <= start,end <= 6 // Precondition: dominoes != null public boolean hasChain(List dominoes, int start, int end) { if (start == end) { return true; // base case } else { // start != end for (int i = 0; i < dominoes.size(); i++) { // choose: pick a domino to start the chain Domino d = dominoes.get(i); if (d.contains(start)) { // d.first() or d.last() is start dominoes.remove(i); // choose if (d.second() == start) { d.flip(); } if (hasChain(dominoes, d.second(), end)) { // explore return true; } dominoes.add(i, d); // un-choose } } return false; // tried all dominoes and none worked } } @Test public void test1() { helper(5, 5, true); } @Test public void test2() { helper(1, 5, true); } @Test public void test3() { helper(1, 3, true); } @Test public void test4() { helper(1, 6, false); } @Test public void test5() { helper(1, 2, false); } // helper for all of the JUnit test cases private void helper(int start, int end, boolean expected) { List dominoes = new ArrayList(); dominoes.add(new Domino(1, 4)); dominoes.add(new Domino(2, 6)); dominoes.add(new Domino(4, 5)); dominoes.add(new Domino(1, 5)); dominoes.add(new Domino(3, 5)); boolean actual = hasChain(new ArrayList(dominoes), start, end); assertEquals("chain from " + start + " to " + end, expected, actual); } }