# Make a matrix full of 0 and 1 in Elixir

Hi,
I would like to make a matrix with a function (my_matrix) which has 2 arguments:

@type coordinate :: { x :: integer, y :: integer}
@type list_of_coordinates:: [coordinate]
@spec my_matrix( nm :: coordinate, ls :: list_of_coordinates ) :: rs :: [[integer]]

• nm specifies the size of the matrix for example nm = { 3, 4 } then the matrix has to have 3 rows and 4 columns
• ls is list of coordinates (coordinates <= nm, so if nm = { 3, 4 } then is not allowed {3, 5} or {4, 4} in the list)

On the output I would like to get only 0 and 1. If the matrix get an empty list then all the value is 0. The list tells which value in the matrix has to be 1.

For example:

iex> my_matrix({3,3},[])
[[0,0,0],[0,0,0],[0,0,0]]

iex> my_matrix({2,3}, [{2,2}])
[[0,0,0],[0,1,0]]

iex> my_matrix({4,5}, [{1,1}, {2, 1}, {2, 5}, {4,4}])
[[1,0,0,0,0],
[1,0,0,0,1],
[0,0,0,0,0],
[0,0,0,1,0]]

Thank you for everyone who helps.

Hi,

We can help, but where are you stuck at exactly? What have you tried so far?

``````defmodule Matrix do
def my_matrix({x, y}, ones) do
for x1 <- 1..x do
for y1 <- 1..y  do
if  Enum.member?(ones, {x1,y1}) do
1
else
0
end
end
end
end

def my_matrix1({x, y}, ones) do

ones_map= ones
|>Enum.map(& {&1, 1})
|> Enum.into(%{})

for x1 <- 1..x do
for y1 <- 1..y do
# Look for the one and default to 0
Map.get(ones_map, {x1,y1}, 0)
end
end
end
end
true = Matrix.my_matrix1({3,3},[]) == [[0,0,0],[0,0,0],[0,0,0]]
true = Matrix.my_matrix1({4,5}, [{1,1}, {2, 1}, {2, 5}, {4,4}]) ==
[[1,0,0,0,0],
[1,0,0,0,1],
[0,0,0,0,0],
[0,0,0,1,0]]
true = Matrix.my_matrix1({2,3}, [{2,2}]) == [[0,0,0],[0,1,0]]

``````

Two solutions, almost exactly the same `my_matrix1` just uses a map

2 Likes

Thank you very much. I did not think of Enum’s member function.