【发布时间】:2020-07-07 15:35:10
【问题描述】:
def baubles_on_tree(ornaments, branches)
counter = 0
decorations = []
puts ornaments, branches
# Evenly distribute ornaments across branches
# if there are no branches, return string
if branches == 0
return "Grandma, we will have to buy a Christmas tree first!"
end
puts "The number of ornaments (#{ornaments}) divided by branches (#{branches}) equal " + ((ornaments / branches).to_f).to_s
# add 1 to the decorations array while counter <= ornaments.
# ensure decoration.length maxes out at branches
while counter <= ornaments
# Add 1 to counter until it reaches the number of ornaments
counter += 1
#puts decorations.length
# Push 1 to the decorations array for each iteration
decorations << 1
# if the decorations array length equals the number of branches,
# stop creating new indices and instead add 1 to each array element
if decorations.length == branches
print decorations.length
decorations.map! {|n| n + 1 }
end
end
print decorations
end
Test.describe("Here are some test cases") do
Test.assert_equals(baubles_on_tree(5,5),[1,1,1,1,1])
Test.assert_equals(baubles_on_tree(5,0),"Grandma, we will have to buy a Christmas tree first!")
Test.assert_equals(baubles_on_tree(6,5),[2,1,1,1,1])
Test.assert_equals(baubles_on_tree(50,9),[6,6,6,6,6,5,5,5,5])
Test.assert_equals(baubles_on_tree(0,10),[0,0,0,0,0,0,0,0,0,0])
end
问题:大家好。我很难找到在 if decors.length == branches 块中使用的正确语法。目前,
decorations.map! {|n| n + 1 }
在每次迭代的装饰数组中的每个元素上加 1。相反,我想将 1 添加到单个数组元素(从左到右),直到计数器等于装饰品的数量。
目标:bables_on_tree 函数的最终目标是将装饰品均匀地分布在圣诞树的所有分支上。如果饰品=7,分支=5,则返回的数组为[2,2,1,1,1]。
感谢您的指导!
【问题讨论】:
标签: arrays ruby conditional-statements