01020304050607080910111213141516171819202122232425

Advent of Code

2016/20

Firewall Rules

in C#

by encse

You'd like to set up a small hidden computer here so you can use it to get back into the network later. However, the corporate firewall only allows communication with certain external IP addresses.

You've retrieved the list of blocked IPs from the firewall, but the list seems to be messy and poorly maintained, and it's not clear which IPs are allowed. Also, rather than being written in dot-decimal notation, they are written as plain 32-bit integers, which can have any value from 0 through 4294967295, inclusive.

Read the full puzzle.

using System.Collections.Generic;
using System.Linq;

namespace AdventOfCode.Y2016.Day20;

[ProblemName("Firewall Rules")]
class Solution : Solver {

    public object PartOne(string input) {
        var k = 0L;
        foreach (var range in Parse(input)) {
            if (k < range.min) {
                break;
            } else if (range.min <= k && k <= range.max) {
                k = range.max + 1;
            }
        }
        return k;
    }

    public object PartTwo(string input) {
        var k = 0L;
        var sum = 0L;
        foreach (var range in Parse(input)) {
            if (k < range.min) {
                sum += range.min - k;
                k = range.max + 1;
            } else if (range.min <= k && k <= range.max) {
                k = range.max + 1;
            }
        }

        var lim = 4294967296L;
        if (lim > k) {
            sum += lim - k;
        }
        return sum;
    }

    IEnumerable<(long min, long max)> Parse(string input) => (
            from line in input.Split('\n')
            let parts = line.Split('-')
            let min = long.Parse(parts[0])
            let max = long.Parse(parts[1])
            orderby min
            select (min, max)
        ).AsEnumerable();
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator