Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Main()
- {
- #region testdata
- var test = new string[] {
- "#..#.#..##......###...###...........",
- "",
- "...## => #",
- "..#.. => #",
- ".#... => #",
- ".#.#. => #",
- ".#.## => #",
- ".##.. => #",
- ".#### => #",
- "#.#.# => #",
- "#.### => #",
- "##.#. => #",
- "##.## => #",
- "###.. => #",
- "###.# => #",
- "####. => #",
- };
- #endregion
- //test
- if(answerA(test, 20) != 325) throw new Exception("failed test a");
- var aoc = new AdventOfCode(2018, 12);
- aoc.SubmitAnswer(answerA(aoc.InputLines, 20), Part.A);
- aoc.SubmitAnswer(answerA(aoc.InputLines, 50000000000), Part.B);
- }
- public long answerA(string[] input, long cycles)
- {
- //get input
- string state = input[0].Replace("initial state: ", "").Trim();
- //create rule dic
- var dicRules = input.Skip(2).Select(x => x.Split(' ')).ToDictionary(x=> x[0], x => x[2]);
- //determine leftsize added
- long appendLeft = 0;
- //each cycle
- for(int i = 0; i < cycles; i++)
- {
- //get next state
- var nextGen = NextGen(state, appendLeft, dicRules);
- //did it change?
- if(nextGen.state == state)
- {
- //nope, what the next state
- var nextGen2 = NextGen(nextGen.state, nextGen.appendLeft, dicRules);
- //determine the delta per cycle
- long delta = nextGen2.appendLeft - nextGen.appendLeft;
- //move append forward in time
- appendLeft += (cycles - i) * delta;
- break; //DONE!
- }
- else
- {
- //switch
- state = nextGen.state;
- appendLeft = nextGen.appendLeft;
- }
- }
- //sum
- long sum = 0;
- //loop through the plants
- for(int i = 0; i < state.Length; i++)
- {
- //add score
- if(state[i] == '#') sum += i - appendLeft;
- }
- return sum;
- }
- public (string state, long appendLeft) NextGen(string state, long appendLeft, Dictionary<string, string> dicRules)
- {
- //append start if needed
- while (state.StartsWith("...") == false)
- {
- state = "." + state;
- appendLeft++;
- }
- //append end if needed
- while (state.EndsWith("...") == false)
- {
- state = state + ".";
- }
- //build the new state
- StringBuilder sb = new StringBuilder();
- //loop through the state
- for (int x = 0; x < state.Length - 4; x++)
- {
- if (dicRules.TryGetValue(state.Substring(x, 5), out string c))
- sb.Append(c);
- else sb.Append(".");
- }
- //create the new state (.. is default as those fall off per rules
- state = sb.ToString() + "..";
- appendLeft -= 2;
- //done
- return(state, appendLeft);
- }
- // Define other methods and classes here
Advertisement
Add Comment
Please, Sign In to add comment