📄 riverside.java
字号:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
* Represents a riverside in the puzzle.
*/
class RiverSide implements Serializable {
private ArrayList men = new ArrayList(), boat = new ArrayList();
public RiverSide(int nMissionary, int nCannibal, boolean withBoat) {
men.addAll(Collections.nCopies(nMissionary, MACPS.MISSIONARY));
men.addAll(Collections.nCopies(nCannibal, MACPS.CANNIBAL));
Collections.sort(men);
if (withBoat)
boat.add(MACPS.BOAT);
}
public RiverSide deepCopy() {
return (RiverSide) Copy.deepCopy(this);
}
public Collection getMenList() {
return (Collection) Copy.deepCopy(men);
}
public boolean equals(Object otherSide) {
RiverSide other = (RiverSide) otherSide;
Collections.sort(men);
Collections.sort(other.men);
return this.men.equals(other.men) && this.boat.equals(other.boat);
}
public String toString() {
return "BOAT" + boat + "\t" + "MEN" + men;
}
public boolean hasBoat() {
return !boat.isEmpty();
}
// Checks for violation of Rule #1.
public boolean fatal() {
int mCount = 0, cCount = 0;
for (Iterator i = men.iterator(); i.hasNext();) {
Object val = i.next();
if (val.equals(MACPS.MISSIONARY))
++mCount;
if (val.equals(MACPS.CANNIBAL))
++cCount;
}
return mCount > 0 && mCount < cCount;
}
// Throws SecurityException if the transfer of all men in menList
// from this to destination *will* result in violation of Rule #1.
// Else, executes the transfer.
public void transferMen(RiverSide destination, Collection menList) {
for (Iterator i = menList.iterator(); i.hasNext();)
destination.men.add(men.remove(men.indexOf(i.next())));
// A nice place to automate boat transfer.
_transferBoat(destination);
// Undo the transfer if it led to violation of Rule #1.
if (fatal() || destination.fatal()) {
destination.transferMen(this, menList);
throw new SecurityException();
}
}
// Tansfers boat from this to destination. Called only by transferMen( ).
private void _transferBoat(RiverSide destination) {
destination.boat.add(boat.remove(0));
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -