Is it possible to update a 2D List Values?

I have the the following list: mylist = [[1,2,3], [4,5,6], [7,8,9]]. I want to basically update its last row and 1st column value which in coding terms would be this: mylist[-1][1].

Basically, what I want to update this is with the maximum value between the value present at this specific row and column and the value at its last row and 0th column value which is: mylist[-1][0]. Something like the following:

mylist[-1][1] = max(mylist[-1][1], mylist[-1][0])

The values inside the max function can change. This is just one small example. My main goal is to try and find a way of updating the value inside this 2D list.

Any help will be appreciated. Thanks!

Lists are not really appropriate for this…

You can, but You are using them as if they were arrays.

There is an array lib, by @Qqwy

Maybe tuples can help You (with finding element at a given position).

The library is called arrays and it is thoroughly documented.

2 Likes

I would just convert the list to a map %{ {i, j} => value }, like

my_map =
  for {row, i} <- Enum.with_index(mylist), {value, j} <- Enum.with_index(row), into: %{} do
    { {i, j}, value }
  end

Then just work with the map until I eventually want to convert it back to list (or never convert back, depending on the case).

1 Like

I think it is also worth mentioning that often in Elixir you don’t actually want/need random access, and most of the time there is an efficient way to do it with plain lists by using the right function in the Enum library (or a for comprehension, or a recursive function).

If I understand your use case correctly, Enum.scan/2 might help to keep track of the maximum so far within each row:

rows = [[1, 5, 2, 3], [2, 4, 6, 2]]
Enum.map(rows, fn row -> Enum.scan(row, &max/2) end)
# [[1, 5, 5, 5], [2, 4, 6, 6]]

It takes a bit of time to get familiar with Enum, but I think it really pays off both in terms of expressiveness and efficiency.

PS: I fully understand the irony of preaching against random access after spending much time working on persistent vectors :grinning_face_with_smiling_eyes:

4 Likes