77 lines
2.0 KiB
C#
77 lines
2.0 KiB
C#
using System;
|
|
using static System.Console;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using Xunit;
|
|
|
|
namespace AdventOfCode {
|
|
|
|
public class Day05 {
|
|
|
|
static int FindRow(string boardingPass, int low, int high) {
|
|
if (low == high) {
|
|
return low;
|
|
}
|
|
int midpoint = (high + low) / 2;
|
|
if (boardingPass[0] == 'F' || boardingPass[0] == 'L') {
|
|
return FindRow(boardingPass.Substring(1), low, midpoint);
|
|
} else {
|
|
return FindRow(boardingPass.Substring(1), midpoint + 1, high);
|
|
}
|
|
}
|
|
|
|
static int FindRow(string boardingPass) {
|
|
return FindRow(boardingPass, 0, 127);
|
|
}
|
|
|
|
static int FindColumn(string boardingPass) {
|
|
return FindRow(boardingPass.Substring(7), 0, 7);
|
|
}
|
|
|
|
static int FindSeatId(string boardingPass) {
|
|
return FindRow(boardingPass) * 8 + FindColumn(boardingPass);
|
|
}
|
|
|
|
static int Part1() {
|
|
string[] passes = File.ReadAllLines(Util.RootDir + "day05.txt");
|
|
int maxId = 0;
|
|
foreach (string boardingPass in passes) {
|
|
int id = FindSeatId(boardingPass);
|
|
if (id > maxId) {
|
|
maxId = id;
|
|
}
|
|
}
|
|
return maxId;
|
|
}
|
|
|
|
static int Part2() {
|
|
string[] passes = File.ReadAllLines(Util.RootDir + "day05.txt");
|
|
var seatIds = new HashSet<int>();
|
|
foreach (string boardingPass in passes) {
|
|
int id = FindSeatId(boardingPass);
|
|
seatIds.Add(id);
|
|
}
|
|
for (int i = 1; i < 828; i++) {
|
|
if (!seatIds.Contains(i) && seatIds.Contains(i - 1) && seatIds.Contains(i + 1)) {
|
|
return i;
|
|
}
|
|
}
|
|
return -1;
|
|
}
|
|
|
|
[Fact]
|
|
public static void Test() {
|
|
Assert.Equal(44, FindRow("FBFBBFFRLR"));
|
|
Assert.Equal(5, FindColumn("FBFBBFFRLR"));
|
|
Assert.Equal(357, FindSeatId("FBFBBFFRLR"));
|
|
Assert.Equal(567, FindSeatId("BFFFBBFRRR"));
|
|
Assert.Equal(119, FindSeatId("FFFBBBFRRR"));
|
|
Assert.Equal(820, FindSeatId("BBFFBBFRLL"));
|
|
|
|
Assert.Equal(828, Part1());
|
|
Assert.Equal(565, Part2());
|
|
}
|
|
}
|
|
}
|