Skip to content

Instantly share code, notes, and snippets.

@lithtle
Created May 25, 2015 08:56
Show Gist options
  • Save lithtle/9203791872bc8c37989b to your computer and use it in GitHub Desktop.
Save lithtle/9203791872bc8c37989b to your computer and use it in GitHub Desktop.
「Five programming problems every Software Engineer should be able to solve in less than 1 hour」をrubyで解いてみた
# encoding: sjis
# 1
# using for
def sum_for(list)
sum = 0
for i in list
sum += i
end
sum
end
# using while
def sum_while(list)
sum = 0
i = 0
while i < list.length
sum += list[i]
i += 1
end
sum
end
# using recursive call
def sum_rec(list, sum=0)
return sum if list.empty?
head = list.shift
sum_rec(list, sum + head)
end
# 2
def my_zip(alist=[], blist=[], result=[])
return result if alist.empty? && blist.empty?
a = alist.shift
b = blist.shift
my_zip(alist, blist, (result << [a, b].compact).flatten)
end
# 3
def fib(n)
case n
when 0
[]
when 1
[0]
else
list = [0, 1]
(n - list.length).times do
list[list.length] = list[-2] + list[-1]
end
list
end
end
# 4
def perm_max(list=[])
list.permutation.collect{ |i| i.map(&:to_s).join }.max.to_i
end
# 5
def comb_100(size=1)
["+", "-", ""]
.repeated_permutation(size - 1)
.to_a
.map{ |e| (1..size).to_a.zip(e).flatten.map(&:to_s).join }
.select{ |e| eval(e) == 100 }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment