~kb/sparse

3b44fbb07664509f3790704d3ab422cf468f46f4 — Kim Burgess 3 years ago ad8dd73
Support random element generation in specs
2 files changed, 28 insertions(+), 4 deletions(-)

M spec/sparse/vector_spec.cr
M spec/spec_helper.cr
M spec/sparse/vector_spec.cr => spec/sparse/vector_spec.cr +3 -4
@@ 43,15 43,14 @@ describe Sparse::Vector do

  describe "#clear" do
    it "removes all elements" do
      v = Sparse::Vector(Int32, 10000).new
      v.set_element 0, 42
      v.nvals.should eq(1)
      v = Sparse::Vector(Int32, 10000).random 100
      v.nvals.should eq(100)
      v.clear
      v.nvals.should eq(0)
    end

    it "keeps the underlying arrays in place" do
      v = Sparse::Vector(UInt8, 10000).new
      v = Sparse::Vector(UInt8, 10000).random
      idx, val = v.extract_tuples
      v.clear
      idx2, val2 = v.extract_tuples

M spec/spec_helper.cr => spec/spec_helper.cr +25 -0
@@ 1,2 1,27 @@
require "spec"
require "random"
require "../src/sparse"

module Sparse::Spec::Random
  SEED = ENV.fetch("RANDOM_SEED", "").to_u64 { ::Random.rand(UInt64) }

  SOURCE = ::Random.new SEED

  def self.rand(type)
    SOURCE.rand type
  end

  ::Spec.before_suite do
    puts "Running with random seed: #{SEED}"
  end
end

struct Sparse::Vector(T, N)
  def self.random(nvals = 1000)
    # OPTIMIZE: build in O(n) specs get slow. This is simple for now.
    idx = Array.new(nvals) { Sparse::Spec::Random.rand UInt64 }.sort!
    val = Array.new(nvals) { Sparse::Spec::Random.rand T }
    new idx, val
  end
end