Here is what I'm doing:
下面是我所做的:
(1..999).each do |a|
(1..999).each do |b|
if Math.sqrt(a**2 + b**2) % 1 == 0 && a + b + Math.sqrt(a**2 + b**2) == 1000 && a >= b
puts a * b * Math.sqrt(a**2 + b**2)
end
end
end
What is happening is that a
and b
are interchangeable in the formulas so there are two matches and thus puts
gets outputted twice. To fix this, I added a >= b
and now it only gets outputted once. But, if a == b
it outputs it twice. I know that a and b will always be different in the example I'm using, but this seems like bad design to me.
现在的情况是a和b在公式中是可以互换的,所以有两个匹配,因此输出两次。为了解决这个问题,我添加了>= b,现在只输出了一次。但是,如果a ==位输出两次。我知道在我使用的例子中a和b总是不同的,但这对我来说似乎是糟糕的设计。
Two questions:
两个问题:
-
Is there a better pattern in Ruby for taking an array and comparing it to it self?
Ruby中是否有更好的模式来获取数组并将其与它自己进行比较?
-
How can I avoid it outputting twice always. I could set a variable that if changed before the start of the next loop would break out. Is that the proper way to do this?
我怎样才能避免它两次被输出。我可以设置一个变量,如果在下一个循环开始之前发生了变化。这样做合适吗?
1 个解决方案
#1
5
#using combination
(1..999).to_a.combination(2).each do |low, high|
if Math.sqrt(low**2 + high**2) % 1 == 0 && low + hight + Math.sqrt(low**2 + high**2) == 1000
puts low * high * Math.sqrt(low**2 + high**2)
end
end
Edited to use a little better practice (each block with first and second for arrays of arrays)
编辑后使用了一个更好的实践(数组数组的每个块都有1和2)
#1
5
#using combination
(1..999).to_a.combination(2).each do |low, high|
if Math.sqrt(low**2 + high**2) % 1 == 0 && low + hight + Math.sqrt(low**2 + high**2) == 1000
puts low * high * Math.sqrt(low**2 + high**2)
end
end
Edited to use a little better practice (each block with first and second for arrays of arrays)
编辑后使用了一个更好的实践(数组数组的每个块都有1和2)