This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# factorial method | |
def fact(n) | |
(1..n).reduce(:*) | |
end | |
# binomial theorem, n choose k | |
def binomial(n,k) | |
return 1 if n-k <= 0 | |
return 1 if k <= 0 | |
fact(n) / ( fact(k) * fact( n - k ) ) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# recursive 'de Casteljau' method. The method multiplies the array's elements in pairs (1st * 2nd, 2nd * 3rd, 3rd * 4th, etc.). Output array is one element less than input array. | |
# test_ary = [7, 17, 23, 47, 61] | |
def rec(ary) | |
if ary.length == 2 then | |
# base case | |
return [ ary[0] * ary[1] ] | |
else | |
# recursive case |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# 2011-10-10 20:57:53 +1000 | |
def merge_sort(a) | |
return a if a.size <= 1 | |
l, r = split_array(a) | |
result = combine(merge_sort(l), merge_sort(r)) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby Array's "-" (minus) method removes elements from the receiver which exist in the parameter Array | |
[5, 6, 1] - [2, 3, 5] | |
# => [6, 1] | |
# this #subtract method will subtract the value of the parameter Array from the value of the receiver Array, defined by the actual index. | |
# type mismatch, Nil, and different Array length are not handled | |
class Array |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Enumerator based Logistic map, can be used as a PRNG as well. | |
def logistic_map(x0, r) | |
return Enumerator.new do |yielder| | |
number = x0.to_f | |
r = r.to_f | |
loop do | |
yielder.yield(number) | |
number = r * number * (1 - number) | |
end |