首页 > 解决方案 > 我将如何更改此代码以具有 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;
}

标签: javascript

解决方案


在“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++) {

推荐阅读