Если случайность контролируется так, она всегда может генерировать любое количество точек данных заданного диапазона. Если случайный метод в java используется только, мы не можем гарантировать, что все числа будут уникальными.
package edu.iu.common;
import java.util.ArrayList;
import java.util.Random;
public class RandomCentroidLocator {
public static void main(String [] args){
int min =0;
int max = 10;
int numCentroids = 10;
ArrayList<Integer> values = randomCentroids(min, max, numCentroids);
for(Integer i : values){
System.out.print(i+" ");
}
}
private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {
boolean status = true;
int count=0;
for(Integer i : arr){
if(i==num){
count++;
}
}
if(count==1){
status = true;
}else if(count>1){
status =false;
}
return status;
}
// generate random centroid Ids -> these Ids can be used to retrieve data
// from the data Points generated
// simply we are picking up random items from the data points
// in this case all the random numbers are unique
// it provides the necessary number of unique and random centroids
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {
Random random = new Random();
ArrayList<Integer> values = new ArrayList<Integer>();
int num = -1;
int count = 0;
do {
num = random.nextInt(max - min + 1) + min;
values.add(num);
int index =values.size()-1;
if(unique(values, num, numCentroids)){
count++;
}else{
values.remove(index);
}
} while (!( count == numCentroids));
return values;
}
}