如何循环一组数字,进行一些加法并附加到数组?
我的目标是创建一个数组,其中包含一组骰子上 2 个数字的每个组合的总和。我正在创建一个循环的开头,在执行 die1[1] + die2[ 之前将
等等。die1[0]
添加到 die2[0..5]
0..5]
我有下面的代码,但我做错了。我希望能够调用数组中的特定数字,例如 dieSums[4]
,并获取一个数字。知道我在这里做错了什么吗?
die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]
dieSums = []
count = 0
while count <= 5 do
dieSums << die1[0] + die2[count]
count += 1
puts dieSums[5]
end
My goal here is to create an array with the sum totals of every combination of 2 numbers on a set of dice. I'm creating the beginning of a loop that adds die1[0]
to die2[0..5]
before going through die1[1] + die2[0..5]
and so on.
I've got this code below and I'm doing something wrong. I want to be able to call specific numbers in the array, such as dieSums[4]
, and get one number. Any idea what i'm doing incorrectly here?
die1 = [1,2,3,4,5,6]
die2 = [1,2,3,4,5,6]
dieSums = []
count = 0
while count <= 5 do
dieSums << die1[0] + die2[count]
count += 1
puts dieSums[5]
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如您所编写的,
while
循环并不是很 Rubyonic。 (Rubinic?)一种更惯用的迭代数组元素的方法:当然,在这种情况下,
die1
和die2
是相同的,因此您可以替换die2
与die1
就可以了。A
while
loop, as you've written it, isn't very Rubyonic. (Rubinic?) A more idiomatic way to iterate over the elements of an array:Of course,
die1
anddie2
are identical in this case, so you could replacedie2
withdie1
and it'd all work out.您正在循环内调用
puts dieSums[5]
。dieSums[5]
在最后一次迭代之前不会存在。如果你在循环之外调用它,它就会起作用:You are calling
puts dieSums[5]
inside the loop.dieSums[5]
won't exist until the last iteration. It'll work if you call it outside the loop:附带说明:请注意,您的问题过于复杂化(因为您以命令式的方式思考,请查看 函数式编程)。两个骰子的所有可能值的总和:
uniq
。repeated_combination(2)
而不是product
。die.repeated_permutation(2)
)查找 N 个骰子的所有总和几乎同样简单:
As a side note: notice that you are over-complicating the problem (because you think in imperative terms, take a look at Functional programming). The sum of all possible values for two dice:
uniq
at the end if you don't want repeated values.repeated_combination(2)
instead ofproduct
if you don't care about the order.die.product(die)
=die.repeated_permutation(2)
)Finding all the sums for N dice is almost as simple: