Skip to content

Instantly share code, notes, and snippets.

# Determine whether a string contains a Social Security number.
def has_ssn?(string)
!!string.match(/(\d{3})-(\d{2})-(\d{4})/)
end
puts "has_ssn? returns true if it has what looks like a SSN"
puts has_ssn?("please don't share this: 234-60-1422") == true
puts "has_ssn? returns false if it doesn't have a SSN"
# Fill in the methods below with your solution.
# Do not change the method names
# Iteration 1: Converting one word to Pig Latin
def convert_word_to_pig_latin(word)
if word[0].downcase == 'a' || word[0].downcase == 'e' || word[0].downcase == 'i' || word[0].downcase == 'o' || word[0].downcase == 'u'
word
else
str_front = ''
# TODO: Refactor for elegance
def shout_backwards(string)
# before:
# all_caps = string.upcase
# backwards = all_caps.reverse
# result = backwards + "!!!!"
# return result
string.upcase.reverse + "!!!!"
end
def prime_factors(num)
return [num] if num <= 1
result = []
until num == 1
for i in (2..num)
if num % i == 0
result << i
num /= i
break
def linear_search(target, arr)
for i in 0...arr.length
return i if target == arr[i]
end
return nil
end
def global_linear_search(target, arr)
indices = []
for i in 0...arr.length
# Place your solutions here
# Implement a method named binary_search
def binary_search(target, arr)
s = 0
e = arr.length - 1
until s < e
m = (s + e) / 2
# found target
if target == arr[m]
return m
# Implement an iterative version of the factorial function
def factorial_iterative(n)
return n if n <= 1
total = 1
n.downto(1) { |i| total *= i }
return total
end
# def factorial_iterative(n)
# return n if n <= 1
# OLD SOLUTION
# def fibonacci_iterative(n)
# if n <= 1
# return n
# else
# arr = [0, 1]
# index = 0
# (n - 1).times do
# # arr might get very big if n is a big number
# arr << arr[index] + arr[index + 1]
# generates a tic tac toe array with the right ratio of 'x' and 'o'
def generate_realistic_tic_tac_toe
# hardcode 4 'X's and 4 'O's, then pick one on random from ['X', 'O']
one_d = (%w(X X X X O O O O) << %w(X O).sample).shuffle
return one_d.each_slice(3).to_a
end
# turns the array of players into array of hashes
def convert_roster_format(roster)
header = roster.shift