【问题标题】:ruby uniq with replacementruby uniq 替换
【发布时间】:2014-10-31 11:25:25
【问题描述】:

普通uniq:

[1, 2, 3, 1, 1, 4].uniq => [1, 2, 3, 4]

我想用原来的位置替换副本。

有没有办法或途径来实现这样的事情?

[1, 2, 3, 1, 1, 4].uniq_with_replacement(-1) => [1, 2, 3, -1, -1, 4]

提前致谢!

【问题讨论】:

    标签: ruby uniq


    【解决方案1】:

    这是一个单行:

    a.fill{ |i| a.index(a[i]) == i ? a[i] : -1 }

    【讨论】:

      【解决方案2】:

      像这样?:

      class Array
        def uniq_with_replacement(v)
          map.with_object([]){|value, obj| obj << (obj.include?(value) ? v : value) }
        end
      end
      

      现在:

      [1, 2, 3, 1, 1, 4].uniq_with_replacement(-1)
      # => [1, 2, 3, -1, -1, 4]
      
      [1, 2, 3, 1, 1, 2, 4].uniq_with_replacement(-1)
      # => [1, 2, 3, -1, -1, -1, 4]
      

      【讨论】:

        【解决方案3】:

        还有 1 个:

        arr = [1, 2, 3, 1, 1, 4]
        value = -1
        
        a = arr.each_with_index.to_a
          #=> [[1, 0], [2, 1], [3, 2], [1, 3], [1, 4], [4, 5]]
        
        b = (a - a.uniq(&:first)).map(&:last)
          #=> [3, 4]
        
        arr.map.with_index { |e,i| b.include?(i) ? value : e }
          #=> [1, 2, 3, -1, -1, 4]
        

        【讨论】:

        • 阅读具有科学或大学背景的人编写的代码总是一种乐趣。好主意!
        猜你喜欢
        • 2016-02-28
        • 2011-10-27
        • 2020-07-19
        • 2015-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-26
        • 2012-01-29
        相关资源
        最近更新 更多