gpt4 book ai didi

ruby - 获取二维数组中值的坐标

转载 作者:太空宇宙 更新时间:2023-11-03 17:23:00 25 4
gpt4 key购买 nike

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

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之前,并产生了一个类似的不优雅的解决方案。

最佳答案

这里有一个更优雅的解决方案。我有:

  • 在最后使用 flat_map 而不是 flatten
  • 使用 .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] }
}

关于ruby - 获取二维数组中值的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816978/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com