Java Program to divide a number into smaller random ints

Java 8Object Oriented ProgrammingProgramming

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(0);
set.add(0);
set.add(0);
set.add(number);

Now use nextInt to get the next random integer −

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];
}

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>();
      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)));
   }
}

Output

[1, 1, 2, 2, 1, 1, 1, 1]
raja
Published on 23-Apr-2019 08:47:28
Advertisements