JavaScript实现奇数尺寸X×X网格图案绘制问题求助
修正奇数尺寸网格图案生成代码
需求说明
在X×X的多维数组网格(X必须为奇数)中构造指定图案,以X=5为例,目标图案如下:
ooxoo
oxxxo
xxxxx
oxxxo
ooxoo
对应的正确返回数组为:
[["o","o","x","o","o"], ["o","x","x","x","o"], ["x","x","x","x","x"], ["o","x","x","x","o"], ["o","o","x","o","o"]]
现有错误代码
以下代码无法生成正确结果:
function drawPattern(X) { // Create an empty grid var grid = []; // Calculate the middle of the grid var middle = Math.floor(X / 2); // Loop through each row of the grid for (var i = 0; i < X; i++) { // Create an empty row var row = []; // Loop through each column of the row for (var j = 0; j < X; j++) { // Check if the current position is on the edge of the grid if (i == 0 || i == X - 1 || j == 0 || j == X - 1) { // If the current position is on the edge, add an "o" to the row row.push("o"); } else { // If the current position is not on the edge, check if it is in the middle of the grid if (i == middle && j == middle) { // If the current position is in the middle, add an "x" to the row row.push("x"); } else { // If the current position is not in the middle, add an "o" to the row row.push("o"); } } } // Add the row to the grid grid.push(row); } // Return the grid return grid; } console.log(drawPattern(5).join("\n"))
错误分析
原代码逻辑错误:仅判断了网格边缘和中心单点的位置,完全不符合目标图案的规律。目标图案的核心规则是:
对第i行,位置j显示为x的条件是该位置到网格中心的横向距离 ≤ 中心到当前行的纵向距离的差值,即:Math.abs(j - middle) ≤ middle - Math.abs(i - middle)
修正后的代码
function drawPattern(X) { const grid = []; const middle = Math.floor(X / 2); for (let i = 0; i < X; i++) { const row = []; // 计算当前行到中心的距离 const rowDist = Math.abs(i - middle); // 该行中x允许的最大横向距离 const maxColDist = middle - rowDist; for (let j = 0; j < X; j++) { // 计算当前列到中心的距离 const colDist = Math.abs(j - middle); // 根据条件添加x或o row.push(colDist <= maxColDist ? "x" : "o"); } grid.push(row); } return grid; } // 验证X=5的输出 console.log(drawPattern(5).map(row => row.join('')).join('\n'));
验证结果
运行修正后的代码,输入X=5时会输出符合要求的图案:
ooxoo
oxxxo
xxxxx
oxxxo
ooxoo
内容的提问来源于stack exchange,提问作者Wije2000
相关产品推荐
相关产品推荐

