Search code examples
javascriptloopsgeometrypseudocode

Iterate perimeter of rectangle


Say you got a rectangle, width=10, height=20 and want to get the coordinates of every pixel in the perimeter. You could have done it with 4 for loops, but isn't there a better, neater way?

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

I'll use javascript but help in pseudocode or other languages are appreciated.

image of rectangle with colored perimiter


Solution

  • You can do it with just two for loops:

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

    Example:

    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;
    }