-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGenVector.java
More file actions
27 lines (23 loc) · 869 Bytes
/
GenVector.java
File metadata and controls
27 lines (23 loc) · 869 Bytes
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
package generator;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
public class GenVector {
/**
* Generates a random vector of integers, length n
*
* @param n The length of the vector
* @param m The maximum value of any element in the vector (non-inclusive)
* @return A vector of length n
*/
public static Vector<Integer> generateVector(int n, int m) {
// Use ArrayList for better performance. Vectors are synchronized, which adds overhead.
ArrayList<Integer> ret = new ArrayList<>(n); // Initialize with capacity to avoid resizing
Random rand = new Random();
for (int i = 0; i < n; i++) {
ret.add(rand.nextInt(m));
}
// Convert back to vector if the return type must be Vector. If not, returning the ArrayList directly would be more efficient.
return new Vector<>(ret);
}
}