Last active
October 1, 2018 15:08
-
-
Save yurko/232f0a5786afda4f408eead82ffc3584 to your computer and use it in GitHub Desktop.
algos jff
This file contains 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
def anagram? a, b | |
counts = ->(word) { word.each_char.with_object(Hash.new(0)) { |c, h| h[c] += 1 unless c =~ /\s/} } | |
counts[a] == counts[b] | |
end |
This file contains 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
def factorial n | |
fac_times = ->(n, acc) { n == 0 ? acc : fac_times.(n - 1, acc * n) } | |
fac_times.(n, 1) | |
end |
This file contains 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
fibo = ->(n) { Enumerator.new { |y, a=[0,1]| loop { y << a[-1]; a << a[-2..-1].reduce(:+) } }.take n } | |
fibo[10] | |
def fibonacci | |
# Enumerator.new { |y, a=1, b=1| loop { y << a; a, b = b, a + b } } | |
Enumerator.new { |y, a=[0,1]| loop { y << a[-1]; a << a[-2..-1].reduce(:+) } } | |
end | |
fibonacci.lazy.select(&:even?).first 10 | |
# using Hash | |
fib = Hash.new {|h, k| h[k] = k < 3 ? 1 : h[k-1] + h[k-2]} | |
# https://blog.arkency.com/2014/07/hidden-features-of-ruby-you-may-dont-know-about/ | |
fibbonacci = Hash.new do |accumulator, index| | |
accumulator[index] = fibbonacci[index - 2] + fibbonacci[index - 1] | |
end.update(0 => 0, 1 => 1) |
This file contains 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
def sleep_sort arr | |
[].tap do |sorted| | |
arr.map { |el| Thread.new { sleep el; sorted << el } }.each(&:join) | |
end | |
end | |
sleep_sort Array.new(10) { rand(10) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment