访问矩阵的第n个元素

时间:2020-05-20 09:22:39

标签: arrays matrix search modulus

给出一个数字n和一个表示为数组数组的矩阵。您将如何找到第n个元素?我正在寻找的答案应该涉及模运算,而不要使用标准库函数。

例如n = 7和矩阵:

[
[a_1,a_2,a_3,a_4],
[a_5,a_6,a_7,a_8],
[a_9,a_10,a_11,a_12]
]

2 个答案:

答案 0 :(得分:1)

假设我们使用基于零的索引使事情变得更简单。因此,如果我们想要第7个元素,则使用n=6

rowIndex = n / rowLength
columnIndex = n % rowLength
answer = array[rowIndex][columnIndex]

答案 1 :(得分:-2)

希望这会有所帮助。

############# Inputs ################

matrix = [[1,2,3],
         [4,5,6]]
## n is the element we need to find 
n = 16

########## Search Matrix element Logic ###########

for i in range(len(matrix)):
    for j in range(len(matrix[1])):
        if matrix[i][j] == n:
            print('row:',i,' column:',j)
            break;

        elif ( (j == len(matrix[1])-1)  and (i== len(matrix)-1) ):
            print("element not found")