arrays - 你如何在 Ruby 中的循环迭代中刷新数组?

标签 arrays ruby

对于给定的数组,我想计算乘积时总是遗漏一个值。例如,对于输入 [1, 2, 3, 4] 我想要输出 [2*3*4, 1*3*4, 1*2*4, 1*2* 3],即 [24, 12, 8, 6]

def array_product(array)
  arr_lgth=array.length
  array_d=array.dup 
  sum=[]
  itr=0

  while itr<(arr_lgth)
    p itr
    p array

    array[itr]=1
    sum << array.reduce(1,:*); 
    array=array_d

    itr+=1
  end

  return sum
end

array_product([1,2,3,4])

当我跟踪迭代和数组时,我得到了以下我不理解的结果:

0
[1, 2, 3, 4]
1
[1, 2, 3, 4]
2
[1, 1, 3, 4]
3
[1, 1, 1, 4]

难道不应该在每次 while 循环迭代结束时为数组分配重复值吗?

最佳答案

对于本应是一个简单问题的问题,这段代码中发生了很多事情。 Ruby 的优势之一是能够针对这个确切的问题表达一个简单的解决方案。我认为你想要做的是:

def array_product(array)
  # Convert each index in the array...
  array.each_index.map do |i|
    # ...into a copy of the array with that index set as 1...
    array.each_with_index.map do |a, j|
      i == j ? 1 : a
    end.reduce(1, :*) # ...multiplied together.
  end
end

在 Ruby 中很少看到传统的 for 循环、类似迭代器的变量等的使用,因为 Enumerable 中有大量的工具。使它们大多已过时的库。

这里的关键是尽可能使用 map 之类的工具,而不是 dup 并且一些使用索引变量来处理数据。当您需要将原始数据 1:1“映射”到长度相同的数组中时,map 函数是关键,您可以在其中决定如何单独处理每个元素。

此代码产生:

array_product([ 1, 2, 3 ])
# => [6, 3, 2]

关于arrays - 你如何在 Ruby 中的循环迭代中刷新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853019/

相关文章:

ruby - 运行配置错误 : Custom RSpec runner script doesn't exist

ruby - 在 ruby​​ 中扩展 Date 类

ruby - 为什么分配变量时 do/end block 的行为/返回不同?

javascript - 如何将某些内容 append 到数组?

javascript - 如何动态添加 Vue JS 组件到 packery?

javascript - JQuery 读取文本并安全到二维数组

ruby-on-rails - RSpec mock_model 和 inherited_resources

ruby - 为什么 EventMachine 的延迟比 Ruby 线程慢?

c - 从字符中删除字母并重新打印该字符

java - Collections.sort 排序错误列表