
Data Structure

This illustrates a data structure, a means of storing data within a program.

You may see other such structures in the Data Structures category.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then output that element. Finally destroy the array if not done by the language itself.

 
defmodule TwoDimArray do
 
  def create(w, h) do
    List.duplicate(0, w)
      |> List.duplicate(h)
  end
 
  def set(arr, x, y, value) do
    List.replace_at(arr, x, 
      List.replace_at(Enum.at(arr, x), y, value)
    )
  end
 
  def get(arr, x, y) do
    arr |> Enum.at(x) |> Enum.at(y)
  end
end
 
 
width = IO.gets "Enter Array Width: "
w = width |> String.trim() |> String.to_integer()
 
height = IO.gets "Enter Array Height: "
h = height |> String.trim() |> String.to_integer()
 
arr = TwoDimArray.create(w, h) 
arr = TwoDimArray.set(arr,2,0,42)
 
IO.puts(TwoDimArray.get(arr,2,0))
 