Created
June 9, 2015 14:02
-
-
Save teknocat/ec8b4140ad19819bf2ea to your computer and use it in GitHub Desktop.
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
# http://www.softantenna.com/wp/software/5-programming-problems/ | |
# https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour | |
# | |
# 問題1 | |
# forループ、whileループ、および再帰を使用して、リスト内の数字の合計を計算する3つの関数を記述せよ。 | |
@list = [ 1, 7, 3, 12, 5, 8 ].freeze | |
# @param [Array] list | |
def funcX(list) | |
list.reduce {|result, num| | |
result + num | |
} | |
end | |
# @param [Array] list | |
def funcX2(list) | |
list.reduce(:+) | |
end | |
# @param [Array] list | |
def func1(list) | |
result = 0 | |
for num in list | |
result += num | |
end | |
result | |
end | |
# @param [Array] list | |
def func2(list) | |
result = 0 | |
while !list.empty? do | |
result += list.shift | |
end | |
result | |
end | |
# @param [Array] list | |
def func3(list) | |
return 0 if list.empty? | |
list.shift + func3(list) | |
end | |
p "funcX = #{funcX(@list)}" | |
p "funcX2 = #{funcX2(@list)}" | |
p "func1 = #{func1(@list)}" | |
p "func2 = #{func2(@list.dup)}" | |
p "func3 = #{func3(@list.dup)}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment