将IsubMatrixFull函数从Python转换为JS

2024-09-28 21:56:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将以下函数从Python转换为JS(尽可能接近原始版本(本例中为Python))

def getCol(mat, col):
    return [mat[i][col] for i in range(3)]

def isSubMatrixFull(mat):
    n = len(mat[0])
    ans = [False]*(n-2)
    kernel = getCol(mat, 0) + getCol(mat, 1) + getCol(mat, 2) # O(1)
    for i in range(n - 2): # O(n)
        if len(set(kernel)) == 9: # O(1)
            ans[i] = True # O(1)
        if i < n - 3: # O(1)
            kernel = kernel[3:] + getCol(mat, i + 3) # O(1)
    return ans

nums = [[1, 2, 3, 2, 5, 7], [4, 5, 6, 1, 7, 6], [7, 8, 9, 4, 8, 3]]
print(isSubMatrixFull(nums)) 

到目前为止,我已经了解了这一点:

function isSubMatrixFull(mat) {
  
  let test = new Array();
  function getCol(mat, col) {
    for (let i in mat) {
      test.push([mat[i][col]]);
     
       //  I have to find a way, to basically assign test values to [mat[i][col]]
       //   and then send it back to getCol(mat, i + 3)
    }
  }

  getCol(mat, 3);
  // The below would be unnecessary if I would have managed to assign test values(or 
  //  would have found other way) to [mat[i][col]] and send back to getCol(mat, i + 3) 
  test = test
    .map((v) => v)
    .join("")
    .split("")
    .map(Number);

  let n = mat[0].length;
  let res = new Array(n - 2).fill(false);
  let main = mat
    .map((rowValue, rowIndex) => mat.map((val) => val[rowIndex]))
    .join(",")
    .split(",");
  for (let i = 0; i < n - 2; i++) {
    if (new Set(main).size == 9) {
      res[i] = true;
    }
    if (i < n - 3) {
      main = main.slice(3) + getCol(mat, i + 3);
    }
  }
  // return res;
}

console.log(
  isSubMatrixFull([
    [1, 2, 3, 2, 5, 7],
    [4, 5, 6, 1, 7, 6],
    [7, 8, 9, 4, 8, 3],
  ])
);

上述功能输入的**输出**应为
isSubmatrixFull(numbers) = [true, false, true, false]

有关此问题的更多信息,请参见此处:https://leetcode.com/discuss/interview-question/860490/codesignal-intern-issubmatrixfull

请阅读评论(内部代码),看看我做了什么和试图做什么


Tags: tointestmapforreturnifmain
1条回答
网友
1楼 · 发布于 2024-09-28 21:56:57

这段代码是python的直接端口。它适用于提供的示例

const getColumn = (matrix, column) => {
    return [...Array(3).keys()].map((i) => {
        return matrix[i][column];
    });
};

const computeKernel = (matrix) => {
    return [
        ...getColumn(matrix, 0),
        ...getColumn(matrix, 1),
        ...getColumn(matrix, 2),
    ];
};

const isSubMatrixFull = (matrix) => {
    const n = matrix[0].length;
    const answer = [...Array(n - 2)].map((_) => {
        return false;
    });
    let kernel = computeKernel(matrix);
    [...Array(n - 2).keys()].forEach((i) => {
        if (new Set(kernel).size === 9) {
            answer[i] = true;
        }
        if (i < n - 3) {
            kernel = [...kernel.slice(3), ...getColumn(matrix, i + 3)];
        }
    });
    return answer;
};

const numbers = [
    [1, 2, 3, 2, 5, 7],
    [4, 5, 6, 1, 7, 6],
    [7, 8, 9, 4, 8, 3],
];
console.log(isSubMatrixFull(numbers));

相关问题 更多 >