Advertisement
Guest User

2024day09notransform

a guest
Dec 9th, 2024
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. public static partial class Day09
  2. {
  3. public static long Solve1(string input)
  4. {
  5. int[] nums = input.ToCharArray().Select(c => c - '0').ToArray();
  6. long result = 0L;
  7. int k = 0;
  8. int i = 0;
  9. int j = nums.Length - 1;
  10. while (true)
  11. {
  12. if (i % 2 == 0)
  13. {
  14. result += UpdateFileCheckSum(nums[i], i / 2, ref k);
  15. nums[i] = 0;
  16. if (i >= j)
  17. break;
  18. i += 1;
  19. }
  20. else
  21. {
  22. if (i >= j)
  23. {
  24. result += (nums[j] + 1) * nums[j] / 2;
  25. break;
  26. }
  27. int m = Math.Min(nums[i], nums[j]);
  28. result += UpdateFileCheckSum(m, j / 2, ref k);
  29. nums[i] -= m;
  30. nums[j] -= m;
  31. if (nums[i] == 0)
  32. i += 1;
  33. if (nums[j] == 0)
  34. j -= 2;
  35. }
  36. }
  37. return result;
  38. }
  39. public static long Solve2(string input)
  40. {
  41. int[] nums = input.ToCharArray().Select(c => c - '0').ToArray();
  42. int[] numsCopy = nums.ToArray();
  43. long result = 0L;
  44. int k = 0;
  45. int i = 0;
  46. while (i < nums.Length)
  47. {
  48. if (i % 2 == 0)
  49. {
  50. int v = i / 2;
  51. if (nums[i] == 0)
  52. k += numsCopy[i];
  53. result += UpdateFileCheckSum(nums[i], i / 2, ref k);
  54. nums[i] = 0;
  55. i += 1;
  56. }
  57. else
  58. {
  59. bool found = false;
  60. int j = -1;
  61. var loopTo = i;
  62. for (j = nums.Length - 1; j >= loopTo; j -= 2)
  63. {
  64. if (nums[j] > 0 && nums[j] <= nums[i])
  65. {
  66. found = true;
  67. break;
  68. }
  69. }
  70. if (found)
  71. {
  72. result += UpdateFileCheckSum(nums[j], j / 2, ref k);
  73. nums[i] -= nums[j];
  74. nums[j] = 0;
  75. if (nums[i] == 0)
  76. i += 1;
  77. }
  78. else
  79. {
  80. k += nums[i];
  81. i += 1;
  82. }
  83. }
  84. }
  85. return result;
  86. }
  87. private static long UpdateFileCheckSum(int cur, long value, ref int k)
  88. {
  89. long ret = (cur - 1 + 2 * k) * cur / 2 * value;
  90. k += cur;
  91. return ret;
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement