題目:Advent of Code 2019 Day 2
  使用語言:C#
  第二天的題目是IntcodeProgram,簡單來說就是輸入一個數字會執行指定行為,題目設計有難度越來越高的趨勢,所以還不算很難,而且這次寫的IntcodeProgram後面還會再繼續發展,老實說有點後悔偷懶沒有好好寫,後面在加功能的時候就寫得有點痛苦。
  Part1是給一串指令數字和指定input算出最後結果,Part2則是給定最後結果和input範圍要算出input,都還不算太難。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
	
public class Program
{
	public static void Main()
	{
		int result = 0;
		int targetValue = 19690720;
		int noun = 0;
		int verb = 0;
		
		for(noun = 0;noun< 100;noun++)
		{
			for(verb = 0;verb < 100;verb++)
			{
				result = IntcodeProgram(noun, verb, 1);
				if(result.Equals(targetValue)) break;
				result = IntcodeProgram(noun, verb, 2);
				if(result.Equals(targetValue)) break;
			}
			
			if(result.Equals(targetValue)) break;
		}
		
		Console.WriteLine(100 * noun + verb);
	}
	
	public static int IntcodeProgram(int noun, int verb, int firstOpCode)
	{
		var inputArray = new int[] {firstOpCode,noun,verb,3,1,1,2,3,1,3,4,3,1,5,0,3,2,1,10,19,2,9,19,23,1,9,23,
									27,2,27,9,31,1,31,5,35,2,35,9,39,1,39,10,43,2,43,13,47,1,47,
									6,51,2,51,10,55,1,9,55,59,2,6,59,63,1,63,6,67,1,67,10,71,1,
									71,10,75,2,9,75,79,1,5,79,83,2,9,83,87,1,87,9,91,2,91,13,95,
									1,95,9,99,1,99,6,103,2,103,6,107,1,107,5,111,1,13,111,115,
									2,115,6,119,1,119,5,123,1,2,123,127,1,6,127,0,99,2,14,0,0};
		
		// Example input
		// var inputArray = new int[] {1,9,10,3,2,3,11,0,99,30,40,50};
		
		for(int i = 0; i < inputArray.Length - 3;i += 4)
		{
			var opCode = inputArray[i];
			
			if(opCode.Equals(99) || (!opCode.Equals(1) && !opCode.Equals(2))) break;
			
			var firstValuePosition = inputArray[i+1];
			var secondValuePosition = inputArray[i+2];
			var outputPosition = inputArray[i+3];
			
			int outputValue = 0;
			
			if(opCode.Equals(1))
				outputValue = inputArray[firstValuePosition] + inputArray[secondValuePosition];
			else
				outputValue = inputArray[firstValuePosition] * inputArray[secondValuePosition];
			
			inputArray[outputPosition] = outputValue;
		}
		
		return inputArray[0];
	}
}
    
    
Comments