在JS中绘制具有最小时间复杂度的带边框正方形

时间:2018-11-23 01:49:21

标签: javascript time-complexity

我刚刚编写了一个绘制边框的代码。

例如,以5的正方形大小为例,代码应打印以下多行字符串:

#####
#   #
#   #
#   #
#####

,我想知道是否可以进一步简化此流程并降低时间复杂度。

var BoxFiller = "#";
var BoxSize = 8;
var Row = "";

function DrawSquare() {

  for (i = 0; i < BoxSize; i++) {
    var r = BoxSize - 1;

    if (i == 0 || i == r) {
      Row = BoxFiller.repeat(BoxSize);
    } else {
      Row = BoxFiller + " ".repeat(BoxSize - 2) + BoxFiller;
    }

    console.log(Row);

  }
}

DrawSquare();

3 个答案:

答案 0 :(得分:2)

这是降低空间和时间复杂度的替代方法。

时间复杂度:O(n)

var BoxFiller = "#";
var BoxSize = 8;
var Row = "";
var spaces = " ".repeat(BoxSize - 2);
var hashtags = BoxFiller.repeat(BoxSize);

function DrawSquare() {  
  console.log(hashtags);
  
  for (var i = 1; i < BoxSize - 1; i++) {
    console.log(BoxFiller + spaces + BoxFiller);
  }
  
  console.log(hashtags);
}

DrawSquare();
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

可以使用递归

let BoxFiller = "#";
let Row = "";
var spaces, hashtags;

function DrawRow(BoxSize, CurrPos) { 
	if(CurrPos >= BoxSize - 2)
		return;
		
	console.log(BoxFiller + spaces + BoxFiller);
	DrawRow(BoxSize, CurrPos + 1);
}

function DrawSquare(BoxSize) { 
	spaces = " ".repeat(BoxSize - 2);
	hashtags = BoxFiller.repeat(BoxSize);
	console.log(hashtags);
	DrawRow(BoxSize, 0);
	console.log(hashtags);
}

DrawSquare(8);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

对@Ele版本的微小改动,允许传入大小和填充符。

function DrawSquare(size, filler) { 
  const line = filler.repeat(size);
  const mid = filler+' '.repeat(size-2)+filler;
  let lines = [line];
  
  for (var i = 1; i < size - 1; i++) {
    lines.push(mid);
  }
  
  lines.push(line);
  
  console.log(lines.join('\n'));
}

DrawSquare(8, '*');

如果我要重画几次相同的东西,我将其更改为如下形式:

const cache = {};

function DrawSquare(size, filler) {
  if (!cache[size]) {
    const line = filler.repeat(size);
    const mid = filler+' '.repeat(size-2)+filler;
    let lines = [line];

    for (var i = 1; i < size - 1; i++) {
      lines.push(mid);
    }

    lines.push(line);

    cache[size] = lines.join('\n');
  }
  
  console.log(cache[size]);
}


console.time('first');
DrawSquare(12, '*');
console.timeEnd('first');

console.time('second');
DrawSquare(12, '*');
console.timeEnd('second');