Skip to content

Instantly share code, notes, and snippets.

View nimamehanian's full-sized avatar
🎧
Focused

Nima Mehanian nimamehanian

🎧
Focused
View GitHub Profile
@nimamehanian
nimamehanian / prime.rb
Created March 5, 2013 21:54
A predicate method that determines whether a number is prime. Useful for some of Project Euler's challenges.
class Integer
def prime?
if self.even? && self != 2 ||
self.send(:sum_of_digits_div_by_three?) && self != 3 ||
self.send(:last_two_digits_div_by_four?) ||
self.send(:last_digit_div_by_five?) && self != 5
return false
else
return true
end
@nimamehanian
nimamehanian / countem.rb
Created February 21, 2013 02:38
Display how many times an integer occurs at each index, within a nested array.
def countem(list_of_lists)
occurrences = {}
list_of_lists.each do |inner_list|
inner_list.each_with_index do |integer, index_of_integer|
if occurrences.has_key?("#{integer} @ #{index_of_integer}") == false
# if not there, add it
occurrences["#{integer} @ #{index_of_integer}"] = 1
else
# if there, increment
occurrences["#{integer} @ #{index_of_integer}"] += 1
@nimamehanian
nimamehanian / shuffle_array.rb
Created February 21, 2013 02:32
Shuffle an array's elements, without using Ruby's built-in methods.
class Array
def mixup
length = self.length
while length > 0
length -= 1
break if length == 0
randomIndex = (rand * (length - 1)).floor
self[length], self[randomIndex] = self[randomIndex], self[length]
end
end
@nimamehanian
nimamehanian / reverse_array.rb
Created February 21, 2013 02:31
Reverse the order of an array's elements, without using Ruby's built-in methods.
class Array
def backwards
length = self.length
i = 1
while i != length
i += 1
value = self.slice!(length - i)
self << value
break if self[length - i] == self[0]
end
@nimamehanian
nimamehanian / anagrams.rb
Created February 21, 2013 02:29
Determine whether two strings are anagrams.
def anagrams?(word_one, word_two)
word_one = word_one.split('').sort
word_two = word_two.split('').sort
word_one == word_two ? true : false
end
@nimamehanian
nimamehanian / rpn_calc.rb
Created February 21, 2013 02:28
RPN Calculator
class Rpn
def evaluate(expression)
operators = ['+', '-', '*']
stack = []
symbols = expression.split(' ')
symbols.each do |symbol|
if operators.include?(symbol)
number_two = stack.pop
number_one = stack.pop