I'm writing a method that generates a random integer array that are sorted. It takes the arguments of min value, max value and the length of desired array. So for example the arguments with min val = 1 max val = 10 length = 5 could give [1,1,2,3,5,6,9,9,9,10]
or [2,4,5,6,6,6,6,6,6,8]
. Let me know if the specifications are unclear and I'll elaborate.
Here is my code; it works but is a bit messy:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.ListIterator;
import java.util.Random;
public class test {
public static void main(String[] args)
{
System.out.println(Arrays.toString(generateSorted(10, 0, 100)));
}
public static int[] generateSorted(final int length, final int minVal, final int maxVal)
{
ArrayList<Integer> data = new ArrayList<>(length);
data.add(getRandomVal(minVal, maxVal));
boolean added;
for(int i = 0; i < length; i++)
{
added = false;
ListIterator<Integer> itr = data.listIterator();
int rndNum = getRandomVal(minVal, maxVal);
while(itr.hasNext() && !added)
{
Integer currentNum = itr.next();
if(currentNum >= rndNum)
{
itr.previous();
itr.add(rndNum);
added = true;
}
}
if(!added)//add to end of arrayList
{
data.add(rndNum);
}
//printArrList(data);
}
return data.stream().mapToInt(i -> {
return i;
}).toArray();
}
/*prints contents of arraylist all on 1 line*/
public static void printArrList(ArrayList<Integer> al)
{
System.out.print("[");
/*this could be replaced with a for (each) loop*/
al.stream().forEach((i) -> {
System.out.print(i+", ");
});
System.out.println("]");
}
/*returns random int between [min, max]*/
private static int getRandomVal(int min, int max)
{
int n = max - min + 1;
int i = rand.nextInt(n);//nextInt(n) returns random int in [0, n)
return min + i;
}
final static private Random rand = new Random();
}