Question: Create the needed class definition, and equip the main client to print
ID: 3717011 • Letter: Q
Question
Question: Create the needed class definition, and equip the main client to print out any chains that you find.
--Code---
import java.util.*; // for ArrayList
public class SolveDominoes {
public static void main(String[] args) {
// [(1|4), (2|6), (4|5), (1|5), (3|5)]
List<Domino> dominoes = new ArrayList<Domino>();
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));
System.out.println(hasChain(dominoes, 5, 5)); // true
System.out.println(hasChain(dominoes, 1, 5)); // true
System.out.println(hasChain(dominoes, 1, 3)); // true
System.out.println(hasChain(dominoes, 1, 6)); // false
System.out.println(hasChain(dominoes, 1, 2)); // false
System.out.println(dominoes.get(0));
}
public static boolean hasChain(List<Domino> dominoes,
int start, int end) {
if (start == end) {
return true; // base case
} else {
for (int i = 0; i < dominoes.size(); i++) {
Domino d = dominoes.remove(i); // choose
if (d.first() == start) { // explore
if (hasChain(dominoes, d.second(), end)) {
return true;
}
} else if (d.second() == start) {
if (hasChain(dominoes, d.first(), end)) {
return true;
}
}
dominoes.add(i, d); // un-choose
}
return false;
}
}
}
Explanation / Answer
Required Domino class:
//class Domino
public class Domino
{
//data members of the class
int start,end;
//constructor to initialize data members
public Domino(int start, int end)
{
this.start=start;
this.end=end;
}
//first() method to return the start value
public int first()
{
return this.start;
}
//second() method to return the end value
public int second()
{
return this.end;
}
//toString() method to represent the object in readable format
public String toString()
{
return "Domino [start=" + start + ", end=" + end + "]";
}
}
//end
Output:
true
true
true
false
false
Domino [start=2, end=6]
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.