English 中文(简体)
如何取取一个阵列并操作每个元素相互对立的元素
原标题:How to take an array and operate each element against each other element
  • 时间:2012-05-26 22:27:44
  •  标签:
  • ruby
  • arrays

这就是我正在做的:

(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

正在发生的情况是, a b 在公式中是可以互换的,所以有两种匹配,因此 puts 得到两次输出。要解决这个问题,我添加了 a>=b ,现在它只能输出一次。但是,如果 a= b 输出两次,那么,如果 a_b it 输出两次。我知道在Im 使用的示例中, a 和 b 总是会不同, 但对我来说这看起来是糟糕的设计。

两个问题:

  1. Ruby有更好的模式吗? 选择一个阵列, 比较自己?

  2. 我怎么能避免它输出两次ways 。我可以设定一个变量,如果在下一个循环开始之前更改,它就会破解。这是这样做的正确方式吗?

最佳回答
#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

编辑以使用一个稍好一点的练习( 每个区块, 第一个和第二个区块用于数组阵列)

问题回答

暂无回答




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签