Javascript – Draw Pattern

Construct the following pattern in a X by X grid(Multidimensional array)
X should be an odd number

ooxoo
oxxxo
xxxxx
oxxxo
ooxoo

Example :
Input X = 5 should return

[["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"]]

Return type should be a object.

So far I have written this code but it does not correctly provide the result I am looking for.

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"))

>Solution :

I have broken up the code into manageable pieces. The key into solving this type of problem is to break it into subproblems.

function getRow(c1, n, c2, m) {
    const row = [];
  
    for (let i=0; i<n; i++)
      row.push(c1);
  
    for (let i=0; i<m; i++)
      row.push(c2);

  
    for (let i=0; i<n; i++)
      row.push(c1);
  
  return row;
}

function getGrid(c1, c2, p) {
    let grid = [];
    for (let i=1; i<=p; i+=2) {
        let m = i;
        let n = (p - i) / 2;
        let row = getRow(c1, n, c2, m);
        grid.push(row);
    }
  
    for (let i=p-2; i>=1; i-=2) {
        let m = i;
        let n = (p - i) / 2;
        let row = getRow(c1, n, c2, m);
        grid.push(row);
    }
  
    return grid;
}

console.log(getGrid('o', 'x', 5));
console.log('');
console.log(getGrid('o', 'x', 7));

Leave a Reply