code for chapter 4 in ruby

This commit is contained in:
Leon Rische
2016-03-03 15:34:16 +01:00
parent 0aa3c5efc7
commit 33d432bdaf
5 changed files with 45 additions and 0 deletions

View File

@@ -0,0 +1,10 @@
def sum(arr)
total = 0
arr.each do |x|
total += x
end
total
end
puts sum([1, 2, 3, 4])

View File

@@ -0,0 +1,4 @@
def sum(list)
return 0 if list.empty?
list[0] + sum(list[1..-1])
end

View File

@@ -0,0 +1,4 @@
def count(list)
return 0 if list.empty?
1 + count(list[1..-1])
end

View File

@@ -0,0 +1,9 @@
def max(list)
if list.length == 2
# condition ? then : else
list[0] > list[1] ? list[0] : list[1]
else
sub_max = max(list[1..-1])
list[0] > sub_max ? list[0] : sub_max
end
end

View File

@@ -0,0 +1,18 @@
def quicksort(array)
if array.length < 2
# base case, arrays with 0 or 1 element are already "sorted"
array
else
# recursive case
pivot = array[0]
# sub-array of all the elements less than the pivot
rest = array[1..-1]
less = rest.select { |i| i <= pivot }
# sub-array of all the elements greater than the pivot
greater = rest.select { |i| i > pivot }
quicksort(less) + [pivot] + quicksort(greater)
end
end
print quicksort([10, 5, 2, 3])