迭代矩形的周长

Dwa*_*fri 1 javascript geometry loops pseudocode

假设您有一个矩形,width=10, height=20并且想要获取周长中每个像素的坐标。你可以用 4 个 for 循环来完成它,但没有更好、更简洁的方法吗?

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)
}
Run Code Online (Sandbox Code Playgroud)

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

带有彩色边界的矩形图像

Tra*_*tal 5

你可以只用两个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)
}
Run Code Online (Sandbox Code Playgroud)

例子:

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)
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)