Method: RubyLabs::TestArray#random

Defined in:
lib/rubylabs.rb

#random(outcome) ⇒ Object

Return a value that is guaranteed to be in the array or not in the array, depending on the value of outcome. Pass :success to get a random value in the array, or pass :fail to get an item of the same type as the items in the array but which is not itself in the array. Call a.random(:fail) to get a value that will cause a search algorithm to do the maximum number of comparisons.

Example:

>> a = TestArray.new(10).sort
=> [13, 23, 24, 26, 47, 49, 86, 88, 92, 95]
>> x = a.random(:fail)
=> 22
>> search(a, x)
=> nil

:call-seq:

a.random(outcome) => Object


305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/rubylabs.rb', line 305

def random(outcome)
  if outcome == :success
    return self[ rand(self.length) ]
  elsif outcome == :fail
    raise "TestArray#random: array is universal set" if @all
    loop do
      if @max
        x = rand( @max )
      else
        x = @words[ rand( @words.length ) ].chomp
      end
      return x if @h[x] == nil
    end
  else
    return nil
  end
end