Skip to content

Commit b9c1388

Browse files
committed
Day 18: finish ruby solution
1 parent 93f0dde commit b9c1388

File tree

2 files changed

+66
-1
lines changed

2 files changed

+66
-1
lines changed

day18/README.md

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,11 @@ I'll just implement the binary search by rows solution for now.
5656

5757
[Ruby](./searchMatrix2.rb)
5858

59-
## Follow up
59+
## Follow up
60+
61+
I can optimize this approach even further by checking which dimension
62+
is longer (rows or columns) and doing binary search along the larger
63+
valued dimension to maximize efficiency.
64+
65+
I'll update this soluiton once I think of an even more optimal approach.
66+

day18/searchMatrix2.rb

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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

Comments
 (0)