forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFarmer.java
More file actions
80 lines (70 loc) · 2.66 KB
/
Copy pathFarmer.java
File metadata and controls
80 lines (70 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// David Anderson
public class Farmer{
public static void main(String[] args){
// try to move more than one thing
isMoveLegal(1, 1, 1, 1, 2, 2, 2);
// try to move the wolf when it isnt on the same side as the boat
isMoveLegal(2, 1, 1, 1, 1, 1, 1);
// try to move the goat when it isnt on the same side as the boat
isMoveLegal(1, 2, 1, 1, 1, 1, 1);
// try to move the cabbage when it isnt on the same side as the boat
isMoveLegal(1, 1, 2, 1, 1, 1, 1);
// try to make a move where the wolf would eat the goat
isMoveLegal(2, 2, 2, 2, 2, 2, 1);
// try to make a move where the goat would eat the cabbage
isMoveLegal(2, 2, 2, 2, 1, 2, 2);
// make a legal move (move the goat, leaving wolf and cabbage together)
isMoveLegal(1, 1, 1, 1, 1, 2, 1);
}
// no parameter for boatAfter because the boat always moves
public static boolean isMoveLegal(int wolfBefore, int goatBefore, int cabbageBefore, int boatBefore, int wolfAfter, int goatAfter, int cabbageAfter){
int numMoving = 0;
// is the wolf moving?
if(wolfBefore != wolfAfter){
// ensure the wolf can actually move (boat must be on the same side)
if(wolfBefore != boatBefore){
System.out.println("Cannot move the wolf if the boat isn't on the same side!");
return false;
}
numMoving++;
}
// is the goat moving?
if(goatBefore != goatAfter){
// ensure the goat can actually move (boat must be on the same side)
if(goatBefore != boatBefore){
System.out.println("Cannot move the goat if the boat isn't on the same side!");
return false;
}
numMoving++;
}
// is the cabbage moving?
if(cabbageBefore != cabbageAfter){
// ensure the cabbage can actually move (boat must be on the same side)
if(cabbageBefore != boatBefore){
System.out.println("Cannot move the cabbage if the boat isn't on the same side!");
return false;
}
numMoving++;
}
// ensure that only one item is moving
if(numMoving > 1){
System.out.println("The boat cannot hold more than one item at a time!");
return false;
}
// switch the boat to the other side
int boatAfter = boatBefore == 1 ? 2 : 1;
// ensure the wolf wont eat the goat
if(wolfAfter == goatAfter && wolfAfter != boatAfter){
System.out.println("The wolf would eat the goat!");
return false;
}
// ensure the goat wont eat the cabbage
if(goatAfter == cabbageAfter && goatAfter != boatAfter){
System.out.println("The goat would eat the cabbage!");
return false;
}
// valid move
System.out.println("Valid move!");
return true;
}
}