Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Ruby has some built-in methods that make this pretty easy:</p> <pre><code>def has_zero_sum_pair?(a) a.permutation(2).any?{|pair| pair.inject(:+) == 0} end </code></pre> <p><code>a.permutation(2)</code> gives you every pair in <code>a</code>. <code>any?</code> returns <code>true</code> if the block ever returns <code>true</code>. <code>inject(:+)</code> is an easy way to get the sum of an array.</p> <pre><code>has_zero_sum_pair?([1, 2, 3]) # =&gt; false has_zero_sum_pair?([1, 2, 3, -2]) # =&gt; true has_zero_sum_pair?([1, 2, 3, 0]) # =&gt; false has_zero_sum_pair?([0, 1, 2, 3, 0]) # =&gt; true </code></pre> <p><strong>Update:</strong> If I didn't know about <a href="http://ruby-doc.org/core-2.0/Array.html#method-i-permutation" rel="nofollow">Array#permutation</a> and had to accomplish this in the first way that came to mind, or if I was concerned about performance, I'd probably do something like this:</p> <pre><code>def has_zero_sum_pair2?(a) (0..a.length-2).each do |i| (i+1..a.length-1).each do |j| return true if a[i] + a[j] == 0 end end false end </code></pre> <p>I find that uglier and more error-prone, and it took longer to write. But it's about four times faster with small arrays and 10 times faster for larger arrays. It's typical in programming to have an easy way that works well enough in most cases but isn't ideal in performance. Sometimes better performance can be attained without costing clarity by choosing a better algorithm or data structure. Often a trade-off has to be made.</p> <p><strong>Update 2:</strong> If I really cared about performance, I'd use @FMc's technique. That's a great example of using a better data structure and algorithm for huge performance gains.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload