# Java Program to divide a number into smaller random ints

We have considered a number 10 here, which will divided into 8 random ints with Random class. The number we have set as HashSet collection −

HashSet<Integer>set = new HashSet<Integer>();
set.add(number);

Now use nextInt to get the next random integer −

intarrSize = parts + 1;
while (set.size() < arrSize) {
}
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];
}

## Example

Live Demo

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>();
int arrSize = parts + 1;
while (set.size() < arrSize) {
}
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)));
}
}

## Output

[1, 1, 2, 2, 1, 1, 1, 1]

Updated on: 30-Jul-2019

341 Views