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

:warning: spec/collection/each_pair_spec.cr

Depends on

Code

require "spec"
require "../../src/collection/each_pair"

describe Indexable do
  it "#each_pair(&)" do
    result = [] of {Int32, Int32}
    [0, 1, 2, 3].each_pair { |i, j| result << {i, j} }
    result.should eq [{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}]
  end

  it "#each_pair" do
    [0, 1, 2, 3].each_pair.to_a.should eq [
      {0, 1}, {0, 2}, {0, 3},
      {1, 2}, {1, 3},
      {2, 3},
    ]
    (0...1000).to_a.each_pair.max_of(&.sum).should eq 998 + 999
  end
end
require "spec"

# require "../../src/collection/each_pair"
module Indexable(T)
  def each_pair(&)
    each_with_index do |x, i|
      (i + 1...size).each do |j|
        yield x, unsafe_fetch(j)
      end
    end
  end

  def each_pair
    PairIterator(self, T).new(self)
  end

  private class PairIterator(A, T)
    include Iterator({T, T})

    def initialize(@array : A)
      @i, @j = 0, 1
    end

    def next : {T, T} | Iterator::Stop
      if @j >= @array.size
        @i += 1
        @j = @i + 1
      end
      if @j >= @array.size
        stop
      else
        {@array[@i], @array[@j]}.tap { @j += 1 }
      end
    end
  end
end

describe Indexable do
  it "#each_pair(&)" do
    result = [] of {Int32, Int32}
    [0, 1, 2, 3].each_pair { |i, j| result << {i, j} }
    result.should eq [{0, 1}, {0, 2}, {0, 3}, {1, 2}, {1, 3}, {2, 3}]
  end

  it "#each_pair" do
    [0, 1, 2, 3].each_pair.to_a.should eq [
      {0, 1}, {0, 2}, {0, 3},
      {1, 2}, {1, 3},
      {2, 3},
    ]
    (0...1000).to_a.each_pair.max_of(&.sum).should eq 998 + 999
  end
end
Back to top page