recursive.codes


The Personal Blog of Todd Sharp

Brain Teaser: Split An Array Into Equal Parts

Posted By: Todd Sharp on 3/28/2017 7:01 GMT
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?

Image by Franc-Comtois from Pixabay



Related Posts

Simulating Texas Hold'em With Groovy

Simulating Texas Hold'em With Groovy

Last week I had a bit of free time and decided to see how difficult it would be to write a Texas Hold'em poker simulation in Groovy.  My goal wasn't...

Spark Java "Flash" Scope

Spark Java "Flash" Scope

One of the handiest features of Grails is the "flash" scope.  The flash scope is "A temporary storage map that stores objects within the session for...

Realtime GPIO On Raspberry Pi With Spark Java And WebSockets

Realtime GPIO On Raspberry Pi With Spark Java And WebSockets

One of the cooler things about the Spark Java framework is built in websocket support thanks to the embedded Jetty server.  I've long been fascinated...

Note: Comments are currently closed on this blog. Disqus is simply too bloated to justify its use with the low volume of comments on this blog. Please visit my contact page if you have something to say!