main.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const fs = require('fs');
  2. function read(cb) {
  3. fs.readFile('./input', 'utf8', (err, data) => {
  4. data.split("\n").forEach((line) => {
  5. var currentNb = Number.parseInt(line);
  6. if (!isNaN(currentNb))
  7. return cb.onLine(currentNb);
  8. });
  9. cb.onDone();
  10. });
  11. }
  12. function Sum(nb) {
  13. this.number = 0;
  14. }
  15. Sum.prototype.onLine = function(number) {
  16. this.number += number;
  17. return true;
  18. }
  19. Sum.prototype.onDone = function() {
  20. console.log(this.number);
  21. }
  22. function FqFinder() {
  23. Sum.call(this);
  24. this.buffer = [0];
  25. this.allNumbers = [];
  26. this.doneReading = false;
  27. this.found = false;
  28. this.sqLen = -1;
  29. this.sqPos = 0;
  30. }
  31. FqFinder.prototype.onLine = function(number) {
  32. Sum.prototype.onLine.call(this, number);
  33. if (this.buffer.indexOf(this.number) >= 0) {
  34. this.found = true;
  35. return false;
  36. }
  37. this.buffer.push(this.number);
  38. if (!this.doneReading) {
  39. this.allNumbers.push(number);
  40. }
  41. if (this.sqLen < 0 && this.sqPos > 0 && this.sqPos %2 == 1)
  42. this.checkSq();
  43. this.sqPos++;
  44. if (this.sqLen > 0 && this.sqPos == this.sqLen)
  45. this.sqPos = 0;
  46. return true;
  47. }
  48. FqFinder.prototype.checkSq = function() {
  49. for (var i =0; i < this.sqPos /2; ++i) {
  50. if (this.allNumbers[i] != this.allNumbers[i +this.sqPos /2])
  51. return false;
  52. }
  53. this.sqLen = this.sqPos = this.sqPos /2;
  54. console.log("Found sequence ! (len=" +this.sqLen +")");
  55. return true;
  56. }
  57. FqFinder.prototype.onDone = function() {
  58. this.doneReading = true;
  59. if (!this.found) {
  60. if (this.sqLen == -1) {
  61. this.sqLen = this.sqPos;
  62. this.sqPos = 0;
  63. }
  64. while (this.onLine(this.allNumbers[this.sqPos]));
  65. }
  66. console.log(this.number);
  67. }
  68. function ex1() {
  69. read(new Sum());
  70. }
  71. function ex2() {
  72. read(new FqFinder());
  73. }
  74. ex1();
  75. ex2();