Trapped Rain 3D

by sperske

JavaScript

// expected answer: 1
const landSimple = [
  [1, 1, 1],
  [1, 0, 1],
  [1, 1, 1]
];
//Expected answer: 9
const landComplex = [
  [2, 2, 2, 0, 2, 2],
  [2, 0, 0, 1, 0, 2],
  [2, 0, 1, 1, 0, 2],
  [2, 0, 0, 0, 0, 2],
  [2, 2, 2, 2, 2, 2]
];
// expected answer: 0
const landException = [
  [1, 1, 1],
  [1, 2, 1],
  [1, 1, 1]
];

function assert(predicate, error) {
  if (!predicate) {
    throw new Error(error || 'Assertion is not true');
  }
}

function isEdge(x, y, landWidth, landHeight) {
  return (x === 0 || x === landWidth - 1) || (y === 0 || y === landHeight - 1);
}

function calcWater(land) {
  let landWidth = land.length;
  assert(landWidth > 0, 'Land has no width');
  let landHeight = land[0].length;

  let heights = [];
  for (let [x, row] of land.entries()) {
    for (let [y, height] of row.entries()) {
      heights.push({
        height,
        locaiton: {
          x,
          y
        },
        isEdge: isEdge(x, y, landWidth, landHeight)
      });
    }
  }
  // Order heigths by smallest to tallest
  heights.sort((a, b) => a.height - b.height);
  let waterVolumn = 0;
  let waterLevel = heights[0].height;

  for (let i = 0; i < heights.length; i++) {
    if (heights[i].isEdge) {
      // Don't bother testing the edge cells
      // they are guarenteed to spill over
      continue;
    }
    if (heights[i].waterLevel >= waterLevel) {
    	//Don't double count water
    	continue;
    }
    // Look for walls around
    
    console.log(cell);
  }
}

calcWater(landSimple);