-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExample10.java
75 lines (51 loc) · 1.73 KB
/
Example10.java
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
package applications.algorithms;
import datastructs.adt.ArrayStack;
import java.util.Random;
/**
* A train holds items for three different destinations
* We need to sort the cars in such a way so that the cars
* are grouped according to the destination
*/
public class Example10 {
public static void run(String[] args) {
Random random = new Random();
random.setSeed(2);
ArrayStack<Integer> input = new ArrayStack<Integer>(20);
for (int i = 0; i < input.size(); ++i) {
input.push(random.nextInt());
}
// holds items for destination 2
ArrayStack<Integer> hold1 = new ArrayStack<Integer>(20);
// holds items for destination 3
ArrayStack<Integer> hold2 = new ArrayStack<Integer>(20);
// holds items for destination 1
ArrayStack<Integer> output = new ArrayStack<Integer>(20);
for(int i=0; i<input.size(); ++i){
Integer integer = input.pop();
if(integer.intValue() == 2){
hold1.push(integer);
}
else if(integer.intValue() == 3){
hold2.push(integer);
}
else{
output.push(integer);
}
}
//assume that the items for destination 3 should go last
//item with destination 1 after and first the items with
// destination 2
for(int i=0; i<hold2.size(); ++i){
input.push(hold2.pop());
}
for(int i=0; i<output.size(); ++i){
input.push(output.pop());
}
for(int i=0; i<hold1.size(); ++i){
input.push(hold1.pop());
}
}
public static void main(String[] args){
Example10.run(args);
}
}