Farmers transporting cats and dogs across the river problem (object oriented)

Source: Internet
Author: User

let the title : Farmers want the left bank of the cat to be transported to the right bank by boat, dog and fish.

In the course of transportation, only one animal can be transported at a time. The river farmer can empty the boat.

When people are not on this bank, the dog will bite the cat. Cats can eat fish. When people are on this bank, there is no conflict.

Please use object-oriented design ideas to solve this kind of problem.

Analysis : The following conclusions can be obtained by setting conditions: 1. Left to right, there is no empty ship from the left bank to the right bank (that is, from the left bank to the right bank must transport an animal only); 2, right to left. There are only two cases: ① empty boat across the river, ② with a mere animal across the river.

Programming : 5 classes: Mycrossriver.java, Crossprocess.java, Crossstep.java, Status.java, Animal.java. Of Mycrossriver is the main class of program execution, also includes the river crossing logic; crossprosess is the correct sequence of steps to record the whole process; Crossstep represents every step Status represents the encapsulation of the state of the current step (for the left bank and right bank data is a deep copy); Animal is an abstraction of animals.

The main code such as the following:

Mycrossriver.java:

Package Com.others;import java.util.arraylist;import java.util.list;/** * Cat Pike River crossing Problem * @author Xuefeihu * */public class MyCr Ossriver {/** river Left Bank **/private list<animal> ieft = new arraylist<animal> ()/** River right bank **/private List<Animal&gt ; right = new arraylist<animal> ();/** person's position: Left is true, False **/private Boolean flag = true;/** crossing step **/private CROSSPR ocess process = new crossprocess ();p ublic static void Main (string[] args) {new Mycrossriver (). Crossriver (); /** * Initialize the 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);} /** * River Operation */public void Crossriver () {initanimal (); while (Right.size ()! = 3) {Status Prestatus = new status (This.left, this. Right, This.flag);//Record the pre-step status crossstep step = new Crossstep (Process.getstepcount () +1, This.flag, NULL, prestatus);// Create step if (This.flag) {//From left to right across the river (there is no empty ship crossing) int leftindex = Step.getnextleftindex (); int leftsize = This.left.size (); if (Leftindex >= leftsize) {//Fallback data this.process.removeLastStep (); Crossstep Step2 = This.process.getLastStep (); This.back2step (step2); continue;} else{//with animals across the river Step.setanimal (This.left.get (Leftindex));}} else{//the river from right to left animal animal = Null;boolean rightsecurity = This.check; if (rightsecurity) {animal = This.gettargetanimal (this.right); if (animal = = NULL) {//conflict cannot be resolved, fallback data this.process.removeLastStep (); Crossstep Step2 = This.process.getLastStep (); This.back2step (step2); continue;} Else{step.setanimal (animal);}} else{//when there is no conflict. Do not ship animals step.setanimal (null);}} Boolean result = Movebyonestep (step); if (!result) {//Assuming the run fails, restore the previous step this.process.removeLastStep (); Crossstep Step2 = This.process.getLastStep (); This.back2step (STEP2);}} This.process.printStepMessage ();} /** * Move Operation * @param step * @return Returns True for transfer success, false for transfer failure (fallback to previous step for failure) */public Boolean movebyonestep (Crossstep step {/** Returns the result: True indicates that the move succeeded, false indicates failure **/boolean result = false;/** loop flag bit **/boolean Cricleflag = False;while (!cricleflag) {inT leftindex = Step.getnextleftindex (); int leftsize = Step.getstatus (). GetLeft (). size (); int rightindex = Step.getnextrightindex (); if (This.flag) {//When the next index can be found, transfer if (Leftindex < leftsize) {//Bring animals across the river animal animal = Left.remove (Leftindex); Right.add (animal); flag =!flag;step.setanimal (animal);} else if (Leftindex >= leftsize) {return false;//returns the failure information and hands over the previous layer of program processing}}else if (!this.flag) {if (step.getanimal () = = null) { At this time can single river flag =!flag;this.process.addstep (step); return true;} else{//with animals across the river animal animal = Right.remove (Rightindex); Left.add (animal); flag =!flag;}} Check for conflict conditions (fallback 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 current status to step step * @param step */private void Back2step (Crossstep step) {Status status = Step.getstatus (); this.left = s Tatus.getleft (); this.right = Status.getrigHT (); this.flag = Status.getflag ();} /** * Get non-conflicting animals from conflicting data: Returns NULL when not present */public Animal Gettargetanimal (list<animal> array) {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, SOURC E.id, Source.afraid, Source.control); Lists.add (target);} Find object for (int i = 0; i < lists.size (); i++) {result = Lists.remove (i), if (!check (lists)) {break;} Lists.add (i, result);} return result;} /** * Check if there is a conflict */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;/** * The process of crossing the river * @author Xuefeihu * */public class CrossP rocess {/** All steps **/private list<crossstep> steps = new arraylist<crossstep> ();/** * Join step * @param step step */p ublic void Addstep (Crossstep step) {if (Step.getdirection ()) {Step.addnextleftindex ();} Else{step.addnextrightindex ();} This.steps.add (step);} /** * Remove the 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 ());}} /** * Gets the current number of steps * @return */public int getstepcount () {return this.steps.size ();}}

Crossstep.java

Package com.sunrise.others;/** * Step across the river * @author Xuefeihu * */public class Crossstep {/** steps **/private int stepcount;/** Direction: True is left to right, false is right-to-left **/private Boolean direction;/** This step transports animals **/private Animal animal;/** before the step state **/private status St atus;/** Print Statement **/private String message;/** The next left side need to move the index **/private int nextleftindex = 0;/** The next right side needs to move the index **/private int Nextrightindex = 0;/** * constructor * @param stepcount number of steps * @param direction direction: True is left to right, false is right to left * @param animal this step transporting animals * @p Aram status Current state */public crossstep (int stepcount, Boolean direction, Animal Animal, status status) {This.stepcount = step Count;this.direction = Direction;this.animal = Animal;this.status = Status;this.message = "+stepCount+" Step: Farmer will "+ ( This.animal==null? "Self": this.animal.type) + (this.direction? ") From the left bank to the right bank ":" from the right bank to the 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 nextrightindex;} public void Addnextrightindex () {this.nextrightindex++;}  public void Setanimal (Animal Animal) {this.animal = Animal;this.message = "+stepcount+" Step: The farmer will "+ (This.animal==null?" Himself ": This.animal.type) + (this.direction?") From the left bank to the right bank ":" from the right bank to the left Bank ");}

Status.java

Package Com.sunrise.others;import Java.util.arraylist;import java.util.list;/** * Current status * @author Xuefeihu * */public clas s Status {/** **/private list<animal> left = new arraylist<animal> ()/** right side **/private list<animal> R ight = new arraylist<animal> ();/** person's position **/private Boolean flag;/** * construct state Object-clone corresponding data * @param left side status * @param rig HT Right state * @param flag person's position * @param preself the previous action is a person crossing the river */public status (list<animal> left, list<animal> righ T, 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& Lt Animal> (); for (Animal Animal:array) {result.add (Animal);} return result;} Public list<animal> GetLeft () {return to left;} Public list<animal> GetRight () {return to 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 restrictive relationship: check if animals can coexist * @param animal * @return */boolean Check (animal animal) {return this.afraid = Animal.id | | 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 tip: (the object-oriented thinking is generally correct; because of the time, if there is a change in code, please attach the source code to share with you, thank you!) )

Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

Farmers transporting cats and dogs across the river problem (object oriented)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.