查找从数组中删除的数字 [英] Find number deleted from array
问题描述
我对红宝石很陌生,所以请耐心等待,我有两个数组,我们打算查找缺失的数字.
I am quite new to ruby so bear with me, I have two arrays and we are meant to find the number which is missing.
起始数组序列为[1,2,3,4,5,6,7,8,9] 具有一个已删除数字的混合数组是5 [3,2,4,6,7,8,1,9]
The starting array sequence is [1,2,3,4,5,6,7,8,9] The mixed array with one deleted number is 5 [3,2,4,6,7,8,1,9]
我的想法是将每个数组加起来,看看缺少哪个数字-我开始产生一个方法(我知道它很破旧,但是我正在学习)
My idea is to add up each array and see which number is missing- I started to produce a method (I know it is shabby but I am learning)
def find_deleted_number(arr, mixed)
arr = [1,2,3,4,5,6,7,8,9]
mixed = [3,2,4,6,7,8,1,9]
y = arr.inject(0){|sum,x| sum + x }
x = mixed_arr.inject(0){|total, y| total + y}
return y - x
end
有人可以指导我这里做错了什么吗?
Could anyone guide me to what I am doing wrong here?
推荐答案
您将mixed
作为参数传递,然后将其用作mixed_arr.inject...
,似乎可以使它们保持一致.
You are passing in mixed
as an argument and then are using it as mixed_arr.inject...
, seems to work fine making those consistent.
此外,由于您要传入arr
和mixed
,因此不需要在方法中设置它们,因此可以将其称为
Also, since you are passing in the arr
and mixed
you don't need them to be set in the method, you can call it as
find_deleted_number([1,2,3,4,5,6,7,8,9], [3,2,4,6,7,8,1,9])
然后删除
arr = [1,2,3,4,5,6,7,8,9]
mixed = [3,2,4,6,7,8,1,9]
从方法开始.
这篇关于查找从数组中删除的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!