DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 10: Adapter Array

Collapse
 
mgasparel profile image
Mike Gasparelli

Another day where I solved Part1 and had to go back to rewrite it when Part2 came around!

My insight was that you could count the length of the sequences of 1 joltage deltas, and use that to derive the number of possible combinations. Unfortunately, I wasn't able to figure out the general formula for sequenceLength->permutations, and had to hardcode the table 😣

Part 1

        public override long SampleAnswer => 220;

        public override IEnumerable<int> ParseInput(string rawInput)
            => rawInput
                .Split(Environment.NewLine)
                .Where(line => line.Length > 0)
                .Select(line => int.Parse(line));

        public override long Solve(IEnumerable<int> input)
        {
            var deltas = GetDeltas(input.OrderBy(x => x).ToArray());
            return deltas.Count(x => x == 1) * deltas.Count(x => x == 3);
        }

        protected int[] GetDeltas(int[] values)
        {
            var deltas = new int[values.Length + 1];
            for (var i = 1; i < values.Length; i++)
            {
                deltas[i] = values[i] - values[i - 1];
            }

            deltas[0] = values[0];        // joltage between outlet and first adapter.
            deltas[values.Length] = 3;    // joltage between last adapter and device.

            return deltas;
        }
Enter fullscreen mode Exit fullscreen mode

Part 2

    public class Part2 : Part1
    {
        public override long SampleAnswer => 19208;

        public override long Solve(IEnumerable<int> input)
        {
            int[] deltas = GetDeltas(input.OrderBy(x => x).ToArray());

            return  GetContiguousOnesCounts(deltas)
                .Aggregate(1L, (sum, cur) => sum *= PossibleCombinations(cur));
        }

        IEnumerable<int> GetContiguousOnesCounts(IEnumerable<int> deltas)
        {
            int contiguousOnes = 0;
            foreach(var delta in deltas)
            {
                if (delta == 1)
                {
                    contiguousOnes++;
                    continue;
                }

                if (contiguousOnes == 0)
                {
                    continue;
                }

                yield return contiguousOnes;
                contiguousOnes = 0;
            }
        }

        long PossibleCombinations(int seqLength)
            => seqLength switch
            {
                1 => 1,
                2 => 2,
                3 => 4,
                4 => 7,
                5 => 13,
                6 => 22,
                _ => 0
            };
    }
Enter fullscreen mode Exit fullscreen mode