Skip to content

Commit 5e313a8

Browse files
committed
add
1 parent 65a3c9c commit 5e313a8

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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+
}

0 commit comments

Comments
 (0)