【问题标题】:get coordinates of value in 2D array获取二维数组中值的坐标
【发布时间】:2014-09-13 12:22:47
【问题描述】:

我想获取存储在数组数组中的对象每次出现的坐标。如果我有一个数组:

array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"]]

还有一个对象"foo",我想得到:

[[0,0], [1,2]]

以下会这样做,但它很复杂且丑陋:

array.map
.with_index{
  |row,row_index| row.map.with_index {
    |v,col_index| v=="foo" ? [row_index,col_index] : v
  }
}
.flatten(1).find_all {|x| x.class==Array}

有没有更直接的方法来做到这一点?这是之前的asked,产生了同样不优雅的解决方案。

【问题讨论】:

    标签: ruby arrays


    【解决方案1】:

    这是一个稍微优雅的解决方案。我有:

    • 最后使用flat_map而不是flattening
    • .each_index.select代替.map.with_index,最后不得不去掉非数组,真的很丑
    • 添加缩进
    array.flat_map.with_index {|row, row_idx|
      row.each_index.select{|i| row[i] == 'foo' }.map{|col_idx| [row_idx, col_idx] }
    }
    

    【讨论】:

      【解决方案2】:

      另一种方式:

      array = [["foo", "bar", "lobster"], ["camel", "trombone", "foo"],
               ["goat", "car", "hog"], ["foo", "harp", "foo"]]
      
      array.each_with_index.with_object([]) { |(a,i),b|
         a.each_with_index { |s,j| b << [i,j] if s == "foo" } }
         #=> [[0,0], [1,2], [3,0], [3,2]
      

      【讨论】:

        【解决方案3】:

        最好使用平面数组。

        cycle = array.first.length
        #=> 3
        array.flatten.to_enum.with_index
        .select{|e, i| e == "foo"}
        .map{|e, i| i.divmod(cycle)}
        #=> [[0, 0], [1, 2]]
        

        cycle = array.first.length
        #=> 3
        array = array.flatten
        array.each_index.select{|i| array[i] == "foo"}.map{|e, i| i.divmod(cycle)}
        #=> [[0, 0], [1, 2]]
        

        【讨论】:

          猜你喜欢
          • 2017-12-23
          • 2021-08-19
          • 2019-04-14
          • 2012-02-25
          • 2016-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-05-22
          相关资源
          最近更新 更多