【问题标题】:Select all but current in array选择数组中除当前之外的所有内容
【发布时间】:2016-11-03 02:19:11
【问题描述】:
a = [1,4,1]
total = []

a.each do |num|
  total << a.select {|x| x != num}
end

p total => [[4], [1, 1], [4]]

我希望选择数组中除当前元素之外的所有其他元素。当没有重复时,上面的工作正常,但是当有重复时,输出不正确。在这种情况下,输出应该是:

[[4,1], [1, 1], [1,4]]

我尝试使用 each_with_index 并以索引而不是数字为目标,但遇到了同样的问题。有任何想法吗?选择以外的东西?

谢谢

【问题讨论】:

    标签: arrays ruby iteration


    【解决方案1】:

    我不是一个 Ruby 开发人员,如果这不是惯用的,那么很抱歉,但试一试?

    a = [1,4,1]
    
    total = a.each_index.map { |index| a[0...index] + a[(index+1)..-1] }
    
    p total
    

    【讨论】:

    • 这是一个智能解决方案。 @user3007294 还可以查看 Array#combination。例如a.combination(a.size - 1).to_a #=&gt; [[4,1], [1, 1], [1,4]](虽然不能保证订单)
    猜你喜欢
    • 2016-01-11
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2021-01-25
    • 1970-01-01
    • 2020-09-01
    • 1970-01-01
    相关资源
    最近更新 更多