比如说, 我希望验证一个排序算法是否正确. 我不想自己去写测试数据, 有没有什么库能够自动生成包含数据的数组或其它的容器类.
比如能够自动生成一个长度为100的有序int数组等等.
巴扎黑2017-04-18 10:50:41
Keywords, shuffle
public static List<Integer> generateRandomArray(int len)
{
if(len <= 0)
{
throw new IllegalArgumentException(len + " can not be negitive.");
}
List<Integer> arr = new ArrayList<>(len);
for(int i = 0; i < len; i++)
{
arr.add(i);
}
Collections.shuffle(arr);
return arr;
}
PHP中文网2017-04-18 10:50:41
I have never heard of such a library - but for this kind of simple method, I suggest "do it yourself and have enough food and clothing". Based on your current foundation, you should think more, write more and practice more - implementing this type of method yourself is a good foundation-laying process.
What you need now is not a method to generate an ordered array. What you need is the following two methods:
Generate an unordered integer array of length n. The range of the array elements is 0 ~ bound:
public int[] randomArray(int n, int bound) {
Random random = new Random();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = random.nextInt(bound);
}
return array;
}
Determine whether array is sorted in ascending order:
public boolean isAscending(int[] array) {
for (int i = 1; i < array.length; i++) {
if (array[i - 1] > array[i]) { // 判断降序的话,将 > 改成 <
return false;
}
}
return true;
}
With these two methods, you can generate an integer array for sorting and determine whether the integer array is in order.