Question settingsThe farmer wants to ship cats, dogs, and fish on the left bank to the right bank by boat. During the transportation process, only one animal can be shipped at a time, and the farmer can cross the river by air. When a person is not on the bank, the dog will bite the cat and the cat will eat fish. When a person is on this bank, there will be no conflict. Use an object-oriented design to solve such problems.
Analysis: According to the Question Setting conditions, the following conclusions can be drawn: 1. There is no empty ship from the left bank to the right bank (that is, an animal must be transported from the left bank to the right bank ); 2. from right to left, there are only two cases: ① An empty boat crosses the river, and ② an animal crosses the river.
Program Design: Five classes: mycrossriver. Java, crossprocess. Java, crossstep. Java, status. Java, and animal. java. Among them, mycrossriver is the main class for running the program, and also contains the logic for crossing the river; crossprosess is the correct sequence of steps that have been recorded throughout the process; crossstep represents each step that has been taken; status indicates the encapsulation of the status of the current step (for data on the Left Bank and Right Bank, it is a deep copy); animal is an abstract of animals.
The main code is as follows:
Mycrossriver. Java:
Package COM. others; import Java. util. arraylist; import Java. util. list; /*** question about crossing the river with a cat, a dog, or a fish * @ author xuefeihu **/public class mycrossriver {/** left bank of the river **/private list <animal> left = new arraylist <animal> (); /** Right Bank **/private list <animal> right = new arraylist <animal> ();/** location of the person: true on the left, the right side is false **/private Boolean flag = true;/** cross-river process **/private crossprocess process = new crossprocess (); public static void main (String [] ARGs) {New mycrossriver (). crossriver ();}/*** initialization condition */Public void initanimal () {animal dog = new animal ("dog", 1,-1, 2 ); animal cat = new animal ("cat", 2, 1, 3); animal fish = new animal ("fish", 3, 2,-1); left. add (DOG); left. add (CAT); left. add (fish);}/*** cross-river operation */Public void crossriver () {initanimal (); While (right. size ()! = 3) {status prestatus = new status (this. left, this. right, this. flag); // record the status crossstep step = new crossstep (process. getstepcount () + 1, this. flag, null, prestatus); // create step if (this. flag) {// cross the river from left to right (no empty ship crossing the river) int leftindex = step. getnextleftindex (); int leftsize = This. left. size (); If (leftindex> = leftsize) {// roll back the data this. process. removelaststep (); crossstep step2 = This. process. getlaststep (); this. back2step (step 2 ); Continue;} else {// step for crossing the river with animals. setanimal (this. left. get (leftindex) ;}} else {// crossing the river from right to left animal = NULL; Boolean rightsecurity = This. check (right); If (rightsecurity) {animal = This. gettargetanimal (this. right); If (animal = NULL) {// when the conflict cannot be resolved, roll back the data this. process. removelaststep (); crossstep step2 = This. process. getlaststep (); this. back2step (step 2); continue;} else {step. setanimal (animal) ;}} else {// when no conflict exists, no animal step is shipped. setanim Al (null) ;}} boolean result = movebyonestep (STEP); If (! Result) {// if the execution fails, restore the previous step this. process. removelaststep (); crossstep step2 = This. process. getlaststep (); this. back2step (step2) ;}} this. process. printstepmessage ();}/*** move operation ** @ Param step * @ return true indicates that the transfer is successful, and false indicates that the transfer fails (if the transfer fails, you need to roll back to the previous step for transfer) */Public Boolean movebyonestep (crossstep step) {/** returned result: True indicates that the operation is successfully moved, and false indicates that the operation fails. **/boolean result = false; /** loop flag **/Boolean cricleflag = false; while (! Cricleflag) {int leftindex = step. getnextleftindex (); int leftsize = step. getstatus (). getleft (). size (); int rightindex = step. getnextrightindex (); If (this. flag) {// If (leftindex <leftsize) is transferred when the next index can be found {// animal = left. remove (leftindex); right. add (animal); flag =! Flag; step. setanimal (animal);} else if (leftindex> = leftsize) {return false; // return the failure information and submit it to the previous program for processing.} else if (! This. Flag) {If (step. getanimal () = NULL) {// you can cross the river by yourself. Flag =! Flag; this. process. addstep (STEP); return true;} else {// crossing the river with animals animal = right. remove (rightindex); left. add (animal); flag =! Flag ;}}// check the conflict (rollback after transfer) if (! This. flag & check (this. left) {step. addnextleftindex (); this. back2step (STEP);} else if (this. flag & check (this. right) {step. addnextrightindex (); this. back2step (STEP);} else {This. process. addstep (STEP); Result = true; cricleflag = true ;}} return result ;} /*** restore the current status to step * @ Param step */private void back2step (crossstep step) {status = step. getstatus (); this. left = status. getleft (); this. right = stat Us. getright (); this. flag = status. getflag ();}/*** get non-conflicting animals from the conflicting data: NULL */Public animal gettargetanimal (list <animal> array) is returned if no conflicting animal exists) {animal result = NULL; // clone Object List <animal> lists = new arraylist <animal> (); animal target = NULL; Animal Source = NULL; for (INT I = 0; I <array. size (); I ++) {source = array. get (I); target = new animal (source. type, source. ID, source. afraid, source. control); lists. add (target);} // query Find the object for (INT I = 0; I <lists. Size (); I ++) {result = lists. Remove (I); If (! Check (lists) {break;} lists. add (I, result);} return result;}/*** check for conflicts */private Boolean check (list <animal> array) {boolean result = true; if (array. size ()> 1) {for (INT I = 0; I <array. size (); I ++) {for (Int J = I + 1; j <array. size (); j ++) {result = array. get (I ). check (array. get (j); If (result) return result ;}} else {result = false;} return result ;}}
Crossprocess. Java
Package COM. others; import Java. util. arraylist; import Java. util. list; /*** cross-river process ** @ author xuefeihu **/public class crossprocess {/** all steps **/private list <crossstep> steps = new arraylist <crossstep> (); /*** add step * @ Param step */Public void addstep (crossstep step) {If (step. getdirection () {step. addnextleftindex ();} else {step. addnextrightindex ();} This. steps. add (STEP);}/*** Delete last step */Public crossstep removelaststep () {return this. steps. remove (this. steps. size ()-1);}/*** get the last step * @ return */Public crossstep getlaststep () {return this. steps. get (this. steps. size ()-1);}/*** print step information */Public void printstepmessage () {for (crossstep step: Steps) {system. out. println (step. getmessage () ;}}/*** get the number of current steps * @ return */Public int getstepcount () {return this. steps. size ();}}
Crossstep. Java
Package COM. sunrise. others;/*** cross-river procedure ** @ author xuefeihu **/public class crossstep {/** number of steps **/private int stepcount;/** direction: true is left-to-right, false is right-to-left **/private Boolean direction;/** the animal transported in this step **/private animal; /** status before this step **/private status;/** print statement **/private string message; /** the index to be moved to the next left **/private int nextleftindex = 0;/** the index to be moved to the next right **/private int nextrightindex = 0; /*** constructor * @ para M stepcount step count * @ Param direction: True is left to right, false is the right-to-left * @ Param animal transported in this step * @ Param status current status */Public crossstep (INT stepcount, Boolean direction, animal, status) {This. stepcount = stepcount; this. direction = direction; this. animal = animal; this. status = status; this. message = "Step" + stepcount + ": farmer will" + (this. animal = NULL? "Yourself": This. Animal. Type) + (this. Direction? "Transport from Left Bank to Right Bank": "transport from right bank to Left Bank");} public int getstepcount () {return stepcount;} public Boolean getdirection () {return direction ;} public animal getanimal () {return animal;} public status getstatus () {return status;} Public String getmessage () {return message;} public int getnextleftindex () {return nextleftindex ;} public void addnextleftindex () {This. nextleftindex ++;} public int getnextrightindex () {return nextrigh Tindex;} public void addnextrightindex () {This. nextrightindex ++;} public void setanimal (animal) {This. animal = animal; this. message = "Step" + stepcount + ": farmer will" + (this. animal = NULL? "Yourself": This. Animal. Type) + (this. Direction? "Transport from Left Bank to Right Bank": "transport from right bank to Left Bank ");}}
Status. Java
Package COM. sunrise. others; import Java. util. arraylist; import Java. util. list; /*** Current Status ** @ author xuefeihu **/public class status {/** left **/private list <animal> left = new arraylist <animal> (); /** right **/private list <animal> right = new arraylist <animal> ();/** location of the person **/private Boolean flag; /*** construct the State object-clone the corresponding data * @ Param left Left State * @ Param right state * @ Param flag person location * @ Param preself whether the previous action is individual cross-river */public status (list <animal> left, list <animal> right, Boolean flag) {This. left = newlist (left); this. right = newlist (right); this. flag = flag;}/*** clone list object */private list <animal> newlist (list <animal> array) {list <animal> result = new arraylist <animal> (); For (animal: array) {result. add (animal) ;}return result ;}public list <animal> getleft () {return left;} public list <animal> getright () {return right ;} public Boolean getflag () {return flag ;}}
Animal. Java
Package COM. sunrise. others;/*** animal entity * @ author xuefeihu **/public class animal {public string type = NULL; Public int id =-1; Public int afraid =-1; public int control =-1; Public animal (string type, int ID, int afraid, int Control) {This. type = type; this. id = ID; this. afraid = afraid; this. control = control;}/*** design a constraint: Check whether animals coexist * @ Param animal * @ return */Boolean check (animal) {return t His. afraid = animal. id | this. control = animal. id | animal. afraid = This. id | animal. control = This. id ;}@ overridepublic int hashcode () {final int prime = 31; int result = 1; Result = prime * result + ID; return result ;} @ overridepublic Boolean equals (Object OBJ) {If (this = OBJ) return true; If (OBJ = NULL) return false; If (getclass ()! = Obj. getclass () return false; animal Other = (animal) OBJ; If (ID! = Other. ID) return false; return true ;}}
Friendly reminder: (the object-oriented thinking is generally considered correct. Due to the rush of time, if you have modified the code, please attach the source code to share with you. Thank you !)
Farmer's problem of transporting cats, dogs, and fish across the river (Object Oriented)