In Ruby, I would like to take an array of numbers, select 2 different numbers, add those 2 numbers together and see weather there equal to a variable x.y'd a variable x. Here is the code I used
def arrayIsEqual? (numArray, x)
return true if numArray.sample + numArray.sample == x
return false if numArray.empty? || numArray.count == 1
end
for example
numArray = [4,2,7,5]
x = 11
arrayIsEqual (numArray, n)
should return true
, since 4 + 7 = n(11)
How do I get this to work?
I don't want it to be 2 random numbers, just any 2 different numbers that add up to n
Use lowercase and underscores for variables in Ruby. The convention is different here than in some other languages.
It looks like you're trying to see if there are any two numbers in the array that add up to the specified value
x
. However, your code just picks two numbers at random and checks if those numbers add up.Ruby has the
Array#combination
method, which generates all combinations of a given length:A few things to note:
First, we named it according to Ruby conventions: each word is
separated_by_underscores
. The?
on the end means that the method is a predicate method and returns a true or false value.Inside the method, a few things happen. Let's look at that line, piece by piece.
arr
: We take the array that was passed in.<...>.uniq
: We only look at the unique elements (because the OP wants to pick two different numbers).<...>.combination(2)
: We ask for all combinations from the array of length 2. If the array was[4, 5, 6]
, we'd get[[4, 5], [4, 6], [5, 6]]
.<...>.detect { |a, b| a + b == n }
: We look for the first combination that adds up ton
. If we found one, that's the result of that method. Otherwise, we getnil
.!!<...>
: Finally, we take the result we got fromdetect
and negate it twice. The first negation produces a Boolean value (true
if the value we got wasnil
, orfalse
if it's anything else); the second negation produces a Boolean value that's identical to the truth value of the first negation. This is a Ruby idiom to coerce a result into being eithertrue
orfalse
.Let's see it in action:
I understand that your question is "is there any pair of numbers in my array equals x", in which case this will do what you need:
This checks all sums of pairs of numbers in the array, and checks if their sum is
x
.sample
randomly picks an item from the array, which means that what your code does is "return true sometimes if there is a pair of numbers in my array equals x"One liner
And as a function
Updated: Added each_with_index to avoid self inclusion on checks. It's a lot longer now :-/
Just iterate over it once and use the target number to see if it matches. 100 times faster then most of the answers here