File tree Expand file tree Collapse file tree 1 file changed +76
-0
lines changed
Chapter1_Fundamentals/c1_3_bags_queues_stacks Expand file tree Collapse file tree 1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change
1
+ package c1_3_bags_queues_stacks ;
2
+
3
+ import java .util .Iterator ;
4
+ import java .util .NoSuchElementException ;
5
+ import java .util .Random ;
6
+
7
+ public class RandomBag <Item > implements Iterable <Item > {
8
+
9
+ private int N ;
10
+ private Item [] bag ;
11
+
12
+ public RandomBag (){
13
+ N = 0 ;
14
+ bag = (Item []) new Object [1 ];
15
+ }
16
+
17
+ public boolean isEmpty (){
18
+ return N == 0 ;
19
+ }
20
+
21
+ public int size (){
22
+ return N ;
23
+ }
24
+
25
+ public void add (Item item ){
26
+ if (N == bag .length )
27
+ resize (2 * bag .length );
28
+ bag [N ++] = item ;
29
+ }
30
+
31
+ private void resize (int n ){
32
+ assert n >= N ;
33
+ Item [] temp = (Item []) new Object [n ];
34
+ for (int i = 0 ; i < N ; i ++)
35
+ temp [i ] = bag [i ];
36
+ bag = temp ;
37
+ }
38
+
39
+ @ Override
40
+ public Iterator <Item > iterator () {
41
+ // TODO Auto-generated method stub
42
+ return new ListIterator ();
43
+ }
44
+
45
+ private class ListIterator implements Iterator <Item > {
46
+
47
+ private int num ;
48
+
49
+ public ListIterator (){
50
+ randomSort ();
51
+ }
52
+
53
+ private Random rand = new Random ();
54
+ private void randomSort (){
55
+ for (int i = 0 ; i < N ; i ++){
56
+ int randomIndex = i + rand .nextInt (N - i );
57
+ Item item = bag [i ];
58
+ bag [i ] = bag [randomIndex ];
59
+ bag [randomIndex ] = item ;
60
+ }
61
+ }
62
+
63
+ @ Override
64
+ public boolean hasNext () {
65
+ return num < N ;
66
+ }
67
+
68
+ @ Override
69
+ public Item next () {
70
+ if (!hasNext ())
71
+ throw new NoSuchElementException ();
72
+ return bag [num ++];
73
+ }
74
+
75
+ }
76
+ }
You can’t perform that action at this time.
0 commit comments