Last active
July 31, 2016 10:08
-
-
Save marekdano/6b61c67c75d9048dfbdcf91e1a90e1ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############################################################################################# | |
# Write a function fib() that a takes an integer "n" and returns the n-th fibonacci number | |
# fib(0) # => 0 | |
# fib(1) # => 1 | |
# fib(2) # => 1 | |
# fib(3) # => 2 | |
# fib(4) # => 3 | |
# ... | |
def fib(n) | |
# write the body of your function here | |
if n<=2 | |
return 1 | |
else | |
return fib(n-1) + fib(n-2) | |
end | |
end | |
# run your function through some test cases here | |
puts fib(1) | |
puts fib(2) | |
puts fib(3) | |
puts fib(4) | |
#################################################################################### | |
# Calculate factorial n | |
puts (1..n).inject(1,:*) | |
# Resursively | |
def factorial(n) | |
return 1 if n <= 1 | |
n * factorial(n-1) | |
end | |
puts factorial(num) | |
# or this short method in javascript | |
let fact = (n) => { return n>0 ? n*fact(n-1) : 1 } | |
console.log(fact(3)) | |
#################################################################################### | |
# FizzBuzz | |
# Print a string FizzBuzz if a number is devided by 3 and 5. | |
# Print Fizz if is devided by 3, prind Buzz if is devided by 5 or just a number | |
n = 100 | |
(1..n).each do |n| | |
puts n%15==0 ? "FizzBuzz" : n%3==0 ? "Fizz" : n%5==0 ? "Buzz" : n | |
end | |
#################################################################################### | |
# Write a function that sorts the keys in a hash by the length of the key as a string. For instance, the hash: | |
# | |
# { abc: 'hello', 'another_key' => 123, 4567 => 'third' } | |
# should result in: | |
# | |
# ["abc", "4567", "another_key"] | |
hsh = { abc: 'hello', 'another_key' => 123, 4567 => 'third' } | |
#The same as hsh.keys.map{ |key| key.to_s }.sort_by{ |key| key.length } | |
p hsh.keys.map(&:to_s).sort_by(&:length) | |
#################################################################################### | |
# Write a single line of Ruby code that prints the Fibonacci sequence of any length as an array. | |
(1..20).inject( [0, 1] ) { | fib | fib << fib.last(2).inject(:+) } | |
#################################################################################### | |
# Extract substring from a string | |
a = "hello there" | |
a[1] #=> "e" | |
a[2, 3] #=> "llo" | |
a[2..3] #=> "ll" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment