javascript - 我将如何更改此代码以具有 5 x 4 网格?
问题描述
那么如何让代码成为如下所示的 5 x 4 网格。我目前得到一个 5 x 5 的网格并且未定义。
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
感谢 julien.giband 对代码的帮助。
//Grid size: result will be n*n cells
const GRID_SIZE = 5;
const grid = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"];
// Ship Locations
const shipLocations = ["3", "9", "15"];
let guess; //Entered value
let count = 0; //counter for rounds
do { //We'll loop indefintely until the user clicks cancel on prompt
//Construct prompt using string template (multiline)
const prpt = `Round #${++count}
${printGrid()}
Enter a Number Between 0-19`;
guess = prompt(prpt);
if (!guess && guess !== 0)
break; //Stop when cancel was clicked
const hit = shipLocations.indexOf(guess) >= 0;
console.log(`At round ${count}, cell ${guess} is a ${hit ? 'hit': 'miss'}`);
grid[guess] = hit ? '1' : 'X';
} while (guess || guess === 0); //Must have an exit condition
/** Pretty-print the grid **/
function printGrid() {
let res = "";
for (let r = 0; r < GRID_SIZE; r++) {
let srow = "";
for (let c = 0; c < GRID_SIZE; c++) {
srow += " " + grid[r * GRID_SIZE + c];
}
res += srow.substr(1) + '\n';
}
return res;
}
解决方案
在“printGrid”中,行 (r) 和列 (c) 都循环到 5 (GRID_SIZE)。如果需要 5x4 网格,则行和列需要不同的大小值:
ROW_GRID_SIZE=4;
COL_GRID_SIZE=5;
并改变你的循环:
for (let r = 0; r < ROW_GRID_SIZE; r++) {
let srow = "";
for (let c = 0; c < COL_GRID_SIZE; c++) {
推荐阅读
- r - 将因素放在数据框R中
- sql - GCP Bigquery 中的动态合并
- sql - 如何将此 SQL 查询转换为 JOIN?
- python - 在 google colab 中使用 [print(n) for n in list]
- javascript - TypeScript 数组定义
- python-3.x - @lru_cache 在具有交换参数的函数上
- postgresql - typeorm 不适用于软删除记录和唯一约束字段
- mysql - MySQL插入成功执行并返回ID,但有时并发时不保存数据
- python - Tkinter 在使用自定义图像背景时删除小部件背景
- angular - Angular等待服务中组件的输出