Skip to content

Commit dce9bd9

Browse files
authored
Merge pull request kelvins#320 from davide-almeida/min_max_dc_ruby
Add min max divide and conquer in Ruby
2 parents 7092b0e + 9b313ad commit dce9bd9

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -1310,8 +1310,8 @@ In order to achieve greater coverage and encourage more people to contribute to
13101310
</a>
13111311
</td>
13121312
<td> <!-- Ruby -->
1313-
<a href="./CONTRIBUTING.md">
1314-
<img align="center" height="25" src="./logos/github.svg" />
1313+
<a href="./src/ruby/min_max_dc.rb">
1314+
<img align="center" height="25" src="./logos/ruby.svg" />
13151315
</a>
13161316
</td>
13171317
<td> <!-- JavaScript -->

src/ruby/min_max_dc.rb

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# frozen_string_literal: true
2+
3+
require "test/unit/assertions"
4+
include Test::Unit::Assertions
5+
6+
def min_max_dc(vector, start_index, end_index)
7+
if start_index == end_index
8+
return [vector[start_index], vector[start_index]]
9+
end
10+
11+
middle = (start_index + end_index) / 2
12+
left_min, left_max = min_max_dc(vector, start_index, middle)
13+
right_min, right_max = min_max_dc(vector, middle + 1, end_index)
14+
15+
min = left_min < right_min ? left_min : right_min
16+
max = left_max > right_max ? left_max : right_max
17+
18+
[min, max]
19+
end
20+
21+
assert_equal([1, 5], min_max_dc([1, 2, 3, 4, 5], 0, 4))
22+
assert_equal([14, 55], min_max_dc([13, 55, 42, 14, 15], 1, 3))
23+
assert_equal([13, 13], min_max_dc([13, 55, 42, 14, 15], 0, 0))
24+
assert_equal([14, 15], min_max_dc([13, 55, 42, 14, 15], 3, 4))

0 commit comments

Comments
 (0)