【问题标题】:How do you split a ruby array into two arrays based on index?如何根据索引将 ruby​​ 数组拆分为两个数组?
【发布时间】:2021-05-25 22:14:03
【问题描述】:

所以我有一个整数数组。我正在尝试获取该数组并找到一个索引 N,其中 N 左侧的整数之和等于 N 右侧的整数之和。如果没有索引会导致这种情况发生,请返回-1.

例如:

假设我有一个数组[1,2,3,4,3,2,1]: 我希望方法返回索引3,因为在数组的第3个位置,索引左侧的总和和索引右侧的总和都等于6:

[1,2,3].sum #=> 6
[3,2,1].sum #=> 6

对于数组[1,100,50,-51,1,1],它应该返回索引1,因为在数组的第一个位置,索引左侧的总和[1].sum和索引右侧的总和[50,-51,1,1].sum两者等于 1。

最后一个:

我有一个数组[20,10,-80,10,10,15,35] 在索引 0 左侧是[],并且 右侧是[10,-80,10,10,15,35]。 添加时它们都等于 0。 (空数组等于0)。

索引0是左右两边相等的地方。

假设数组都是 长度在 0 到 1000 之间的整数,数字可以是正整数或负整数。

N 左边的边等于 N 右边的边的最低索引 N。如果它没有符合这些规则的索引,则返回 -1。

如果一个数组有多个答案,它会返回最低的正确索引。我一开始就是这样,但我尝试过的一切都没有给我想要的结果。

def find_even_index(arr)
  if arr.size > 1
    left_side = #some code to get left side #reduce(:+)
    right_side = #some code to get right side #reduce(:+)
    # something that gives index at which sum of left side is the same as right
  elsif
    # more than one result give lowest index
  else
    return -1 
  end
end

谢谢!

【问题讨论】:

    标签: arrays ruby indexing methods split


    【解决方案1】:

    这是另一种方法。

    def idx(arr)
      tot = arr.sum
      arr.each_index.reduce(0) do |left_tot, i|
        m = arr[i]
        return i if left_tot == tot - m
        left_tot += 2*m
      end && -1
    end
    
    idx [1, 2, 3, 4, 3, 2, 1]
      #=> 3
    idx [1, 100, 50, -51, 1, 1]
      #=> 1
    idx [20, 10, -80, 10, 10, 15, 35]
      #=> 0
    idx [20, 10, -15, 3]
      #=> -1
    

    【讨论】:

      【解决方案2】:
      def eq_sum_index(arr)
        right_sum = arr.sum
        left_sum = 0
        arr.each_with_index do |e, index|
          right_sum -= e
          return index if left_sum == right_sum
          left_sum += e
        end
        -1
      end
      
      eq_sum_index([1, 2, 3, 4, 3, 2, 1])
      # => 3
      eq_sum_index([1, 100, 50, -51, 1, 1])
      # => 1
      eq_sum_index([20, 10, -80, 10, 10, 15, 35])
      # => 0
      

      解释:

      1. 预先计算右边部分的总和作为数组的总和。
      2. 迭代数组,每一轮将元素从右边传到左边(右边减去左边加)
      3. 每轮,如果两个和相等,则返回索引。
      4. 如果没有找到相等的和,则返回 -1。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-15
        • 2013-12-04
        • 2015-01-28
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        • 2017-05-27
        • 1970-01-01
        相关资源
        最近更新 更多