5_1.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { ExtractNumbers, Inspect, LoadInput } from "../common.ts";
  2. const tests = [
  3. "seeds: 79 14 55 13",
  4. "",
  5. "seed-to-soil map:",
  6. "50 98 2",
  7. "52 50 48",
  8. "",
  9. "soil-to-fertilizer map:",
  10. "0 15 37",
  11. "37 52 2",
  12. "39 0 15",
  13. "",
  14. "fertilizer-to-water map:",
  15. "49 53 8",
  16. "0 11 42",
  17. "42 0 7",
  18. "57 7 4",
  19. "",
  20. "water-to-light map:",
  21. "88 18 7",
  22. "18 25 70",
  23. "",
  24. "light-to-temperature map:",
  25. "45 77 23",
  26. "81 45 19",
  27. "68 64 13",
  28. "",
  29. "temperature-to-humidity map:",
  30. "0 69 1",
  31. "1 0 69",
  32. "",
  33. "humidity-to-location map:",
  34. "60 56 37",
  35. "56 93 4",
  36. ];
  37. const input = await LoadInput(5);
  38. // Parse the input
  39. const maps = ParseInput(input);
  40. // Map the seeds
  41. const seeds = maps.Seeds.map((seed) => MapSeed(seed.ID, maps));
  42. // Get the output
  43. let closestLocationID = Number.MAX_SAFE_INTEGER;
  44. if (isSeedMapArray(seeds)) {
  45. seeds.forEach((seed) => {
  46. if (seed.LocationID < closestLocationID) { closestLocationID = seed.LocationID; }
  47. });
  48. }
  49. console.log(`The lowest location ID found is: ${closestLocationID}`);
  50. function ParseInput(almanac: string[]): RangeMaps {
  51. /** An empty initializer for our output */
  52. const output: RangeMaps = {
  53. Seeds: [],
  54. SeedToSoil: [],
  55. SoilToFertilizer: [],
  56. FertilizerToWater: [],
  57. WaterToLight: [],
  58. LightToTemperature: [],
  59. TemperatureToHumidity: [],
  60. HumidityToLocation: [],
  61. };
  62. for (let i = 0; i < almanac.length; i++) {
  63. let line = almanac[i];
  64. // Parse the seed ID's
  65. if (/^seeds:/.test(line)) {
  66. // Extract all numbers from the line
  67. const seedIDs = ExtractNumbers(line);
  68. // Add to the output's Seeds array a new Seed for each number
  69. seedIDs.forEach((id) => { output.Seeds.push({ID: id}); });
  70. // Skip the next blank
  71. i++;
  72. }
  73. // Parse the Seed to Soil ranges
  74. else if (/^seed\-to/.test(line)) {
  75. output.SeedToSoil = ParseSourceDestinationRange(++i, almanac);
  76. }
  77. // Parse the Soil to Fertilizer ranges
  78. else if (/^soil\-to/.test(line)) {
  79. output.SoilToFertilizer = ParseSourceDestinationRange(++i, almanac);
  80. }
  81. // Parse the Fertilizer to Water ranges
  82. else if (/^fertilizer\-to/.test(line)) {
  83. output.FertilizerToWater = ParseSourceDestinationRange(++i, almanac);
  84. }
  85. // Parse the Water to Light ranges
  86. else if (/^water\-to/.test(line)) {
  87. output.WaterToLight = ParseSourceDestinationRange(++i, almanac);
  88. }
  89. // Parse the Light to Temperature ranges
  90. else if (/^light\-to/.test(line)) {
  91. output.LightToTemperature = ParseSourceDestinationRange(++i, almanac);
  92. }
  93. // Parse the Temperature to Humidity ranges
  94. else if (/^temperature\-to/.test(line)) {
  95. output.TemperatureToHumidity = ParseSourceDestinationRange(++i, almanac);
  96. }
  97. // Parse the Humidity to Location ranges
  98. else if (/^humidity\-to/.test(line)) {
  99. output.HumidityToLocation = ParseSourceDestinationRange(++i, almanac);
  100. }
  101. }
  102. return output;
  103. }
  104. /**
  105. * Helper function to parse the ranges for each mappable section
  106. *
  107. * @param {number} lineNumber The line number to begin parsing from
  108. * @param {string[]} almanac The complete almanac
  109. * @returns {MappableObject[]} A list of mapped indices
  110. */
  111. function ParseSourceDestinationRange(lineNumber: number, almanac: string[]): MappableObject[] {
  112. const rangeMap: MappableObject[] = [];
  113. do {
  114. // Get the values out of the line
  115. const [destinationRangeStart, sourceRangeStart, rangeLength] = ExtractNumbers(almanac[lineNumber]);
  116. // Create the ranges
  117. for (let idx = 0; idx < rangeLength; idx++) {
  118. rangeMap.push({
  119. ID: sourceRangeStart + idx,
  120. PointsTo: destinationRangeStart + idx,
  121. });
  122. }
  123. } while(almanac[++lineNumber]);
  124. return rangeMap;
  125. }
  126. /**
  127. * Find an IdentifiableObject by its ID number
  128. *
  129. * @param needle The ID number to find
  130. * @param haystack The list to find the ID in
  131. * @returns {IdentifiableObject|undefined} The object by that ID if found, or undefined
  132. */
  133. function FindObjectByID(needle: number, haystack: IdentifiableObject[]|MappableObject[]): IdentifiableObject|MappableObject|undefined {
  134. return haystack.find((obj) => obj.ID == needle);
  135. }
  136. /**
  137. * Map a Seed ID to all of its other attributes
  138. *
  139. * Given a seed ID, finds its soil type, fertilizer type, water type,
  140. * light type, temperature type, humidity type, and location ID.
  141. *
  142. * @param {number} seedID
  143. * @param {RangeMaps} rangeMaps A parsed map of ranges
  144. * @returns
  145. */
  146. function MapSeed(seedID: number, rangeMaps: RangeMaps): SeedMap|undefined {
  147. // Make sure the seed with that ID exists before continueing
  148. if(!FindObjectByID(seedID, rangeMaps.Seeds)) { return undefined; }
  149. // Initialize our seed map object
  150. const seed: SeedMap = {
  151. ID: seedID,
  152. SoilID: 0,
  153. FertilizerID: 0,
  154. WaterID: 0,
  155. LightID: 0,
  156. TemperatureID: 0,
  157. HumidityID: 0,
  158. LocationID: 0,
  159. };
  160. seed.SoilID = (FindObjectByID(seedID, rangeMaps.SeedToSoil) as MappableObject)?.PointsTo || seedID;
  161. seed.FertilizerID = (FindObjectByID(seed.SoilID, rangeMaps.SoilToFertilizer) as MappableObject)?.PointsTo || seed.SoilID;
  162. seed.WaterID = (FindObjectByID(seed.FertilizerID, rangeMaps.FertilizerToWater) as MappableObject)?.PointsTo || seed.FertilizerID;
  163. seed.LightID = (FindObjectByID(seed.WaterID, rangeMaps.WaterToLight) as MappableObject)?.PointsTo || seed.WaterID;
  164. seed.TemperatureID = (FindObjectByID(seed.LightID, rangeMaps.LightToTemperature) as MappableObject)?.PointsTo|| seed.LightID;
  165. seed.HumidityID = (FindObjectByID(seed.TemperatureID, rangeMaps.TemperatureToHumidity) as MappableObject)?.PointsTo || seed.TemperatureID;
  166. seed.LocationID = (FindObjectByID(seed.HumidityID, rangeMaps.HumidityToLocation) as MappableObject)?.PointsTo || seed.HumidityID;
  167. return seed;
  168. }
  169. /**
  170. * Type guard function to ensure an array is an array of SeedMaps
  171. *
  172. * @param {any[]} valueArray The array to check
  173. * @returns {boolean} Whether the input is an array of SeedMaps or not
  174. */
  175. function isSeedMapArray(valueArray: any[]): valueArray is SeedMap[] {
  176. const value = valueArray.shift();
  177. if (!value || typeof value !== "object") { return false; }
  178. return Object.hasOwn(value, "ID")
  179. && Object.hasOwn(value, "SoilID")
  180. && Object.hasOwn(value, "FertilizerID")
  181. && Object.hasOwn(value, "WaterID")
  182. && Object.hasOwn(value, "LightID")
  183. && Object.hasOwn(value, "TemperatureID")
  184. && Object.hasOwn(value, "HumidityID")
  185. && Object.hasOwn(value, "LocationID");
  186. }
  187. /** Any object with a unique identifier */
  188. interface IdentifiableObject {
  189. /** The ID number for this object */
  190. ID: number,
  191. };
  192. /** A seed */
  193. interface Seed extends IdentifiableObject {};
  194. /** An IdentifiableObject that points to another IdentifiableObject */
  195. interface MappableObject extends IdentifiableObject {
  196. /** The ID that this object points to */
  197. PointsTo: number,
  198. };
  199. /** A complete map of all object IDs and where they point to */
  200. type RangeMaps = {
  201. /** The list of seed IDs */
  202. Seeds: Seed[],
  203. /** The map of seed to soil IDs */
  204. SeedToSoil: MappableObject[],
  205. /** The map of soil to fertilizer IDs */
  206. SoilToFertilizer: MappableObject[],
  207. /** The map of fertilizer to water IDs */
  208. FertilizerToWater: MappableObject[],
  209. /** The map of water to light IDs */
  210. WaterToLight: MappableObject[],
  211. /** The map of light to temperature IDs */
  212. LightToTemperature: MappableObject[],
  213. /** The map of temperature to humidity IDs */
  214. TemperatureToHumidity: MappableObject[],
  215. /** The map of humidity to location IDs */
  216. HumidityToLocation: MappableObject[],
  217. }
  218. /** A completed map of a seed's property IDs */
  219. type SeedMap = {
  220. /** The ID of the seed */
  221. ID: number,
  222. /** The ID of the soil type the seed needs planted in */
  223. SoilID: number,
  224. /** The ID of the fertilizer type the soil needs */
  225. FertilizerID: number,
  226. /** The ID of the water type the fertilizer needs */
  227. WaterID: number,
  228. /** The ID of the light type the water needs */
  229. LightID: number,
  230. /** The ID of the temperature type the light needs */
  231. TemperatureID: number,
  232. /** The ID of the humidity type the temperature needs */
  233. HumidityID: number,
  234. /** The ID of the location the humidity needs */
  235. LocationID: number,
  236. }