matrix-ships

JavaScript performance comparison

Revision 2 of this test case created by Alexander Andreev

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function removeSheep(area, i, j) {
    if (area[i][j+1]) {
      while(area[i][j]) {
        area[i][j] = 0;
        j++;
      }
    } else {
      while(area[i] && area[i][j]) {
        area[i][j] = 0;
        i++;
      }
    }
  }
  
  function getNumberOfShips1(area) {
    var count = 0;
    for(var i = 0; i < area.length; i++) {
      for(var j = 0; j < area[i].length; j++) {
        if(area[i][j]) {
          count ++;
          removeSheep(area, i, j)
        }
      }
    }
    return count;
  }
  
  function getNumberOfShips2(area) {
      var ships = 0;
    
      for (var i = 0; i < area.length; i++) {
        for (var j = 0; j < area[i].length; j++) {
          if (!area[i][j] || (area[i + 1] && area[i + 1][j]) || area[i][j + 1]) {
            continue;
          }
          ships++;
        }
      }
    
      return ships;
    }
  
  function getNumberOfShips3(area) {
      let [numberOfShips, lenX, lenY] = [0, area.length, area[0].length];
  
      let point = (x,y) => area[x] && area[x][y];
  
      for (let y = 0; y < lenY; y++) {
          for (let x = 0; x < lenX; x++) {
              if (point(x, y) === 1 && point(x - 1, y) != 1 && point(x, y - 1) !== 1 && point(x, y + 1) !== 1) {
                  numberOfShips++;
              } else if (point(x, y) === 1 && point(x, y - 1) != 1 && point(x - 1, y) !== 1 && point(x + 1, y) !== 1) {
                  numberOfShips++;
              }
          }
      }
  
      return numberOfShips;
  }
  
  function getNumberOfShips4(area) {
    return area.reduce((acc, itemOut, iOut, arrOut) => {
      return acc + itemOut.reduce((acc, item, i, arr) => {
        const prevArr = arrOut[iOut - 1];
  
        return !item || (arr[i-1] || (prevArr && prevArr[i])) ? acc : acc + 1;
      }, 0)
    }, 0)
  }

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
solution-3
var area = [
    [1, 0, 0, 1],
    [1, 0, 0, 1],
    [1, 0, 0, 1],
    [0, 0, 0, 0],
    [0, 1, 0, 1]
];

getNumberOfShips3(area);
pending…
solution-4
var area = [
    [1, 0, 0, 1],
    [1, 0, 0, 1],
    [1, 0, 0, 1],
    [0, 0, 0, 0],
    [0, 1, 0, 1]
];

getNumberOfShips4(area);
pending…

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL.

0 Comments