我们在这里考虑了数字10,该数字将分为8个带有Random类的随机整数。我们设置为HashSet集合的数字-
HashSet<Integer>set = new HashSet<Integer>(); set.add(0); set.add(0); set.add(0); set.add(number);
现在使用nextInt获取下一个随机整数-
intarrSize = parts + 1; while (set.size() < arrSize) { set.add(1 + randNum.nextInt(number - 1)); } Integer[] dividers = set.toArray(new Integer[arrSize]); Arrays.sort(dividers); int[] res = new int[parts]; for(int i = 1, j = 0; i < dividers.length; ++i, ++j) { res[j] = dividers[i] - dividers[j]; }
import java.util.Arrays; import java.util.HashSet; import java.util.Random; public class Demo { public static Random randNum = new Random(); public static int[] DemoFunc(int number, int parts) { HashSet<Integer>set = new HashSet<Integer>(); set.add(0); set.add(0); set.add(0); set.add(number); int arrSize = parts + 1; while (set.size() < arrSize) { set.add(1 + randNum.nextInt(number - 1)); } Integer[] dividers = set.toArray(new Integer[arrSize]); Arrays.sort(dividers); int[] res = new int[parts]; for(int i = 1, j = 0; i < dividers.length; ++i, ++j) { res[j] = dividers[i] - dividers[j]; } return res; } public static void main(String[] args) { System.out.println(Arrays.toString(DemoFunc(10, 8))); } }
输出结果
[1, 1, 2, 2, 1, 1, 1, 1]