Skip to content

Instantly share code, notes, and snippets.

@mattdvhope
mattdvhope / gist:6400511
Created August 31, 2013 20:42
recursive_methods.rb
def choose_team(n,k)
return 0 if n == 0
return n if k == 1
choose_team(n-1, k-1) + choose_team(n-1, k)
end
p choose_team(24, 4) # pairs
@mattdvhope
mattdvhope / gist:6254850
Created August 17, 2013 01:44
Exercises 9, 10, 11 on Assessment
# EXERCISE 9
# My plain English answer:
# 1. Create a method for sorting the numbers in order from 1 to 10,000 (w/o the missing number).
# 2. Create a code block for comparing the value each successive number with its previous number.
# If their difference is greater than 1, then I'll subtract the previous number from the subsequent number. Then I'll add 1 to that previous number: that sum equals/is the missing number.
# Output the missing number.
# CODE...
def find_missing(no_order)
ordered_missing = no_order.sort
ordered_include = [*(1..10000)]
@mattdvhope
mattdvhope / gist:6216031
Last active December 20, 2015 23:58
Reverse Polish notation calculator
class RPNCalculator
def evaluate(values_and_operator)
@array = (values_and_operator).split(' ')
if @array.length == 1
return @array.pop.to_i
end
while true
@array.each_with_index do |element, i|
if element == "+"
@mattdvhope
mattdvhope / gist:6085474
Created July 26, 2013 02:03
GuessingGame working in my Terminal, but not working in Socrates. I looked through the Specs, but could not find anything wrong.
class GuessingGame
def initialize(guess)
@guess = guess
end
def guess(last_guess) # passing from last_guess = gets.chomp
@last_guess = last_guess
if @last_guess > @guess
return :high
elsif @last_guess < @guess
@mattdvhope
mattdvhope / gist:6066483
Last active December 20, 2015 03:49
Calculating the array mode
def mode(array)
# I created a new hash to make keys out each integer.
b = Hash.new(0)
# Here, I count/tabulate each time a particular integer appears.
array.each do |value|
b[value] = b[value] + 1
end
# b returns {-2=>1, 1=>3, 2=>3, -5=>2, 3=>1, 4=>1} with the first array
@mattdvhope
mattdvhope / gist:6043860
Last active December 20, 2015 00:39
Socrates - Calculating the median of an array of numbers
Median of an array of numbers
def median(array)
if array.length.even?
return (array[((array.length / 2) - 1)].to_f + array[array.length / 2].to_f) / 2
else
return array[array.length / 2]
end
end
array1 = [1, 2, 3, 4, 5, 5, 7]