js写个环形矩阵随机结束点
时间: 2023-08-14 13:41:13 浏览: 50
好的,以下是一个简单的实现,生成一个 5x5 的环形矩阵,随机选择一个结束点:
```javascript
function generateMatrix(n) {
const matrix = [];
for (let i = 0; i < n; i++) {
matrix.push([]);
for (let j = 0; j < n; j++) {
matrix[i].push(0);
}
}
let left = 0,
right = n - 1,
top = 0,
bottom = n - 1;
let num = 1;
while (left <= right && top <= bottom) {
for (let j = left; j <= right; j++) {
matrix[top][j] = num++;
}
for (let i = top + 1; i <= bottom; i++) {
matrix[i][right] = num++;
}
if (left < right && top < bottom) {
for (let j = right - 1; j >= left; j--) {
matrix[bottom][j] = num++;
}
for (let i = bottom - 1; i > top; i--) {
matrix[i][left] = num++;
}
}
left++;
right--;
top++;
bottom--;
}
return matrix;
}
function getRandomEndPoint(matrix) {
const n = matrix.length;
const edgeLength = n * 2 + (n - 2) * 2;
const randomIndex = Math.floor(Math.random() * edgeLength);
let i, j;
if (randomIndex < n) {
i = 0;
j = randomIndex;
} else if (randomIndex < n + n - 2) {
i = randomIndex - n + 1;
j = n - 1;
} else if (randomIndex < n + n - 2 + n - 1) {
i = n - 1;
j = n - 1 - (randomIndex - n - n + 2);
} else {
i = n - 1 - (randomIndex - n - n - n + 4);
j = 0;
}
return [i, j];
}
const matrix = generateMatrix(5);
console.log(matrix);
const [endI, endJ] = getRandomEndPoint(matrix);
console.log(`End point: (${endI}, ${endJ})`);
```
其中,`generateMatrix()` 函数用于生成环形矩阵,`getRandomEndPoint()` 函数用于随机选择一个结束点。`getRandomEndPoint()` 函数的实现思路是:首先计算出环形矩阵的周长,然后随机选择一个位置,根据位置的值确定结束点的坐标。