mod.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. /*
  2. --- Day 5: Sunny with a Chance of Asteroids ---
  3. You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get
  4. the air conditioner working by upgrading your ship computer to support the Thermal Environment
  5. Supervision Terminal.
  6. The Thermal Environment Supervision Terminal (TEST) starts by running a diagnostic program (your
  7. puzzle input). The TEST diagnostic program will run on your existing Intcode computer after a few
  8. modifications:
  9. First, you'll need to add two new instructions:
  10. Opcode 3 takes a single integer as input and saves it to the position given by its only
  11. parameter. For example, the instruction 3,50 would take an input value and store it at address
  12. 50.
  13. Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would
  14. output the value at address 50.
  15. Programs that use these instructions will come with documentation that explains what should be
  16. connected to the input and output. The program 3,0,4,0,99 outputs whatever it gets as input, then
  17. halts.
  18. Second, you'll need to add support for parameter modes:
  19. Each parameter of an instruction is handled based on its parameter mode. Right now, your ship
  20. computer already understands parameter mode 0, position mode, which causes the parameter to be
  21. interpreted as a position - if the parameter is 50, its value is the value stored at address 50 in
  22. memory. Until now, all parameters have been in position mode.
  23. Now, your ship computer will also need to handle parameters in mode 1, immediate mode. In immediate
  24. mode, a parameter is interpreted as a value - if the parameter is 50, its value is simply 50.
  25. Parameter modes are stored in the same value as the instruction's opcode. The opcode is a two-digit
  26. number based only on the ones and tens digit of the value, that is, the opcode is the rightmost two
  27. digits of the first value in an instruction. Parameter modes are single digits, one per parameter,
  28. read right-to-left from the opcode: the first parameter's mode is in the hundreds digit, the second
  29. parameter's mode is in the thousands digit, the third parameter's mode is in the ten-thousands
  30. digit, and so on. Any missing modes are 0.
  31. For example, consider the program 1002,4,3,4,33.
  32. The first instruction, 1002,4,3,4, is a multiply instruction - the rightmost two digits of the
  33. first value, 02, indicate opcode 2, multiplication. Then, going right to left, the parameter modes
  34. are 0 (hundreds digit), 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore
  35. zero):
  36. ABCDE
  37. 1002
  38. DE - two-digit opcode, 02 == opcode 2
  39. C - mode of 1st parameter, 0 == position mode
  40. B - mode of 2nd parameter, 1 == immediate mode
  41. A - mode of 3rd parameter, 0 == position mode,
  42. omitted due to being a leading zero
  43. This instruction multiplies its first two parameters. The first parameter, 4 in position mode,
  44. works like it did before - its value is the value stored at address 4 (33). The second parameter, 3
  45. in immediate mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written
  46. according to the third parameter, 4 in position mode, which also works like it did before - 99 is
  47. written to address 4.
  48. Parameters that an instruction writes to will never be in immediate mode.
  49. Finally, some notes:
  50. It is important to remember that the instruction pointer should increase by the number of
  51. values in the instruction after the instruction finishes. Because of the new instructions, this
  52. amount is no longer always 4.
  53. Integers can be negative: 1101,100,-1,4,0 is a valid program (find 100 + -1, store the result
  54. in position 4).
  55. The TEST diagnostic program will start by requesting from the user the ID of the system to test by
  56. running an input instruction - provide it 1, the ID for the ship's air conditioner unit.
  57. It will then perform a series of diagnostic tests confirming that various parts of the Intcode
  58. computer, like parameter modes, function correctly. For each test, it will run an output
  59. instruction indicating how far the result of the test was from the expected value, where 0 means
  60. the test was successful. Non-zero outputs mean that a function is not working correctly; check the
  61. instructions that were run before the output instruction to see which one failed.
  62. Finally, the program will output a diagnostic code and immediately halt. This final output isn't an
  63. error; an output followed immediately by a halt means the program finished. If all outputs were
  64. zero except the diagnostic code, the diagnostic program ran successfully.
  65. After providing 1 to the only input instruction and passing all the tests, what diagnostic code
  66. does the program produce?
  67. */
  68. use log::{debug, trace};
  69. use std::convert::TryFrom;
  70. use std::io::{stdin, stdout, Write};
  71. use crate::puzzle::options::Options;
  72. use crate::puzzle::traits::{Create, Solve};
  73. pub struct Puzzle {
  74. options: Options,
  75. computer: Computer,
  76. }
  77. impl Solve for Puzzle {
  78. fn solve(&self) -> i32 {
  79. match self.options.puzzle {
  80. 1 => self.solve_p1(),
  81. 2 => self.solve_p2(),
  82. x => panic!("Unknown puzzle {}", x),
  83. }
  84. }
  85. }
  86. impl Create for Puzzle {
  87. fn new(opt: Options) -> Box<dyn Solve> {
  88. Box::new(Self {
  89. options: opt,
  90. computer: Computer {
  91. opcodes: if opt.prompt {
  92. Self::prompt_for_opcodes()
  93. } else {
  94. Self::default_opcodes()
  95. },
  96. },
  97. })
  98. }
  99. }
  100. impl Puzzle {
  101. fn solve_p1(&self) -> i32 {
  102. let result = self.computer.run();
  103. match result {
  104. Ok(res) => res[0],
  105. Err(e) => panic!(e),
  106. }
  107. }
  108. fn solve_p2(&self) -> i32 {
  109. unimplemented!()
  110. }
  111. fn prompt_for_opcodes() -> Vec<i32> {
  112. println!("enter comma-separated values, like given: ");
  113. let mut input = String::new();
  114. match stdin().read_line(&mut input) {
  115. Ok(_) => (),
  116. Err(e) => panic!("Failed to read input: {}", e),
  117. }
  118. input
  119. .split(',')
  120. .map(|code| match code.trim().parse::<i32>() {
  121. Ok(i) => i,
  122. Err(e) => panic!("failed to parse {}: {}", code, e),
  123. })
  124. .collect()
  125. }
  126. fn default_opcodes() -> Vec<i32> {
  127. vec![
  128. 3, 225, 1, 225, 6, 6, 1100, 1, 238, 225, 104, 0, 1101, 11, 91, 225, 1002, 121, 77, 224,
  129. 101, -6314, 224, 224, 4, 224, 1002, 223, 8, 223, 1001, 224, 3, 224, 1, 223, 224, 223,
  130. 1102, 74, 62, 225, 1102, 82, 7, 224, 1001, 224, -574, 224, 4, 224, 102, 8, 223, 223,
  131. 1001, 224, 3, 224, 1, 224, 223, 223, 1101, 28, 67, 225, 1102, 42, 15, 225, 2, 196, 96,
  132. 224, 101, -4446, 224, 224, 4, 224, 102, 8, 223, 223, 101, 6, 224, 224, 1, 223, 224,
  133. 223, 1101, 86, 57, 225, 1, 148, 69, 224, 1001, 224, -77, 224, 4, 224, 102, 8, 223, 223,
  134. 1001, 224, 2, 224, 1, 223, 224, 223, 1101, 82, 83, 225, 101, 87, 14, 224, 1001, 224,
  135. -178, 224, 4, 224, 1002, 223, 8, 223, 101, 7, 224, 224, 1, 223, 224, 223, 1101, 38, 35,
  136. 225, 102, 31, 65, 224, 1001, 224, -868, 224, 4, 224, 1002, 223, 8, 223, 1001, 224, 5,
  137. 224, 1, 223, 224, 223, 1101, 57, 27, 224, 1001, 224, -84, 224, 4, 224, 102, 8, 223,
  138. 223, 1001, 224, 7, 224, 1, 223, 224, 223, 1101, 61, 78, 225, 1001, 40, 27, 224, 101,
  139. -89, 224, 224, 4, 224, 1002, 223, 8, 223, 1001, 224, 1, 224, 1, 224, 223, 223, 4, 223,
  140. 99, 0, 0, 0, 677, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1105, 0, 99999, 1105, 227, 247,
  141. 1105, 1, 99999, 1005, 227, 99999, 1005, 0, 256, 1105, 1, 99999, 1106, 227, 99999, 1106,
  142. 0, 265, 1105, 1, 99999, 1006, 0, 99999, 1006, 227, 274, 1105, 1, 99999, 1105, 1, 280,
  143. 1105, 1, 99999, 1, 225, 225, 225, 1101, 294, 0, 0, 105, 1, 0, 1105, 1, 99999, 1106, 0,
  144. 300, 1105, 1, 99999, 1, 225, 225, 225, 1101, 314, 0, 0, 106, 0, 0, 1105, 1, 99999,
  145. 1008, 677, 226, 224, 1002, 223, 2, 223, 1006, 224, 329, 101, 1, 223, 223, 8, 226, 677,
  146. 224, 102, 2, 223, 223, 1005, 224, 344, 101, 1, 223, 223, 1107, 226, 677, 224, 102, 2,
  147. 223, 223, 1006, 224, 359, 101, 1, 223, 223, 1007, 226, 226, 224, 102, 2, 223, 223,
  148. 1006, 224, 374, 101, 1, 223, 223, 7, 677, 677, 224, 102, 2, 223, 223, 1005, 224, 389,
  149. 1001, 223, 1, 223, 108, 677, 677, 224, 1002, 223, 2, 223, 1005, 224, 404, 101, 1, 223,
  150. 223, 1008, 226, 226, 224, 102, 2, 223, 223, 1005, 224, 419, 1001, 223, 1, 223, 1107,
  151. 677, 226, 224, 102, 2, 223, 223, 1005, 224, 434, 1001, 223, 1, 223, 1108, 677, 677,
  152. 224, 102, 2, 223, 223, 1006, 224, 449, 1001, 223, 1, 223, 7, 226, 677, 224, 102, 2,
  153. 223, 223, 1005, 224, 464, 101, 1, 223, 223, 1008, 677, 677, 224, 102, 2, 223, 223,
  154. 1005, 224, 479, 101, 1, 223, 223, 1007, 226, 677, 224, 1002, 223, 2, 223, 1006, 224,
  155. 494, 101, 1, 223, 223, 8, 677, 226, 224, 1002, 223, 2, 223, 1005, 224, 509, 101, 1,
  156. 223, 223, 1007, 677, 677, 224, 1002, 223, 2, 223, 1006, 224, 524, 101, 1, 223, 223,
  157. 107, 226, 226, 224, 102, 2, 223, 223, 1006, 224, 539, 101, 1, 223, 223, 107, 226, 677,
  158. 224, 102, 2, 223, 223, 1005, 224, 554, 1001, 223, 1, 223, 7, 677, 226, 224, 102, 2,
  159. 223, 223, 1006, 224, 569, 1001, 223, 1, 223, 107, 677, 677, 224, 1002, 223, 2, 223,
  160. 1005, 224, 584, 101, 1, 223, 223, 1107, 677, 677, 224, 102, 2, 223, 223, 1005, 224,
  161. 599, 101, 1, 223, 223, 1108, 226, 677, 224, 102, 2, 223, 223, 1006, 224, 614, 101, 1,
  162. 223, 223, 8, 226, 226, 224, 102, 2, 223, 223, 1006, 224, 629, 101, 1, 223, 223, 108,
  163. 226, 677, 224, 102, 2, 223, 223, 1005, 224, 644, 1001, 223, 1, 223, 108, 226, 226, 224,
  164. 102, 2, 223, 223, 1005, 224, 659, 101, 1, 223, 223, 1108, 677, 226, 224, 102, 2, 223,
  165. 223, 1006, 224, 674, 1001, 223, 1, 223, 4, 223, 99, 226,
  166. ]
  167. }
  168. }
  169. #[derive(Debug, Copy, Clone)]
  170. enum OpMode {
  171. Position = 0,
  172. Immediate,
  173. }
  174. impl TryFrom<i32> for OpMode {
  175. type Error = i32;
  176. fn try_from(v: i32) -> Result<Self, Self::Error> {
  177. trace!("try converting {} to enum OpMode", v);
  178. match v {
  179. x if x == OpMode::Position as i32 => Ok(OpMode::Position),
  180. x if x == OpMode::Immediate as i32 => Ok(OpMode::Immediate),
  181. _ => Err(v),
  182. }
  183. }
  184. }
  185. #[derive(Debug)]
  186. enum OpCode {
  187. Add = 1,
  188. Mult,
  189. Input,
  190. Output,
  191. Halt = 99,
  192. }
  193. impl TryFrom<i32> for OpCode {
  194. type Error = i32;
  195. fn try_from(v: i32) -> Result<Self, Self::Error> {
  196. trace!("try converting {} to enum OpCode", v);
  197. match v {
  198. x if x == OpCode::Add as i32 => Ok(OpCode::Add),
  199. x if x == OpCode::Mult as i32 => Ok(OpCode::Mult),
  200. x if x == OpCode::Input as i32 => Ok(OpCode::Input),
  201. x if x == OpCode::Output as i32 => Ok(OpCode::Output),
  202. x if x == OpCode::Halt as i32 => Ok(OpCode::Halt),
  203. _ => Err(v),
  204. }
  205. }
  206. }
  207. impl OpCode {
  208. fn num_args(&self) -> i32 {
  209. match self {
  210. OpCode::Add => 4,
  211. OpCode::Mult => 4,
  212. OpCode::Input => 2,
  213. OpCode::Output => 2,
  214. OpCode::Halt => 0,
  215. }
  216. }
  217. }
  218. #[derive(Debug)]
  219. struct Operation<'a> {
  220. opcode: OpCode,
  221. opcodes: &'a mut Vec<i32>,
  222. param_1_mode: OpMode,
  223. param_2_mode: OpMode,
  224. param_3_mode: OpMode,
  225. }
  226. type OperationParseError = String;
  227. impl Operation<'_> {
  228. fn new(opcodes: &mut Vec<i32>, index: usize) -> Result<Operation, OperationParseError> {
  229. let mut opcode = opcodes[index];
  230. debug!("try converting {} to Operation", opcode);
  231. let operation = match OpCode::try_from(opcode % 100) {
  232. Ok(x) => x,
  233. Err(e) => return Err(format!("Unknown opcode {}", e)),
  234. };
  235. opcode /= 100;
  236. trace!("operation: {:?}, opcode: {}", operation, opcode);
  237. let param_1_mode = match OpMode::try_from(opcode % 10) {
  238. Ok(x) => x,
  239. Err(e) => return Err(format!("unknown operation mode {}", e)),
  240. };
  241. opcode /= 10;
  242. trace!("param_1_mode: {:?}, opcode: {}", param_1_mode, opcode);
  243. let param_2_mode = match OpMode::try_from(opcode % 10) {
  244. Ok(x) => x,
  245. Err(e) => return Err(format!("unknown operation mode {}", e)),
  246. };
  247. opcode /= 10;
  248. trace!("param_2_mode: {:?}, opcode: {}", param_2_mode, opcode);
  249. let param_3_mode = match OpMode::try_from(opcode % 10) {
  250. Ok(x) => x,
  251. Err(e) => return Err(format!("unknown operation mode {}", e)),
  252. };
  253. trace!("param_3_mode: {:?}", param_2_mode);
  254. Ok(Operation {
  255. opcode: operation,
  256. opcodes: opcodes,
  257. param_1_mode,
  258. param_2_mode,
  259. param_3_mode,
  260. })
  261. }
  262. fn apply(&mut self, index: usize) -> Result<Option<usize>, String> {
  263. debug!("applying {:?} at index {}", self, index);
  264. match &self.opcode {
  265. OpCode::Add => {
  266. let arg1 = self.value_from(self.param_1_mode, index + 1);
  267. let arg2 = self.value_from(self.param_2_mode, index + 2);
  268. self.value_to(self.param_3_mode, index + 3, arg1 + arg2);
  269. }
  270. OpCode::Mult => {
  271. let arg1 = self.value_from(self.param_1_mode, index + 1);
  272. let arg2 = self.value_from(self.param_2_mode, index + 2);
  273. self.value_to(self.param_3_mode, index + 3, arg1 * arg2);
  274. }
  275. OpCode::Input => {
  276. print!("Input: ");
  277. stdout().flush().unwrap();
  278. let input = &mut String::new();
  279. let _ = stdin().read_line(input);
  280. let num: i32 = match input.trim().parse() {
  281. Ok(x) => x,
  282. Err(e) => return Err(format!("failed to decode input {}: {}", input, e)),
  283. };
  284. self.value_to(self.param_1_mode, index + 1, num);
  285. }
  286. OpCode::Output => {
  287. let arg1 = self.value_from(self.param_1_mode, index + 1);
  288. println!("Output: {}", arg1);
  289. }
  290. OpCode::Halt => return Ok(None),
  291. }
  292. Ok(Some(self.opcode.num_args() as usize))
  293. }
  294. fn value_from(&mut self, opmode: OpMode, index: usize) -> i32 {
  295. debug!("GET via OpMode {:?} from index {}", opmode, index);
  296. match opmode {
  297. OpMode::Position => {
  298. let val = self.opcodes[self.opcodes[index] as usize];
  299. trace!("retrieving position {}: {}", index, val);
  300. val
  301. }
  302. OpMode::Immediate => {
  303. let val = self.opcodes[index];
  304. trace!("directly using position {}: {}", index, val);
  305. val
  306. }
  307. }
  308. }
  309. fn value_to(&mut self, opmode: OpMode, index: usize, value: i32) {
  310. debug!("SET {} via OpMode {:?} to index {}", value, opmode, index);
  311. match opmode {
  312. OpMode::Position => {
  313. let pos = self.opcodes[index] as usize;
  314. trace!(
  315. "storing value {} to position {}: {}",
  316. value,
  317. pos,
  318. self.opcodes[index]
  319. );
  320. self.opcodes[pos] = value
  321. }
  322. OpMode::Immediate => {
  323. trace!(
  324. "immediately storing value {} to position {}: {}",
  325. value,
  326. index,
  327. self.opcodes[index]
  328. );
  329. self.opcodes[index] = value
  330. }
  331. }
  332. }
  333. }
  334. struct Computer {
  335. opcodes: Vec<i32>,
  336. }
  337. impl Computer {
  338. fn run(&self) -> Result<Vec<i32>, String> {
  339. let mut index: usize = 0;
  340. let ref mut opcodes = self.opcodes.clone();
  341. while index < opcodes.len() {
  342. let mut op = match Operation::new(opcodes, index) {
  343. Ok(x) => x,
  344. Err(e) => {
  345. return Err(format!(
  346. "failed to parse operation '{}': {}",
  347. opcodes[index], e
  348. ))
  349. }
  350. };
  351. match op.apply(index) {
  352. Ok(Some(i)) => index += i,
  353. Ok(None) => break,
  354. Err(e) => return Err(e),
  355. }
  356. }
  357. debug!("resulting opcodes: {:?}", opcodes);
  358. Ok(opcodes.to_owned())
  359. }
  360. }
  361. #[cfg(test)]
  362. mod puzzle_1 {
  363. use super::Computer;
  364. #[test]
  365. fn opcodes_sample_1() {
  366. assert_eq!(
  367. Computer {
  368. opcodes: vec![1002, 4, 3, 4, 33],
  369. }
  370. .run()
  371. .unwrap(),
  372. vec![1002, 4, 3, 4, 99]
  373. );
  374. }
  375. #[test]
  376. fn opcodes_sample_2() {
  377. assert_eq!(
  378. Computer {
  379. opcodes: vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]
  380. }
  381. .run()
  382. .unwrap(),
  383. vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50]
  384. );
  385. }
  386. #[test]
  387. fn opcodes_sample_3() {
  388. assert_eq!(
  389. Computer {
  390. opcodes: vec![10001, 1, 1, 0, 99]
  391. }
  392. .run()
  393. .unwrap(),
  394. vec![10001, 1, 1, 2, 99]
  395. );
  396. }
  397. #[test]
  398. fn opcodes_sample_4() {
  399. assert_eq!(
  400. Computer {
  401. opcodes: vec![1, 0, 0, 0, 99]
  402. }
  403. .run()
  404. .unwrap(),
  405. vec![2, 0, 0, 0, 99]
  406. );
  407. }
  408. #[test]
  409. fn opcodes_sample_5() {
  410. assert_eq!(
  411. Computer {
  412. opcodes: vec![3, 0, 4, 0, 99]
  413. }
  414. .run()
  415. .unwrap(),
  416. vec![2, 0, 0, 0, 99]
  417. );
  418. }
  419. }