Write a method that returns b^n recursively. Your solution should accept
negative values for n.
def exponent(b, n)
return 1 if n == 0
if n > 0
b * exponent(b, n-1)
else
1.0 / (b * exponent(b, n.abs-1))
end
endWrite a function anagrams(str1, str2) that takes in two words and returns a boolean indicating whether or not the words are anagrams. Anagrams are words that contain the same characters but not necessarily in the same order.
Solve this without using Array#sort or Array#sort_by.
Write a method, pow(base, exponent), that takes in two numbers. The method should calculate the base raised to the exponent power. You can assume the exponent is always positive.
Solve this recursively!
def pow(base, exponent)
return 1 if exponent == 0
return base if exponent == 1base * pow(base, exponent-1)
end
How can you change the puts output?
Puts changes everything to a string. So you can monkey patch and override to “to_s” method name.
Write a hash_my_each that takes in a proc and does not use hash#each, hash#map or hash#each_with_index.
def my_each(&prc)
i = 0
key_arr = self.keys
while i < key_arr.length
prc.call(key_arr[i], self[key_arr[i]])
i += 1
end
self
endWrite an Array#my_inject method. If my_inject receives no argument, then use the first element of the array as the default accumulator.
**Do NOT use the built-in Array#inject orArray#reduce methods in your implementation.
def my_inject(accumulator = nil, &prc)
arr = self.dup if accumulator == nil accumulator = arr[0] arr.shift end
arr.each do |e|
debugger
accumulator = prc.call(accumulator, e)
end
accumulatorend
end
Define a method Array#my_zip(*arrays) that merges elements from the receiver with the corresponding elements from each provided argument. You CANNOT use Ruby’s built-in Array#zip method
def my_zip(*arrays)
merged = [self, *arrays]
col = merged.map(&:length).max
row = merged.lengthresult = Array.new(col) { Array.new(row) }
(0...merged.length).each do |i1|
(0...merged[0].length).each do |i2|
result[i2][i1] = merged[i1][i2]
end
end
result endWrite an Array#my_controlled_flatten(n) method that only flattens n levels of an array. For example, if you have an array with 3 levels of nested arrays, and run arr.my_flatten(1), you should return an array with 1 level of nested arrays flattened.
def my_controlled_flatten(n)
result = []
self.each do |e|
if e.is_a?(Array) && n != 0
result += e.my_controlled_flatten(n-1)
else
result << e
end
endresult end end
Find all the fibonacci numbers up to and including the nth using recursive
What about with memoization? What does memoization do?
def all_fibs(n) return [ ] if n == 0 return [0] if n == 1 return [0, 1] if n == 2 all_fibs(n-1) << all_fibs(n-1)[-1] + all_fibs(n-1)[-2] end
_________________
With memoization, calls on the method less and runs way faster
def all_fibs(n) return [ ] if n == 0 return [0] if n == 1 return [0, 1] if n == 2 prev_call = all_fibs(n-1) prev_call << prev_call[-1] + prev_call[-2] end