recursive(codes){}


The Personal Blog of Todd Sharp

Brain Teaser: Split An Array Into Equal Parts

Posted By: Todd Sharp on 3/28/2017 11:01 UTC
Tagged: Brain Teasers, Groovy

Here's another challenge that I came across recently:

Given an array of integers greater than zero, find if it is possible to split it in two (without reordering the elements), such that the sum of the two resulting arrays is the same. Print the resulting arrays.

To clarify, given the array [1,2,3,3,2,1] it can it be split into two arrays [1,2,3] and [3,2,1] where the sum of each is equal.

Here's a set of data to work with:

List lists = [
        [1,2,3,3,2,1],
        [1,2,3,4,5,6,21],
        [1,90, 50, 30, 5, 3, 2, 1 ],
        [1, 50, 900, 1000 ],
        [500,400,100,777,223,2456,4,39,1,222,78,93,7,100,23,1000,3,20,555,345,64,36,689,100,211,2000],
        [1,2,3],
        [1]
]

Here's my solution:

Show Solution

Which provides the following result:

Show Result
[[1, 2, 3], [3, 2, 1]]
[[1, 2, 3, 4, 5, 6], [21]]
[[1, 90], [50, 30, 5, 3, 2, 1]]
[]
[[500, 400, 100, 777, 223, 2456, 4, 39, 1, 222, 78, 93, 7, 100, 23], [1000, 3, 20, 555, 345, 64, 36, 689, 100, 211, 2000]]
[[1, 2], [3]]
[]

How would you solve it differently?