main.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. const SERIAL = 8444,
  2. MAP_SIZE =300;
  3. var resultCache = [];
  4. function getLevel(px, py) {
  5. return resultCache[px *MAP_SIZE +py] || (resultCache[px *MAP_SIZE +py] = (Math.floor((((px +10) *py +SERIAL) *(px +10)) / 100) %10) -5);
  6. }
  7. function sumSquare(px, py, size) {
  8. var r = 0;
  9. for (var i =0; i < size; ++i)
  10. for (var j =0; j < size; ++j)
  11. r += getLevel(px +i, py +j);
  12. return writeCache(px, py, size, r);
  13. }
  14. var cache = {};
  15. function getCache(px, py, size) {
  16. if (!cache[size])
  17. return;
  18. if (!cache[size][px])
  19. return;
  20. return (cache[size][px][py])
  21. }
  22. function writeCache(px, py, size, val) {
  23. if (size < (MAP_SIZE /2) +1) {
  24. cache[size] = cache[size] || [];
  25. cache[size][px] = cache[size][px] || [];
  26. cache[size][px][py] = val;
  27. }
  28. return val;
  29. }
  30. function sumSquareWithCache(px, py, size, toto) {
  31. var cached = getCache(px, py, size);
  32. if (cached !== undefined)
  33. return cached;
  34. if (size >= 2 && Math.floor(size /2) == size /2)
  35. return writeCache(px, py, size, sumSquareWithCache(px, py, size /2, 1) +
  36. sumSquareWithCache(px +size /2, py, size /2, 1) +
  37. sumSquareWithCache(px +size /2, py +size /2, size /2, 1) +
  38. sumSquareWithCache(px, py +size /2, size /2, 1));
  39. else if (size > 8) {
  40. var tmpResult = sumSquareWithCache(px, py, size -1, 1);
  41. for (var i =0; i <= size -1; ++i)
  42. tmpResult += getLevel(px +i, py +size -1);
  43. for (var i =0; i < size -1; ++i)
  44. tmpResult += getLevel(px +size -1, py +i);
  45. return writeCache(px, py, size, tmpResult);
  46. }
  47. return sumSquare(px, py, size);
  48. }
  49. function printResult(r) {
  50. console.log(r.px +"," +r.py +", " +r.size);
  51. }
  52. function ex1(size) {
  53. var max = null;
  54. for (var i =1; i <= MAP_SIZE -3; ++i)
  55. for (var j =1; j <= MAP_SIZE -3; ++j) {
  56. var val = sumSquareWithCache(i, j, size);
  57. if (!max || val > max.val)
  58. max = {
  59. px: i,
  60. py: j,
  61. val: val,
  62. size: size
  63. };
  64. }
  65. return max;
  66. }
  67. function ex2() {
  68. var max = null;
  69. for (var i =1; i < MAP_SIZE; ++i) {
  70. var val = ex1(i);
  71. if (!max || (val && val.val > max.val))
  72. max = val;
  73. process.stdout.write(i +"/" +MAP_SIZE +"\r");
  74. }
  75. process.stdout.write("\n");
  76. printResult(max);
  77. }
  78. printResult(ex1(3));
  79. ex2();