blob: 8ba0a7aa0ff03d8cdc15d79cfb50c252fe9aaa18 (
plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
|
/**
*
*/
package de.fhswf.in.inf.java1.aufgabe08;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Utility class for the Floyd and Bentley algorithm.
*
* @author $Author: $
* @version $Revision: $, $Date: $ UTC
*/
public final class FloydAndBentley
{
private static Random rnd = new Random();
/**
* Private constructor for utility class.
*
*/
private FloydAndBentley()
{
}
/**
* A function which chooses a sample from a List with the Floyd and Bentley
* algorithm. (Recursive algorithm)
*
* @param <T>
* Type of the Lists.
* @param s
* The set from which the sample is chosen.
* @param k
* The number of items to be chosen.
* @return Return the sample.
*/
public static <T> List<T> sample(List<T> s, int k)
{
if (s.isEmpty())
{
throw new IllegalArgumentException("Set is empty");
}
if (k > s.size())
{
throw new IllegalArgumentException("k is bigger than the Set");
}
List<T> ret = new ArrayList<>(k);
sampleRec(s, k, ret);
return ret;
}
/**
* The recursive implementation of the Floyd and Bentley algorithm.
*
* @param <T>
* Type of the Lists.
* @param s
* The set from which the sample is chosen.
* @param k
* The number of items to be chosen.
* @param ret
* Return the sample.
*/
private static <T> void sampleRec(List<T> s, int k, List<T> ret)
{
if (ret.size() >= k)
{
return;
}
T val = s.get(rnd.nextInt(s.size() - (k - ret.size() - 1)));
if (ret.contains(val))
{
val = s.get(s.size() - (k - ret.size() - 1));
}
ret.add(val);
sampleRec(s, k, ret);
}
/**
* A function which chooses a sample from a List with the Floyd and Bentley
* algorithm. (Non recursive algorithm)
*
* @param <T>
* Type of the Lists.
* @param s
* The set from which the sample is chosen.
* @param k
* The number of items to be chosen.
* @return Return the sample.
*/
public static <T> List<T> sample2(List<T> s, int k)
{
if (s.isEmpty())
{
throw new IllegalArgumentException("Set is empty");
}
if (k > s.size())
{
throw new IllegalArgumentException("k is bigger than the Set");
}
List<T> ret = new ArrayList<>(k);
for (int i = 0; i < k; i++)
{
T val = s.get(rnd.nextInt(s.size() - (k - ret.size() - 1)));
if (ret.contains(val))
{
val = s.get(s.size() - (k - ret.size() - 1));
}
ret.add(val);
}
return ret;
}
}
|