Skip to content

Instantly share code, notes, and snippets.

View dustinbrownman's full-sized avatar

Dustin Brown dustinbrownman

View GitHub Profile
@dustinbrownman
dustinbrownman / wordy_calculator.rb
Last active December 21, 2015 23:09
Takes an english math expression (e.g. What is 4 plus 2?), and returns the result. Assumes order of operations are those that the user inputs.
class Calculator
def phrase_cleaner(phrase)
operands = phrase.match(/([0-9,-]+.*[\w])/)[0]
end
def number_filter(phrase)
numbers = phrase.scan(/[0-9,-]+/)
numbers.map { |number| number.to_i }
end
@dustinbrownman
dustinbrownman / sieve.rb
Last active December 21, 2015 23:09
Returns all the primes between 2 (the first prime) and a given number using the sieve of Eratosthenes
def sieve(number)
if number < 2
raise TypeError.new("Must be a number greater than 2")
end
primes =* (2..number)
primes.each do |prime|
primes.reject! do |number|
prime != number && number % prime == 0
end
end
@dustinbrownman
dustinbrownman / largest_series_product.rb
Last active December 21, 2015 23:09
Returns the highest product from a string of numbers for the given series length (defaulted to 3). For example, the string "123456789" with a series length of 3 returns 504 (7 * 8 * 9). If I adjust the series length to 4, it returns 3024 (6 * 7 * 8 * 9).
def largest_series_product(number, span_length=3)
if number.match(/\D/)
raise ArgumentError.new("Numbers only")
elsif number.length < span_length
raise ArgumentError.new("The number must have at least #{span_length} digits")
end
product_finder(series_splitter(number, span_length)).max
end
def series_splitter(number, span_length)
@dustinbrownman
dustinbrownman / binary.rb
Created August 29, 2013 16:26
Converts a binary (or trinary) number string to decimal. There's only one character difference between the two functions (besides the exceptions).
def binary(binary_string)
if !(binary_string.is_a?(String)) || binary_string.match(/[^0,1]/)
raise TypeError.new("Input must be only 0s and 1s")
end
total = 0
binary_string.reverse.split("").each_with_index do |bit, index|
total += bit.to_i * 2 ** index
end
total
@dustinbrownman
dustinbrownman / anagram.rb
Created August 29, 2013 16:22
Expects a word and an array of possible anagrams of that word. Returns an array of all true anagrams.
def anagrams(word, possible_anagrams)
unless possible_anagrams.is_a?(Array) || possible_anagrams.all? { |anagram| anagram.is_a?(String) }
raise TypeError.new("The possible anagrams must be an array")
end
possible_anagrams.find_all do |anagram|
word.chars.sort == anagram.chars.sort
end
end