Skip to content

Instantly share code, notes, and snippets.

@daltonhuynh
Created May 21, 2011 21:08
Show Gist options
  • Save daltonhuynh/984905 to your computer and use it in GitHub Desktop.
Save daltonhuynh/984905 to your computer and use it in GitHub Desktop.
Greplin Challenge Problems
class String
def palindrome?
front = 0
back = self.length - 1
while front < back do
return false if self[front] != self[back]
front += 1
back -= 1
end
true
end
end
def longest_palindrome(str)
length = str.length
length.downto(1) do |len|
positions = length - len
(0..positions).each do |start|
substr = str[start, len]
return substr if substr.palindrome?
end
end
nil
end
def is_prime(n)
(2..Math.sqrt(n)).each do |i|
return false if n % i == 0
end
true
end
def prime_fibonacci(n)
prev = 1
cur = 1
while true do
temp = prev
prev = cur
cur += temp
return cur if cur > n && is_prime(cur)
end
end
def sum_divisors(n)
sum = 0
divisor = 2
until n == 1 do
if n % divisor == 0
sum += divisor
# divide by all products of divisor
i = 0
while n % divisor**i == 0 do
n /= divisor
i += 1
end
end
divisor += 1
end
sum
end
# number of subsets in list that fulfill
# sum(list[0..n-2]) == list[n - 1], where
# n is the number of elements.
# precondition: list is sorted
def num_sets(list, pre = [])
count = 0
unless pre.empty?
sum = pre.pop
total = pre.reduce{|t, x| t + x}
pre.push(sum)
count += 1 if total == sum
end
list.each_with_index do |x, i|
count += num_sets(list[i+1..-1], pre + [x])
end
count
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment