Skip to content

Instantly share code, notes, and snippets.

# 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
# 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
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
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
# 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
# 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 = ''
# 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"
@KevinSia
KevinSia / shuffle.rb
Last active September 21, 2017 07:50
# Fisher-Yates shuffle
# the wiki shows two examples
# https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
# pencil-and-paper method
# 1. Duplicate the array and shuffle the duplicate instead (we call the duplicate `input_array`)
# 2. Generate a random number between 0 and (length of the array - 1) (we call the number `random_position`)
# 3. Take an element at position `random_position` in the `input_array`, and put into another array
# 4. Repeat 2-3 until `input_array` has nothing left
# Your code here to sort the array
def dictionary_sort(array)
return if array.length <= 1
array.sort { |word1, word2| word1.downcase <=> word2.downcase }
end
# writing `array.sort` is equivalent to writing `array.sort { |i, j| i <=> j }`
# .sort decides which item should be in the front by doing `<=> on each pair of items
# if the block gives -1, i goes to the front and j goes to the back
# if the block gives 1, j goes to the front and i goes to the back
def canonical(word)
word.downcase.chars.sort
end
def is_anagram?(word1, word2)
canonical(word1) == canonical(word2)
end
puts "One word"
word1 = gets.chomp