Divide the list into two equal halves (± 1)

I know that I can divide an even list into two equal halves in an elixir by doing this:

list = [1, 2, 3, 4, 5, 6] len = length(list)/2 |> round [a, b] = Enum.chunk(list, len) # => [[1, 2, 3], [4, 5, 6]] 

but is there a ruby-esque built-in or more efficient way that also processes odd-length lists?

+6
source share
3 answers

Enum.chunk actually takes 4 arguments and will work with an odd-length list if you include the 4th ( pad ) argument:

 iex(14)> Enum.chunk([1,2,3,4,5], 3, 3, []) [[1, 2, 3], [4, 5]] 
+8
source

After going through the documents and searching elsewhere, I still did not find a built-in solution, but I came across Enum.split/2 This method seems more suitable for splitting odd-length lists, but returns a tuple list instead of a list of lists.

I still don't know how effective this is.

Example:

 def split(list) do len = round(length(list)/2) Enum.split(list, len) end split([1, 2, 3, 4]) # => {[1, 2], [3, 4]} split([5, 6, 7, 8, 9]) # => {[5, 6, 7], [8, 9]} 
+4
source

I do not believe that there is any “more idiomatic” way to do this. I do not know the built-in method for this.

One suggestion - if you are dealing with larger lists, you might be better off using Stream rather than Enum.

 list = [1,2,3,4,5,6,7,8,9] s = Stream.take_every(list,2) l2 = Enum.to_list(s) #=> [1,3,5,7,9] 

And then

 l1 = list -- l2 #=> [2,4,6,8] 

You better use Stream where you can, because Stream is lazily priced. In this particular case, this will not be affected. But in some cases, lazy appreciation can really speed up the process.

As I said, my code is no more idiomatic than your solution, and this is certainly not a built-in function.

+2
source

All Articles