0

I want to divide an array into 3 sub-arrays with random sizes.

For example the input array is I = [20, 5, 1, 2, 5, 10, 2, 5]

The sub-arrays could be like:

A = [20, 5]

B = [2, 5, 10]

C = [1, 2, 5]
ZEESHAN
  • 191
  • 2
  • 15
  • your question could be converted into getting three random int value whose sum is array.length ,and each integer must be more than 0,if the array length is not so big ,try with a while(true) sentence to get the result – ChenZhou Nov 18 '19 at 03:44
  • probably some of these approaches https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/ – Ryuzaki L Nov 18 '19 at 03:45
  • https://stackoverflow.com/questions/12026885/is-there-a-common-java-utility-to-break-a-list-into-batches – Ryuzaki L Nov 18 '19 at 03:47
  • please checkout this question https://stackoverflow.com/questions/2640053/getting-n-random-numbers-whose-sum-is-m – ChenZhou Nov 18 '19 at 03:51
  • actually, I wanted to split to random places, not in consecutive parts – ZEESHAN Nov 18 '19 at 04:06

1 Answers1

0

By the examples you give it looks as though the sub-arrays can overlap so the number of sub-arrays you generate is not relevant. You just want a copy of the array between a random starting and ending position.

int[] getRandomSubArray(int[] array) {
    Random random = new Random();
    int start = random.nextInt(array.length);
    int end = start + random.nextInt(array.length - start);
    return Arrays.copyOfRandom(array, start, end);
}

Then you can generate as many as you want

int[] a = getRandomSubArray(array);
int[] b = getRandomSubArray(array);
int[] c = getRandomSubArray(array);
sprinter
  • 27,148
  • 6
  • 47
  • 78