迭代矩形的周长

时间:2017-02-22 15:28:35

标签: javascript loops geometry pseudocode

假设您有一个矩形width=10, height=20,并希望获得周边每个像素的坐标。你可以用4个循环来完成它,但是不是更好,更整洁的方式吗?

for(x=0; x<width; x++){
    doSomethingWith(x,0)
}
for(y=0; y<height; y++){
    doSomethingWith(0,y)
}
for(x=1; x<width; x++){
    doSomethingWith(x,height)
}
for(y=1; y<height; y++){
    doSomethingWith(width,y)
}

我将使用javascript,但赞赏伪代码或其他语言的帮助。

image of rectangle with colored perimiter

2 个答案:

答案 0 :(得分:4)

只需两个for循环即可完成:

for (x = 0; x < width; x++) {
  doSomethingWith(x, 0)
  doSomethingWith(x, height - 1)
}
for (y = 0; y < height; y++) {
  doSomethingWith(0, y)
  doSomethingWith(width - 1, y)
}

示例:

var x, y, width = 10, height = 20;
for (x = 0; x < width; x++) {
  doSomethingWith(x, 0)
  doSomethingWith(x, height - 1)
}
for (y = 0; y < height; y++) {
  doSomethingWith(0, y)
  doSomethingWith(width - 1, y)
}
function doSomethingWith(x, y) {
  var b = document.createElement("div");
  b.className = "block";
  b.style.left = (x * 10) + "px";
  b.style.top = (y * 10) + "px";
  document.body.appendChild(b)
}
.block {
  box-sizing: border-box;
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: red;
  border: 1px solid black;
}

答案 1 :(得分:1)

我会这样做:

var x = -1; var y = -1; var width = 10; var height = 20;
while (++x < width)
  [[x,0], [x, height-1]].forEach((params) => doSomethingWith.apply(this, params));
while (++y < height)
  [[0, y], [width-1, y]].forEach((params) => doSomethingWith.apply(this, params));

function doSomethingWith(x, y) {
  var b = document.createElement("div");
  b.className = "block";
  b.style.left = (x * 10) + "px";
  b.style.top = (y * 10) + "px";
  document.body.appendChild(b)
}

&#13;
&#13;
var x = -1; var y = -1; var width = 10; var height = 20;
while (++x < width)
  [[x,0], [x, height-1]].forEach((params) => doSomethingWith.apply(this, params));
while (++y < height)
  [[0, y], [width-1, y]].forEach((params) => doSomethingWith.apply(this, params));

function doSomethingWith(x, y) {
  var b = document.createElement("div");
  b.className = "block";
  b.style.left = (x * 10) + "px";
  b.style.top = (y * 10) + "px";
  document.body.appendChild(b)
}
&#13;
.block {
  box-sizing: border-box;
  position: absolute;
  width: 10px;
  height: 10px;
  background-color: red;
  border: 1px solid black;
}
&#13;
&#13;
&#13;