1+ def searchMatrix ( matrix , target )
2+ # the downside to this is that I do a binary search
3+ # on every row before I return
4+ return matrix . map { |row | binarySearch ( row , target ) } . any? { |result | result == true }
5+ end
6+
7+ ###########
8+ # Helpers #
9+ ###########
10+
11+ def binarySearch ( row , target )
12+ low , high = 0 , row . size
13+
14+ while low < high
15+ mid = ( low + high ) / 2
16+ if row [ mid ] == target
17+ return true
18+ elsif target > row [ mid ]
19+ low = mid + 1
20+ else
21+ high = mid
22+ end
23+ end
24+
25+ return false
26+ end
27+
28+ #########
29+ # Tests #
30+ #########
31+
32+ class AssertionError < RuntimeError
33+ end
34+
35+ def assert &block
36+ raise AssertionError unless yield
37+ end
38+
39+ def tests
40+ matrix = [ [ 1 , 2 , 3 ] ,
41+ [ 4 , 5 , 6 ] ,
42+ [ 7 , 8 , 9 ] ]
43+ assert { searchMatrix ( matrix , 1 ) }
44+ assert { searchMatrix ( matrix , 2 ) }
45+ assert { searchMatrix ( matrix , 5 ) }
46+ assert { searchMatrix ( matrix , 6 ) }
47+ assert { searchMatrix ( matrix , 8 ) }
48+ assert { searchMatrix ( matrix , 9 ) }
49+
50+ assert { searchMatrix ( [ [ ] ] , 0 ) == false }
51+ assert { searchMatrix ( [ [ 0 ] ] , 1 ) == false }
52+ assert { searchMatrix ( [ [ 1 , 2 ] ] , 0 ) == false }
53+ assert { searchMatrix ( [ [ 1 ] , [ 2 ] , [ 3 ] ] , 0 ) == false }
54+ assert { searchMatrix ( [ [ 1 ] , [ 2 ] , [ 3 ] ] , 1 ) == true }
55+ assert { searchMatrix ( [ [ 1 ] , [ 2 ] , [ 3 ] ] , 3 ) == true }
56+ end
57+
58+ tests ( )
0 commit comments