如何在ruby中的数组数组中找到整数的位置?

时间:2015-07-16 19:28:14

标签: ruby

假设:

a = [[1,2,3,4],
     [1,2,3,7],
     [1,2,3,4]]

输出7的位置为(1,3)需要做什么?

我尝试使用.index无济于事。

4 个答案:

答案 0 :(得分:3)

require 'matrix'

a = [[1, 2, 3, 4],
     [1, 2, 3, 7],
     [1, 2, 3, 4]]

Matrix[*a].index(7)

=> [1, 3]

答案 1 :(得分:1)

如果子阵列的宽度相同,则可以将其展平为单个阵列,并将位置视为row_num * row_width + col_num

idx = a.flatten.index(7)
row_width = a[0].length
row = idx / row_width
col = idx - (row * row_width)
puts [row, col] # => [1, 3]

或者您可以迭代它以查找所有匹配项:

def find_indices_for(array, value)
  array.with_object([]).with_index do |(row, matches), row_index|
    matches << [row_index, row.index(value)] if row.index(value)
  end
end

find_indices_for(a, 7) # => [[1, 3]]
find_indices_for(a, 2) # => [[0, 1], [1, 1], [2, 1]]

答案 2 :(得分:0)

<int-kafka:message-driven-channel-adapter>在这里效果很好:

KafkaMessageHeaders kafkaMessageHeaders = new KafkaMessageHeaders(generateMessageId, generateTimestamp);

Map<String, Object> rawHeaders = kafkaMessageHeaders.getRawHeaders();
rawHeaders.put(KafkaHeaders.MESSAGE_KEY, key);
rawHeaders.put(KafkaHeaders.TOPIC, metadata.getPartition().getTopic());
rawHeaders.put(KafkaHeaders.PARTITION_ID, metadata.getPartition().getId());
rawHeaders.put(KafkaHeaders.OFFSET, metadata.getOffset());
rawHeaders.put(KafkaHeaders.NEXT_OFFSET, metadata.getNextOffset());

if (!this.autoCommitOffset) {
    rawHeaders.put(KafkaHeaders.ACKNOWLEDGMENT, acknowledgment);
}

现在,each_with_index将返回一个数组,其中包含def locator(array, number) locations = Array.new array.each_with_index do |mini_array, index| mini_array.each_with_index do |element, sub_index| locations << [index, sub_index] if element == number end end locations end locator(array, number)的所有位置。

答案 3 :(得分:0)

def locs2D(a,e)
  a.size.times.with_object([]) do |row,arr|
    row.size.times { |col| arr << [row,col] if a[row][col] == e }
  end
end

locs2D(a,7) #=> [[1, 3]] 
locs2D(a,3) #=> [[0, 2], [1, 2], [2, 2]]