Adds #map_with_index to Matrix

This commit is contained in:
Rémy Marronnier 2019-09-21 04:26:30 +02:00
parent 6247c8d45a
commit e4ddcba118
2 changed files with 23 additions and 1 deletions

View File

@ -0,0 +1,10 @@
require "../spec_helper"
describe "Apatite::Matrix" do
describe ".map_with_index" do
it "returns a new matrix with each element processed according to their indexes" do
matrix = Apatite::Matrix[[1, 2], [3, 4]]
matrix.map_with_index { |e, i, j| e*i + j }.should eq Apatite::Matrix[[0, 1], [3, 5]]
end
end
end

View File

@ -384,6 +384,18 @@ module Apatite
Matrix.new(rows, column_count) Matrix.new(rows, column_count)
end end
# Same as #map, but yields the row index and column index in addition to the element
#
# ```
# matrix = Matrix[[1, 2], [3, 4]].map_with_index do |e, row, col|
# e*row + col
# end
# matrix == Matrix[[0, 1], [3, 5]] # => true
# ```
def map_with_index(&block : T, Int32, Int32 -> U) forall U
Matrix(U).build(@rows.size, @column_count) { |i, j| yield @rows[i][j], i, j }
end
# Yields all elements of the matrix, starting with those of the first row, # Yields all elements of the matrix, starting with those of the first row,
# or returns an Enumerator if no block given. # or returns an Enumerator if no block given.
# Elements can be restricted by passing an argument: # Elements can be restricted by passing an argument:
@ -446,7 +458,7 @@ module Apatite
end end
end end
# Same as #each, but the row index and column index in addition to the element # Same as #each, but yields the row index and column index in addition to the element
# #
# ``` # ```
# Matrix[[1, 2], [3, 4]].each_with_index do |e, row, col| # Matrix[[1, 2], [3, 4]].each_with_index do |e, row, col|