Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Find middle item in list

Tags:

list

elixir

I'm trying to learn Elixir. In most other languages i've battled with, this would be an easy task.

However, i can't seem to figure out how to access a list item by index in Elixir, which i need for finding the median item in my list. Any clarification would be greatly appreciated!

like image 519
dellitsni Avatar asked Jan 03 '23 03:01

dellitsni


2 Answers

You will want to look into Enum.at/3.

a = [1,2,3,4,5]
middle_index = a |> length() |> div(2)
Enum.at(a, middle_index)

Note: This is expensive as it needs to traverse the entire list to find the length of the list, and then traverse halfway through the list to find what the actual element is. Generally speaking, if you need random access to an item in a list, you should be looking for a different data structure.

like image 75
Justin Wood Avatar answered Jan 13 '23 01:01

Justin Wood


This is how I would do it:

Enum.at(x, div(length(x), 2))

Enum.at/3 retrieves the value at a particular index of an enumerable. div/2 is the equivalent of the Python 2.x / integer division.

like image 26
tom Avatar answered Jan 13 '23 00:01

tom