main.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. function Poly(str) {
  2. this.str = str;
  3. this.units = [];
  4. for (var i =0, len= str.length; i < len; ++i)
  5. if (this.units.indexOf(str[i].toLowerCase()) == -1)
  6. this.units.push(str[i].toLowerCase());
  7. this.units = this.units.sort();
  8. }
  9. Poly.checkReact = function(a, b) {
  10. return a.toLowerCase() == b.toLowerCase() && a !== b;
  11. }
  12. Poly.prototype.doReact = function() {
  13. for (var i =0, len= this.str.length -1; i < len; ++i)
  14. if (Poly.checkReact(this.str[i], this.str[i +1])) {
  15. this.str = this.str.substr(0, i) +this.str.substr(i +2);
  16. return true;
  17. }
  18. return false;
  19. }
  20. Poly.prototype.react = function() {
  21. var i = 0;
  22. while (this.doReact())
  23. ++i;
  24. return i;
  25. }
  26. function read(cb) {
  27. require("fs").readFile('./input', 'utf8', (err, data) => {
  28. var line = data.split("\n")[0];
  29. cb(line);
  30. });
  31. }
  32. function ex1() {
  33. read((polymereStr) => {
  34. var polymere = new Poly(polymereStr);
  35. polymere.react();
  36. console.log(polymere.str.length);
  37. });
  38. }
  39. function ex2() {
  40. read((polymereStr) => {
  41. var minPoly = null,
  42. minValue = 0,
  43. pos =0,
  44. poly = new Poly(polymereStr);
  45. poly.units.forEach((i) => {
  46. var p = new Poly(polymereStr.replace(new RegExp(i, "ig"), ""));
  47. p.react();
  48. if (minPoly ===null || minValue > p.str.length) {
  49. minPoly = i;
  50. minValue = p.str.length;
  51. }
  52. process.stdout.write('' +(++pos) +"/" +poly.units.length +"\r");
  53. });
  54. process.stdout.write("\n");
  55. console.log(minPoly, minValue);
  56. });
  57. }
  58. //ex1();
  59. ex2();