7/14/20 practice problems Flashcards
1
Q
Nested Sum
Define a method, #nested_sum, that takes a 2d_array and returns the sum of all nested elements
A
def nested_sum(matrix) sum = 0 matrix.each do |med| #slow loop med.each do |fast| # med loop sum += fast end end
return sum
end my_matrix = [ [1, 2], [3, 4] ] p nested_sum(my_matrix) # => 10
2
Q
# Define a method, #pair_product?, that accepts two arguments: an array of # integers and a target_product (an integer). The method returns a boolean # indicating whether any pair of elements in the array multiplied together equals # that product. You cannot multiply an element by itself. An element on its # own is not a product.
A
def pair_product?(arr, target_product)
pairs = [] arr.each_with_index do |num1, idx1| arr.each_with_index do |num2, idx2| if idx2 > idx1 && num1 * num2 == target_product pairs << [num1, num2] print pairs puts return true end end end
return false
end
p pair_product?([3, 1, 6], 15) # => false
p pair_product?([3, 1, 6], 9) # => false
p pair_product?([3, 1, 6], 18) # => true
p pair_product?([3, 5, 6], 15) # => false
p pair_product?([3, 5, 6], 30) # => false
p pair_product?([3, 5, 6], 17) # => true
3
Q
given a string, return all possible substrings
A
# def substrings(str) # end # p substring("abc")
4
Q
given a string, return the longest substring that is the same forwards and backwards (minimum length 3)
A
# def longest_palindrome(str) # end # p longest_palindrome("abracadabra") # => "aca" # p longest_palindrome("i sleep in a racecar bed") # => " racecar "
5
Q
# given a gap, return the the first pair of contiguous primes with that gap between them # primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29...
A
# primes: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29... # def prime_gap(gap) # end # p prime_gap(2) # => [3, 5] # p prime_gap(4) # => [7, 11] # p prime_gap(6) # => [23, 29]