Skip to content

Instantly share code, notes, and snippets.

@Stephenitis
Created March 28, 2013 20:21
Show Gist options
  • Save Stephenitis/5266464 to your computer and use it in GitHub Desktop.
Save Stephenitis/5266464 to your computer and use it in GitHub Desktop.
recursion kitchen sink
# #How many different ways are there to flip a fair coin 5 times and not have three or more heads in a row?
# def combination(length=5)
# return [[]] if length == 0
# combination(length-1).collect {|c| [:h] + c } +
# combination(length-1).collect {|c| [:t] + c }
# end
# combination
# puts "*There are #{combination.length} ways"
# puts combination.inspect
# recursive function
# Trace the computation of f(9) by drawing a recursion tree (like the one we drew for Fibonacci numbers), showing all of the recursive computations that need to be computed to find the value for f(9). Then using your recursion tree, compute the value of f(9).
# def f(n)
# if n == 0 or n == 1 or n == 2
# n
# else
# f(n-3) + f(n/3)
# end
# end
# f(12)
# =>6
#f(9)
# => 4
# Recursion test
# (1 pt) Write a recursive Ruby function sum_positive(n) that has one parameter n that represents a positive integer. The function should return the sum of the first n positive integers. Your solution must use recursion and should not have a loop in it.
# For example, if we call sum_positive(5), then the function should return the value 15 since 1 + 2 + 3 + 4 + 5 = 15.
# def sum_positive(num)
# return num if num.zero?
# num + sum_positive(num-1)
# end
# sum_positive(9)
# #Recursive Countdown
# def countdown(n)
# return "done" if n.zero? # base case
# puts n
# countdown(n-1) # getting closer to base case
# end #=> nil
# countdown(5) #=> nil
#merge sort algorithm
[16, 26, 55, 13, 21, 26, 31, 44]
1
2
3
4
5
6
7
8
9
10
11
12
def combination(length=5)
return [[]] if length == 0
combination(length-1).collect {|c|[:h] + c } +
combination(length-1).collect {|c|[:t] + c }
end
combination 3
print "*There are #{combination.length} ways"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment