1

I have this function:

def find_deleted_number(arr, mixed_arr)

    default = 0

    arr.each do |i|
        if mixed_arr.include?(arr[i]) == true
            default += arr[i]
        else 
            return arr[i]
        end
    end
    return default  
end

find_deleted_number([1,2,3,4,5], [3,4,1,5])
#=> 2 (as expected)

find_deleted_number([1,2,3,4,5,6,7,8,9], [1,9,7,4,6,2,3,8])
#=> 5 (as expected)

find_deleted_number([1,2,3,4,5,6,7,8,9], [5,7,6,9,4,8,1,2,3])
#=> nil (expected 45)

The idea is for the function to check which number is in arr but not in mixed_arr. That's all good but the problem is that when both arrays are the same, I want it to give me the sum of every value in one of the arrays (that's why I do default += arr[i]). But the result is nil and I dont quite understand why. If possible I would like to understand the reason why it is failing.

2
  • You can simplify your loop by using sum Commented Mar 16, 2021 at 7:21
  • What do you expect from this case: find_deleted_number([1,2,3,4,5,6,7,8,9,9], [5,7,6,9,4,8,1,2,3])? Note the repeated 9. Of course if this case was a possible input. Commented Mar 16, 2021 at 9:13

2 Answers 2

3

arr.each iterates over elements of arr, not over indexes. Therefore, you need to change arr[i] to i.

The full answer is:

def find_deleted_number(arr, mixed_arr)
  default = 0

  arr.each do |i|
    if mixed_arr.include?(i)
      default += i
    else 
      return i
    end
  end

  default  
end
Sign up to request clarification or add additional context in comments.

Comments

2

The reason why it is failing as @yzalavin said.

You could also simplify your code:

def find_deleted_number(arr, mixed_arr)
  return arr.sum if arr.sort == mixed_arr.sort

  (arr - mixed_arr).first
end

And @Stefan provide an even shorter one-liner:

(arr - mixed_arr).first || arr.sum

4 Comments

Even shorter: (arr - mixed_arr).first || arr.sum
@Stefan Wow impressive : )
Suppose arr = [1,2]; mixed = [1,2,3]. Then arr.sort == mixed_arr.sort #=> false, so (arr - mixed_arr).first #=> [].first #=> nil is returned, which is incorrect.
@CarySwoveland Yeah, this just works within condition: The idea is for the function to check which number is in arr but not in mixed_arr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.