main.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. function Claim(line) {
  2. line = line.split(/\D+/).filter(r => r.length > 0);
  3. this.id = parseInt(line[0]);
  4. this.px = parseInt(line[1]);
  5. this.py = parseInt(line[2]);
  6. this.width = parseInt(line[3]);
  7. this.height = parseInt(line[4]);
  8. }
  9. function read(cb) {
  10. require("fs").readFile('./input', 'utf8', (err, data) => {
  11. var lines = [];
  12. data.split("\n").forEach((line) => {
  13. if (line.length > 0)
  14. cb(new Claim(line));
  15. });
  16. cb(null);
  17. });
  18. }
  19. function Fabric() {
  20. this.claimed = [];
  21. }
  22. Fabric.prototype.claim = function(id, x, y) {
  23. var alreadyClaimed = false;
  24. this.claimed[x] = this.claimed[x] || [];
  25. this.claimed[x][y] = 1 +(this.claimed[x][y] || 0);
  26. }
  27. Fabric.prototype.claimArea = function(claim) {
  28. for (var i = 0; i < claim.width; ++i)
  29. for (var j =0; j < claim.height; ++j)
  30. this.claim(claim.id, claim.px +i, claim.py +j);
  31. }
  32. Fabric.prototype.countMultipleClaimedAreas = function() {
  33. var areas = 0;
  34. this.claimed.forEach(function(c) {
  35. c.forEach(function(r) {
  36. if (r > 1)
  37. ++areas;
  38. });
  39. });
  40. return areas;
  41. }
  42. Fabric.prototype.isIntactInch = function(px, py) {
  43. return (this.claimed[px] || [])[py] === 1;
  44. }
  45. Fabric.prototype.isIntact = function(claim) {
  46. var intact = true;
  47. for (var i = 0; i < claim.width && intact; ++i)
  48. for (var j =0; j < claim.height && intact; ++j)
  49. intact &= this.isIntactInch(claim.px +i, claim.py +j);
  50. return intact;
  51. };
  52. function run() {
  53. var f = new Fabric(),
  54. allClaims = [];
  55. read(function(claim) {
  56. if (claim) {
  57. f.claimArea(claim);
  58. allClaims.push(claim);
  59. } else {
  60. console.log("Overlap count: ", f.countMultipleClaimedAreas());
  61. allClaims.some(function(c) {
  62. if (f.isIntact(c)) {
  63. console.log("Intact claim: ", c);
  64. return true;
  65. }
  66. return false;
  67. });
  68. }
  69. });
  70. }
  71. run();