This documentation is automatically generated by online-judge-tools/verification-helper

:warning: spec/array/new_spec.cr

Depends on

Code

require "spec"
require "../../src/array/new"

describe Array do
  it ".new(sizes, initial_value)" do
    Array.new({2, 2}, 42).should eq [[42, 42], [42, 42]]
    Array.new({2, 3}, 42).should eq [[42, 42, 42], [42, 42, 42]]
  end

  it ".new(sizes, &block)" do
    Array.new({2, 2}) { |i, j| i + j }.should eq [[0, 1], [1, 2]]
    Array.new({3, 3, 3}) { |i, j, k| i * j * k }.should eq [
      [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
      [[0, 0, 0], [0, 1, 2], [0, 2, 4]],
      [[0, 0, 0], [0, 2, 4], [0, 4, 8]],
    ]
    Array.new({3, 3}) { |i, j| {i, j} }.should eq [
      [{0, 0}, {0, 1}, {0, 2}],
      [{1, 0}, {1, 1}, {1, 2}],
      [{2, 0}, {2, 1}, {2, 2}],
    ]
  end
end
require "spec"

# require "../../src/array/new"
class Array(T)
  def self.new(sizes : Tuple(*I), initial_value) forall I
    {% begin %}
      {% for i in 0...I.size %} Array.new(sizes[{{i}}]) { {% end %}
      initial_value
      {% for i in 0...I.size %} } {% end %}
    {% end %}
  end

  def self.new(sizes : Tuple(*I), &block) forall I
    {% begin %}
      {% for i in 0...I.size %} Array.new(sizes[{{i}}]) { |index{{i}}| {% end %}
      yield({% for i in 0...I.size %} index{{i}}, {% end %})
      {% for i in 0...I.size %} } {% end %}
    {% end %}
  end
end

describe Array do
  it ".new(sizes, initial_value)" do
    Array.new({2, 2}, 42).should eq [[42, 42], [42, 42]]
    Array.new({2, 3}, 42).should eq [[42, 42, 42], [42, 42, 42]]
  end

  it ".new(sizes, &block)" do
    Array.new({2, 2}) { |i, j| i + j }.should eq [[0, 1], [1, 2]]
    Array.new({3, 3, 3}) { |i, j, k| i * j * k }.should eq [
      [[0, 0, 0], [0, 0, 0], [0, 0, 0]],
      [[0, 0, 0], [0, 1, 2], [0, 2, 4]],
      [[0, 0, 0], [0, 2, 4], [0, 4, 8]],
    ]
    Array.new({3, 3}) { |i, j| {i, j} }.should eq [
      [{0, 0}, {0, 1}, {0, 2}],
      [{1, 0}, {1, 1}, {1, 2}],
      [{2, 0}, {2, 1}, {2, 2}],
    ]
  end
end
Back to top page