fork download
  1. require "test/unit"
  2.  
  3. # Iterative implementation
  4. def chop(target, values)
  5. start = 0
  6. stop = values.length # stop indexes one past the end of the array
  7.  
  8. # loop until something is found or until we
  9. # run out of elements to search
  10. while start != stop
  11. # Find the middle
  12. mid = start + (stop - start) / 2
  13.  
  14. # Check to see if we got lucky
  15. return mid if values[mid] == target
  16.  
  17. # Not this time ... so lets see which half it might be in
  18. if target < values[pos]
  19. stop = mid
  20. else
  21. start = mid + 1
  22. end
  23. end
  24.  
  25. # Didn't find what we were looking for
  26. return -1
  27. end
  28.  
  29. class TestChop < Test::Unit::TestCase
  30.  
  31. def test_chop
  32. assert_equal(-1, chop(3, []))
  33. assert_equal(-1, chop(3, [1]))
  34. assert_equal(0, chop(1, [1]))
  35. #
  36. assert_equal(0, chop(1, [1, 3, 5]))
  37. assert_equal(1, chop(3, [1, 3, 5]))
  38. assert_equal(2, chop(5, [1, 3, 5]))
  39. assert_equal(-1, chop(0, [1, 3, 5]))
  40. assert_equal(-1, chop(2, [1, 3, 5]))
  41. assert_equal(-1, chop(4, [1, 3, 5]))
  42. assert_equal(-1, chop(6, [1, 3, 5]))
  43. #
  44. assert_equal(0, chop(1, [1, 3, 5, 7]))
  45. assert_equal(1, chop(3, [1, 3, 5, 7]))
  46. assert_equal(2, chop(5, [1, 3, 5, 7]))
  47. assert_equal(3, chop(7, [1, 3, 5, 7]))
  48. assert_equal(-1, chop(0, [1, 3, 5, 7]))
  49. assert_equal(-1, chop(2, [1, 3, 5, 7]))
  50. assert_equal(-1, chop(4, [1, 3, 5, 7]))
  51. assert_equal(-1, chop(6, [1, 3, 5, 7]))
  52. assert_equal(-1, chop(8, [1, 3, 5, 7]))
  53. end
  54.  
  55. end
  56.  
  57. #puts test_chop
Runtime error #stdin #stdout 0.03s 6228KB
stdin
Standard input is empty
stdout
Loaded suite prog
Started
E
Finished in 0.000475 seconds.

  1) Error:
test_chop(TestChop):
NameError: undefined local variable or method `pos' for #<TestChop:0x9fc0ab8>
    prog.rb:18:in `chop'
    prog.rb:33:in `test_chop'

1 tests, 1 assertions, 0 failures, 1 errors, 0 skips

Test run options: --seed 62833