I need to create an array using a constructor, add a method to print the array as a sequence and a method to fill the array with random numbers of the type double.
He
If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.
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 values = randomCentroids(min, max, numCentroids);
for(Integer i : values){
System.out.print(i+" ");
}
}
private static boolean unique(ArrayList 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 randomCentroids(int min, int max, int numCentroids) {
Random random = new Random();
ArrayList values = new ArrayList();
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;
}
}