Code formatting and warning fixing.

This commit is contained in:
2024-12-01 17:36:23 +01:00
parent 9f8d966b7a
commit dafd2526d1
93 changed files with 739 additions and 823 deletions

View File

@@ -1,20 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>AdventOfCode2018</RootNamespace>
</PropertyGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>AdventOfCode2018</RootNamespace>
</PropertyGroup>
<ItemGroup>
<None Update="inputs\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<None Update="inputs\*">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\AdventOfCode.Common\AdventOfCode.Common.csproj"/>
</ItemGroup>
</Project>

View File

@@ -63,8 +63,7 @@ public class Day01 : IDay
int accumulator = 0;
foreach (string input in inputs)
{
int intInput;
if (int.TryParse(input.Substring(1), out intInput))
if (int.TryParse(input.Substring(1), out int intInput))
{
if (input[0] == '-')
{
@@ -90,8 +89,7 @@ public class Day01 : IDay
foreach (string input in inputs)
{
accumulatorHistory.Add(accumulator);
int intInput;
if (int.TryParse(input.Substring(1), out intInput))
if (int.TryParse(input.Substring(1), out int intInput))
{
if (input[0] == '-')
{

View File

@@ -50,7 +50,7 @@ What letters are common between the two correct box IDs? (In the example above,
public class Day02 : IDay
{
private int CountOccurrencesOfLetter(string text, char letter)
private static int CountOccurrencesOfLetter(string text, char letter)
{
return text.Count(c => (c == letter));
}
@@ -75,7 +75,7 @@ public class Day02 : IDay
int tripletsCount = 0;
foreach (string input in inputs)
{
var hasPairsAndTriplets = HasPairsAndTriplets(input);
Tuple<bool, bool> hasPairsAndTriplets = HasPairsAndTriplets(input);
if (hasPairsAndTriplets.Item1) { pairsCount++; }
if (hasPairsAndTriplets.Item2) { tripletsCount++; }
}
@@ -104,11 +104,10 @@ public class Day02 : IDay
{
for (int j = (i + 1); j < inputs.Length; j++)
{
var result = CompareIDPair(inputs[i], inputs[j]);
Tuple<int, string> result = CompareIDPair(inputs[i], inputs[j]);
if (result.Item1 == 1) { return result.Item2; }
}
}
return string.Empty;
}
}

View File

@@ -60,7 +60,7 @@ public class Day03 : IDay
{
public string ResolvePart1(string[] inputs)
{
List<Claim> claims = inputs.Select(i => Claim.FromString(i)).ToList();
List<Claim> claims = inputs.Select(Claim.FromString).ToList();
const int edgeSize = 1000;
int[,] cells = new int[edgeSize, edgeSize];
@@ -92,9 +92,9 @@ public class Day03 : IDay
public string ResolvePart2(string[] inputs)
{
List<Claim> claims = inputs.Select(i => Claim.FromString(i)).ToList();
List<Claim> claims = inputs.Select(Claim.FromString).ToList();
Claim unoverlappingClaim = null;
Claim unOverlappingClaim = null;
for (int i = 0; i < claims.Count; i++)
{
bool overlaps = false;
@@ -109,29 +109,43 @@ public class Day03 : IDay
}
if (overlaps == false)
{
unoverlappingClaim = claims[i];
unOverlappingClaim = claims[i];
break;
}
}
return unoverlappingClaim.ID.ToString();
return unOverlappingClaim.ID.ToString();
}
public class Claim
{
public int ID { get; set; }
public int ID { get; private set; }
public int Left { get; set; }
public int Top { get; set; }
public int Left { get; private set; }
public int Top { get; private set; }
public int Width { get; set; }
public int Height { get; set; }
public int Width { get; private set; }
public int Height { get; private set; }
public int MinX { get { return Left; } }
public int MaxX { get { return Left + Width; } }
private int MinX
{
get { return Left; }
}
public int MinY { get { return Top; } }
public int MaxY { get { return Top + Height; } }
private int MaxX
{
get { return Left + Width; }
}
private int MinY
{
get { return Top; }
}
private int MaxY
{
get { return Top + Height; }
}
public int GetArea()
{
@@ -141,7 +155,7 @@ public class Day03 : IDay
public static Claim FromString(string strClaim)
{
Claim claim = new();
string[] parts = strClaim.Split(new[] { " @ ", ",", ": ", "x", }, StringSplitOptions.None);
string[] parts = strClaim.Split([" @ ", ",", ": ", "x"], StringSplitOptions.None);
claim.ID = Convert.ToInt32(parts[0].Substring(1));
claim.Left = Convert.ToInt32(parts[1]);
claim.Top = Convert.ToInt32(parts[2]);

View File

@@ -68,14 +68,14 @@ public class Day04 : IDay
public string ResolvePart1(string[] inputs)
{
List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistorgram(guardEvents);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistogram(guardEvents);
// Find sleepier guard
GuardSleepHistogram highestSleeperHistogram = null;
long highestTotalSleep = long.MinValue;
foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values)
{
int totalSleep = guardHistogram.SleepOnMunute.Sum();
int totalSleep = guardHistogram.SleepOnMinute.Sum();
if (totalSleep > highestTotalSleep)
{
@@ -89,10 +89,10 @@ public class Day04 : IDay
int maxSleepMinuteValue = int.MinValue;
for (int i = 0; i < GuardSleepHistogram.MinutesOnHour; i++)
{
if (highestSleeperHistogram.SleepOnMunute[i] > maxSleepMinuteValue)
if (highestSleeperHistogram.SleepOnMinute[i] > maxSleepMinuteValue)
{
maxSleepMinute = i;
maxSleepMinuteValue = highestSleeperHistogram.SleepOnMunute[i];
maxSleepMinuteValue = highestSleeperHistogram.SleepOnMinute[i];
}
}
@@ -103,7 +103,7 @@ public class Day04 : IDay
public string ResolvePart2(string[] inputs)
{
List<GuardEvent> guardEvents = GuardEvent.FromStringArray(inputs);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistorgram(guardEvents);
Dictionary<int, GuardSleepHistogram> dictFullHistogram = BuildFullHistogram(guardEvents);
int selectedGuardID = int.MinValue;
int selectedMinute = int.MinValue;
@@ -112,9 +112,9 @@ public class Day04 : IDay
{
foreach (GuardSleepHistogram guardHistogram in dictFullHistogram.Values)
{
if (guardHistogram.SleepOnMunute[i] > maxSleepMinuteValue)
if (guardHistogram.SleepOnMinute[i] > maxSleepMinuteValue)
{
maxSleepMinuteValue = guardHistogram.SleepOnMunute[i];
maxSleepMinuteValue = guardHistogram.SleepOnMinute[i];
selectedGuardID = guardHistogram.ID;
selectedMinute = i;
}
@@ -125,7 +125,7 @@ public class Day04 : IDay
return result.ToString();
}
private static Dictionary<int, GuardSleepHistogram> BuildFullHistorgram(List<GuardEvent> guardEvents)
private static Dictionary<int, GuardSleepHistogram> BuildFullHistogram(List<GuardEvent> guardEvents)
{
Dictionary<int, GuardSleepHistogram> dictFullHistogram = new();
foreach (IGrouping<int, GuardEvent> group in guardEvents.GroupBy(guardEvent => guardEvent.Date.DayOfYear))
@@ -156,10 +156,8 @@ public class Day04 : IDay
foreach (GuardSleepHistogram dayGuardHistogram in dictDayHistogram.Values)
{
GuardSleepHistogram guardHistogram;
if (dictFullHistogram.ContainsKey(dayGuardHistogram.ID))
if (dictFullHistogram.TryGetValue(dayGuardHistogram.ID, out GuardSleepHistogram guardHistogram))
{
guardHistogram = dictFullHistogram[dayGuardHistogram.ID];
guardHistogram.AddHistogram(dayGuardHistogram);
}
else
@@ -181,14 +179,14 @@ public class Day04 : IDay
public class GuardEvent
{
public DateTime Date { get; set; }
public int? ID { get; set; }
public GuardEventType Type { get; set; }
public DateTime Date { get; private set; }
public int? ID { get; private set; }
public GuardEventType Type { get; private set; }
public static GuardEvent FromString(string strEvent)
{
GuardEvent guardEvent = new();
string[] parts = strEvent.Split(new[] { "[", "-", " ", ":", "]", "#", }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = strEvent.Split(["[", "-", " ", ":", "]", "#"], StringSplitOptions.RemoveEmptyEntries);
guardEvent.Date = new DateTime(
Convert.ToInt32(parts[0]),
Convert.ToInt32(parts[1]),
@@ -216,7 +214,7 @@ public class Day04 : IDay
public static List<GuardEvent> FromStringArray(string[] strEvents)
{
List<GuardEvent> guardEvents = strEvents
.Select(strEvent => FromString(strEvent))
.Select(FromString)
.OrderBy(guardEvent => guardEvent.Date)
.ToList();
@@ -240,14 +238,14 @@ public class Day04 : IDay
public class GuardSleepHistogram
{
public const int MinutesOnHour = 60;
public int ID { get; set; }
public int[] SleepOnMunute { get; } = new int[MinutesOnHour];
public int ID { get; init; }
public int[] SleepOnMinute { get; } = new int[MinutesOnHour];
public void FallSleep(int minute)
{
for (int i = minute; i < MinutesOnHour; i++)
{
SleepOnMunute[i] = 1;
SleepOnMinute[i] = 1;
}
}
@@ -255,7 +253,7 @@ public class Day04 : IDay
{
for (int i = minute; i < MinutesOnHour; i++)
{
SleepOnMunute[i] = 0;
SleepOnMinute[i] = 0;
}
}
@@ -263,7 +261,7 @@ public class Day04 : IDay
{
for (int i = 0; i < MinutesOnHour; i++)
{
SleepOnMunute[i] += histogram.SleepOnMunute[i];
SleepOnMinute[i] += histogram.SleepOnMinute[i];
}
}
}

View File

@@ -108,7 +108,7 @@ public class Day05 : IDay
public string ResolvePart2(string[] inputs)
{
string input = inputs[0];
List<char> allUnitTypes = input.Select(c => char.ToLower(c)).Distinct().ToList();
List<char> allUnitTypes = input.Select(char.ToLower).Distinct().ToList();
int minPolymerLenght = int.MaxValue;
foreach (char unitType in allUnitTypes)

View File

@@ -96,7 +96,7 @@ public class Day06 : IDay
{
return inputs
.Where(input => string.IsNullOrEmpty(input) == false)
.Select(input => ChronoPoint.FromString(input))
.Select(ChronoPoint.FromString)
.ToList();
}
@@ -183,12 +183,12 @@ public class Day06 : IDay
return areaInRange;
}
public int DistanceThresold { get; set; } = 10000;
public int DistanceThreshold { get; init; } = 10000;
public string ResolvePart2(string[] inputs)
{
List<ChronoPoint> points = InputsToPoints(inputs);
int areaInRange = AreaInThresold(points, DistanceThresold);
int areaInRange = AreaInThresold(points, DistanceThreshold);
return areaInRange.ToString();
}
@@ -200,7 +200,7 @@ public class Day06 : IDay
public static ChronoPoint FromString(string strPoint)
{
if (string.IsNullOrEmpty(strPoint)) { return null; }
string[] parts = strPoint.Split(new[] { ", ", }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = strPoint.Split([", "], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2) { return null; }
ChronoPoint point = new() {
X = Convert.ToInt32(parts[0]),

View File

@@ -89,11 +89,11 @@ public class Day07 : IDay
foreach (string input in inputs)
{
if (string.IsNullOrEmpty(input)) { continue; }
string[] parts = input.Split(new[] {
string[] parts = input.Split([
"Step ",
" must be finished before step ",
" can begin.",
}, StringSplitOptions.RemoveEmptyEntries);
], StringSplitOptions.RemoveEmptyEntries);
instructions.AddNodeRelation(parts[1].ToUpper(), parts[0].ToUpper());
}
foreach (InstructionNode node in instructions.Nodes.Values)
@@ -118,8 +118,8 @@ public class Day07 : IDay
return sbInstructions.ToString();
}
public int BaseCost { get; set; } = 60;
public int NumberOfWorkers { get; set; } = 5;
public int BaseCost { get; init; } = 60;
public int NumberOfWorkers { get; init; } = 5;
public string ResolvePart2(string[] inputs)
{
@@ -130,9 +130,9 @@ public class Day07 : IDay
public class InstructionNode
{
public string NodeID { get; set; }
public string NodeID { get; init; }
public List<string> PreviousNodeIDs { get; } = new();
public List<string> PreviousNodeIDs { get; } = [];
public int Cost { get; set; }
@@ -148,16 +148,16 @@ public class Day07 : IDay
}
}
public class Instructions
private class Instructions
{
public Dictionary<string, InstructionNode> Nodes { get; } = new();
public InstructionNode GetNode(string nodeID)
private InstructionNode GetNode(string nodeID)
{
InstructionNode node = null;
if (Nodes.ContainsKey(nodeID))
InstructionNode node;
if (Nodes.TryGetValue(nodeID, out InstructionNode nodeAux))
{
node = Nodes[nodeID];
node = nodeAux;
}
else
{
@@ -176,7 +176,7 @@ public class Day07 : IDay
public List<InstructionNode> SortInstructions()
{
List<InstructionNode> finalNodes = new();
List<InstructionNode> finalNodes = [];
foreach (InstructionNode node in Nodes.Values)
{
@@ -204,8 +204,8 @@ public class Day07 : IDay
private class SimulatedWorker
{
public InstructionNode CurrentInstruction { get; set; }
public int ElapsedTime { get; set; }
public InstructionNode CurrentInstruction { get; private set; }
private int ElapsedTime { get; set; }
public void SetInstruction(InstructionNode instruction)
{
@@ -242,7 +242,6 @@ public class Day07 : IDay
workers.Add(new SimulatedWorker());
}
bool anyWorkerWitoutWork;
do
{
bool anyWorkDone = false;
@@ -255,8 +254,8 @@ public class Day07 : IDay
}
if (anyWorkDone) { totalElapsedTime++; }
anyWorkerWitoutWork = workers.Any(w => w.CurrentInstruction == null);
if (anyWorkerWitoutWork)
bool anyWorkerWithoutWork = workers.Any(w => w.CurrentInstruction == null);
if (anyWorkerWithoutWork)
{
List<InstructionNode> unusedNodes = Nodes.Values
.Where(n =>

View File

@@ -77,13 +77,13 @@ public class Day08 : IDay
public class IntStream
{
private int[] _values;
private readonly int[] _values;
private int _index;
public IntStream(string strValues)
{
_values = strValues
.Split(new[] { " ", }, StringSplitOptions.RemoveEmptyEntries)
.Split([" "], StringSplitOptions.RemoveEmptyEntries)
.Select(strVal => Convert.ToInt32(strVal))
.ToArray();
_index = 0;
@@ -99,9 +99,9 @@ public class Day08 : IDay
public class ChronoLicenceNode
{
public List<ChronoLicenceNode> Childs { get; } = new();
public List<ChronoLicenceNode> Childs { get; } = [];
public List<int> Metadata { get; } = new();
public List<int> Metadata { get; } = [];
public static ChronoLicenceNode BuildFromIntStream(IntStream stream)
{

View File

@@ -75,7 +75,7 @@ public class Day09 : IDay
private static string CalculateHighScore(string input, long factor)
{
string[] parts = input.Split(new[] { " players; last marble is worth ", " points" }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = input.Split([" players; last marble is worth ", " points"], StringSplitOptions.RemoveEmptyEntries);
long numberOfPlayers = Convert.ToInt32(parts[0]);
long lastMarble = Convert.ToInt32(parts[1]) * factor;
MarbleGame marbleGame = new();
@@ -86,14 +86,14 @@ public class Day09 : IDay
public class Marble
{
public long Value { get; set; }
public long Value { get; init; }
public Marble Previous { get; set; }
public Marble Next { get; set; }
}
public class MarbleGame
{
public Dictionary<long, long> Scores { get; } = new();
private Dictionary<long, long> Scores { get; } = new();
private Marble _firstMarble;
private Marble _currentMarble;
@@ -141,20 +141,15 @@ public class Day09 : IDay
}
}
public void PrintStatus()
private void PrintStatus()
{
Console.Write("[{0}] ", _currentPlayer);
Marble marble = _firstMarble;
do
{
if (_currentMarble.Value == marble.Value)
{
Console.Write("({0}) ", marble.Value);
}
else
{
Console.Write("{0} ", marble.Value);
}
Console.Write(_currentMarble.Value == marble.Value
? "({0}) "
: "{0} ", marble.Value);
marble = marble.Next;
} while (marble.Value != 0);
Console.WriteLine();

View File

@@ -156,13 +156,13 @@ Impressed by your sub-hour communication capabilities, the Elves are curious: ex
public class Day10 : IDay
{
public int Width { get; set; } = 65;
public int Height { get; set; } = 12;
public int Width { get; init; } = 65;
public int Height { get; init; } = 12;
public string ResolvePart1(string[] inputs)
{
LightField lightField = new(inputs);
int t = lightField.SearchSmallerBoundindBox();
int t = lightField.SearchSmallerBoundingBox();
string result = lightField.Render(t, Width, Height);
return result;
}
@@ -170,20 +170,20 @@ public class Day10 : IDay
public string ResolvePart2(string[] inputs)
{
LightField lightField = new(inputs);
int t = lightField.SearchSmallerBoundindBox();
int t = lightField.SearchSmallerBoundingBox();
return t.ToString();
}
public class LightPoint
{
public int X { get; set; }
public int Y { get; set; }
public int VX { get; set; }
public int VY { get; set; }
private int X { get; init; }
private int Y { get; init; }
private int VX { get; init; }
private int VY { get; init; }
public static LightPoint FromString(string strPoint)
{
string[] parts = strPoint.Split(new[] { "position=<", " ", ",", "> velocity=<", ">" }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = strPoint.Split(["position=<", " ", ",", "> velocity=<", ">"], StringSplitOptions.RemoveEmptyEntries);
LightPoint point = new() {
X = Convert.ToInt32(parts[0]),
Y = Convert.ToInt32(parts[1]),
@@ -204,16 +204,11 @@ public class Day10 : IDay
}
}
public class LightField
private class LightField(string[] strPoints)
{
private readonly List<LightPoint> _points;
private readonly List<LightPoint> _points = strPoints.Select(LightPoint.FromString).ToList();
public LightField(string[] strPoints)
{
_points = strPoints.Select(strPoint => LightPoint.FromString(strPoint)).ToList();
}
public int SearchSmallerBoundindBox()
public int SearchSmallerBoundingBox()
{
int minHeight = int.MaxValue;
int minT = 0;
@@ -288,14 +283,7 @@ public class Day10 : IDay
sb.AppendLine();
for (int i = 0; i < width; i++)
{
if (field[i, j] > 0)
{
sb.Append("#");
}
else
{
sb.Append(".");
}
sb.Append(field[i, j] > 0 ? "#" : ".");
}
}
return sb.ToString();

View File

@@ -190,7 +190,7 @@ public class Day11 : IDay
return powerLevel;
}
public static void SearchBestRegion(int width, int height, int serial, out int x, out int y, out int size)
private static void SearchBestRegion(int width, int height, int serial, out int x, out int y, out int size)
{
int[,] summationFiled = GenerateSumationField(width, height, serial);
int bestPowerLevel = int.MinValue;

View File

@@ -96,20 +96,20 @@ public class Day12 : IDay
private class PlantRule
{
public bool Minus2 { get; set; }
public bool Minus1 { get; set; }
public bool Current { get; set; }
public bool Plus1 { get; set; }
public bool Plus2 { get; set; }
public bool Minus2 { get; init; }
public bool Minus1 { get; init; }
public bool Current { get; init; }
public bool Plus1 { get; init; }
public bool Plus2 { get; init; }
public bool Result { get; set; }
public bool Result { get; init; }
}
private const int SideMargin = 5;
private const int SideProcessMargin = 2;
private List<bool> _initialState = new();
private List<PlantRule> _rules = new();
private readonly List<bool> _initialState = [];
private readonly List<PlantRule> _rules = [];
private long _offsetField;
private bool[] _field;
private bool[] _workField;
@@ -126,9 +126,8 @@ public class Day12 : IDay
for (int i = 2; i < inputs.Length; i++)
{
if (string.IsNullOrEmpty(inputs[i])) { continue; }
string[] parts = inputs[i].Split(new[] { " => " }, StringSplitOptions.RemoveEmptyEntries);
_rules.Add(new PlantRule
{
string[] parts = inputs[i].Split([" => "], StringSplitOptions.RemoveEmptyEntries);
_rules.Add(new PlantRule {
Minus2 = (parts[0][0] == '#'),
Minus1 = (parts[0][1] == '#'),
Current = (parts[0][2] == '#'),
@@ -151,9 +150,7 @@ public class Day12 : IDay
private void SwapFields()
{
bool[] aux = _field;
_field = _workField;
_workField = aux;
(_field, _workField) = (_workField, _field);
}
private void RecenterField()
@@ -236,8 +233,7 @@ public class Day12 : IDay
rule.Minus1 == minus1 &&
rule.Current == current &&
rule.Plus1 == plus1 &&
rule.Plus2 == plus2 &&
true
rule.Plus2 == plus2
)
{
result = rule.Result;

View File

@@ -372,7 +372,7 @@ public class Day13 : IDay
private int _width;
private int _height;
private char[,] _grid;
private List<Train> _trains = new();
private readonly List<Train> _trains = [];
private void Initialize(string[] inputs)
{
@@ -387,8 +387,7 @@ public class Day13 : IDay
char cell = inputs[j][i];
if (cell == '^')
{
_trains.Add(new Train
{
_trains.Add(new Train {
X = i,
Y = j,
Direction = TrainDirection.North,
@@ -398,8 +397,7 @@ public class Day13 : IDay
}
if (cell == 'v')
{
_trains.Add(new Train
{
_trains.Add(new Train {
X = i,
Y = j,
Direction = TrainDirection.South,
@@ -409,8 +407,7 @@ public class Day13 : IDay
}
if (cell == '<')
{
_trains.Add(new Train
{
_trains.Add(new Train {
X = i,
Y = j,
Direction = TrainDirection.West,
@@ -420,8 +417,7 @@ public class Day13 : IDay
}
if (cell == '>')
{
_trains.Add(new Train
{
_trains.Add(new Train {
X = i,
Y = j,
Direction = TrainDirection.East,
@@ -502,5 +498,4 @@ public class Day13 : IDay
Console.WriteLine();
}
}
}

View File

@@ -377,18 +377,18 @@ public class Day15 : IDay
{
public enum EntityType { Elf, Goblin, }
public bool Show { get; set; } = false;
private bool Show { get; set; } = false;
public class Entity
{
public const int GoblinAttackPower = 3;
private const int GoblinAttackPower = 3;
public static int ElfAttackPower { get; set; } = 3;
public const int InitialHealth = 200;
private const int InitialHealth = 200;
public EntityType Type { get; set; }
public EntityType Type { get; init; }
public int X { get; set; }
public int Y { get; set; }
public int Health { get; set; } = InitialHealth;
public int Health { get; private set; } = InitialHealth;
public bool IsAlive()
{
@@ -401,18 +401,17 @@ public class Day15 : IDay
(other.X + 1 == X && other.Y == Y) ||
(other.X - 1 == X && other.Y == Y) ||
(other.X == X && other.Y + 1 == Y) ||
(other.X == X && other.Y - 1 == Y) ||
false
(other.X == X && other.Y - 1 == Y)
)
{
return true;
}
return false;
}
public void Attack(char[,] map, Entity other)
{
if(Type == EntityType.Elf)
if (Type == EntityType.Elf)
{
other.Health -= ElfAttackPower;
}
@@ -435,13 +434,12 @@ public class Day15 : IDay
}
}
public class Target
private class Target
{
public int X { get; set; }
public int Y { get; set; }
public int X { get; init; }
public int Y { get; init; }
public int Distance { get; set; }
public int Priority { get; set; }
public Entity Entity { get; set; }
public int Priority { get; init; }
}
private int _width;
@@ -450,7 +448,7 @@ public class Day15 : IDay
private List<Entity> _entities;
private BreadthFirstSearchGrid _search;
private int _rounds;
private void Init(string[] inputs)
{
_height = inputs.Length;
@@ -473,8 +471,7 @@ public class Day15 : IDay
}
else if (cell == 'E')
{
_entities.Add(new Entity
{
_entities.Add(new Entity {
Type = EntityType.Elf,
X = i,
Y = j,
@@ -483,8 +480,7 @@ public class Day15 : IDay
}
else if (cell == 'G')
{
_entities.Add(new Entity
{
_entities.Add(new Entity {
Type = EntityType.Goblin,
X = i,
Y = j,
@@ -505,7 +501,7 @@ public class Day15 : IDay
.ThenBy(e => e.X);
}
public IEnumerable<Entity> GetTargetEntities(Entity entity)
private IEnumerable<Entity> GetTargetEntities(Entity entity)
{
return _entities
.Where(e => e.IsAlive() && e.Type != entity.Type)
@@ -513,30 +509,28 @@ public class Day15 : IDay
.ThenBy(e => e.X);
}
public Entity GetBestInRangeTarget(Entity entity, IEnumerable<Entity> targets)
private Entity GetBestInRangeTarget(Entity entity, IEnumerable<Entity> targets)
{
return targets
.Where(e => entity.InRangeOf(e))
.Where(entity.InRangeOf)
.OrderBy(e => e.Health)
.ThenBy(e => e.Y)
.ThenBy(e => e.X)
.FirstOrDefault();
}
private void AddTarget(List<Target> targets, int targetX, int targetY, int priority, Entity entity)
private void AddTarget(List<Target> targets, int targetX, int targetY, int priority)
{
if (targetX >= 0 && targetX < _width && targetY >= 0 && targetY < _height && _map[targetX, targetY] == '.')
{
int distance = _search.QueryDistance(targetX, targetY);
if (distance >= 0)
{
targets.Add(new Target
{
targets.Add(new Target {
X = targetX,
Y = targetY,
Distance = distance,
Priority = priority,
Entity = entity,
});
}
}
@@ -552,7 +546,7 @@ public class Day15 : IDay
foreach (Entity entity in entities)
{
if (entity.IsAlive() == false) { continue; }
IEnumerable<Entity> entitiesTargets = GetTargetEntities(entity);
IEnumerable<Entity> entitiesTargets = GetTargetEntities(entity).ToList();
if (entitiesTargets.Any() == false)
{
running = false;
@@ -573,19 +567,18 @@ public class Day15 : IDay
int priority = 0;
foreach (Entity entityTarget in entitiesTargets)
{
AddTarget(targets, entityTarget.X, entityTarget.Y - 1, priority++, entityTarget);
AddTarget(targets, entityTarget.X - 1, entityTarget.Y, priority++, entityTarget);
AddTarget(targets, entityTarget.X + 1, entityTarget.Y, priority++, entityTarget);
AddTarget(targets, entityTarget.X, entityTarget.Y + 1, priority++, entityTarget);
AddTarget(targets, entityTarget.X, entityTarget.Y - 1, priority++);
AddTarget(targets, entityTarget.X - 1, entityTarget.Y, priority++);
AddTarget(targets, entityTarget.X + 1, entityTarget.Y, priority++);
AddTarget(targets, entityTarget.X, entityTarget.Y + 1, priority++);
}
Target bestTarget = targets.OrderBy(t => t.Distance).ThenBy(t => t.Priority).FirstOrDefault();
if (bestTarget != null)
{
_search.SearchCharGrid(_map, '.', bestTarget.X, bestTarget.Y);
targets.Clear();
Target dirTarget;
dirTarget = new Target { X = entity.X, Y = entity.Y - 1, Priority = 0, };
Target dirTarget = new() { X = entity.X, Y = entity.Y - 1, Priority = 0, };
dirTarget.Distance = _search.QueryDistance(dirTarget.X, dirTarget.Y);
if (dirTarget.Distance >= 0) targets.Add(dirTarget);
@@ -609,7 +602,7 @@ public class Day15 : IDay
{
throw new Exception("No possible direction");
}
entity.MoveTo(_map, finalTarget.X, finalTarget.Y);
// Attack
@@ -620,10 +613,10 @@ public class Day15 : IDay
}
}
}
if(running == false) { break; }
if (running == false) { break; }
_rounds++;
if (Show) { PrintBattlefield(); }
} while (running);
} while (true);
if (Show) { PrintBattlefield(); }
}
@@ -637,7 +630,8 @@ public class Day15 : IDay
{
Console.Write(_map[i, j]);
}
IEnumerable<Entity> entitiesOnLine = _entities.Where(e => e.IsAlive() && e.Y == j).OrderBy(e => e.X);
int j1 = j;
IEnumerable<Entity> entitiesOnLine = _entities.Where(e => e.IsAlive() && e.Y == j1).OrderBy(e => e.X);
foreach (Entity entity in entitiesOnLine)
{
Console.Write(" {0}({1})", (entity.Type == EntityType.Elf) ? 'E' : 'G', entity.Health);
@@ -683,16 +677,15 @@ public class Day15 : IDay
private class BFSCell
{
public bool Visited { get; set; }
public BFSCell CameFrom { get; set; }
public int Distance { get; set; } = -1;
public int X { get; set; }
public int Y { get; set; }
public int X { get; init; }
public int Y { get; init; }
}
private readonly BFSCell[,] _grid;
private readonly int _width;
private readonly int _height;
public BreadthFirstSearchGrid(int width, int height)
{
_grid = new BFSCell[width, height];
@@ -707,15 +700,14 @@ public class Day15 : IDay
}
}
public void Reset()
private void Reset()
{
for(int j =0;j< _height; j++)
for (int j = 0; j < _height; j++)
{
for(int i = 0; i < _width; i++)
for (int i = 0; i < _width; i++)
{
BFSCell cell = _grid[i, j];
cell.Visited = false;
cell.CameFrom = null;
cell.Distance = -1;
}
}
@@ -724,7 +716,7 @@ public class Day15 : IDay
private void ProcessCell(char[,] grid, char empty, Queue<BFSCell> frontier, BFSCell current, int nextX, int nextY)
{
if (nextX < 0 || nextX >= _width || nextY < 0 || nextY >= _height) { return; }
if (grid[nextX, nextY] == empty || current== null)
if (grid[nextX, nextY] == empty || current == null)
{
BFSCell cell = _grid[nextX, nextY];
if (cell.Visited == false)
@@ -732,7 +724,6 @@ public class Day15 : IDay
frontier.Enqueue(cell);
cell.Visited = true;
cell.Distance = (current?.Distance ?? -1) + 1;
cell.CameFrom = current;
}
}
}

View File

@@ -160,17 +160,11 @@ public class Day16 : IDay
private readonly List<ChronoInstruction> _instructions;
private class ChronoInstruction
private class ChronoInstruction(string opName, Action<int, int, int> opFunc)
{
public int OpCode { get; set; } = -1;
public string OpName { get; }
public Action<int, int, int> OpFunc { get; }
public ChronoInstruction(string opName, Action<int, int, int> opFunc)
{
OpName = opName;
OpFunc = opFunc;
}
public string OpName { get; } = opName;
public Action<int, int, int> OpFunc { get; } = opFunc;
public Dictionary<int, int> OpCodeHistogram { get; } = new();
@@ -191,7 +185,7 @@ public class Day16 : IDay
public ChronoMachine()
{
_registers = new int[4];
_instructions = new List<ChronoInstruction> {
_instructions = [
new("addr", Op_AddR),
new("addi", Op_AddI),
new("mulr", Op_MulR),
@@ -208,7 +202,7 @@ public class Day16 : IDay
new("eqir", Op_EqIR),
new("eqri", Op_EqRI),
new("eqrr", Op_EqRR),
};
];
}
public void ResetRegisters()
@@ -341,7 +335,7 @@ public class Day16 : IDay
public void InitOpCodes(bool debug = false)
{
if(debug)
if (debug)
{
foreach (ChronoInstruction instruction in _instructions)
{
@@ -374,7 +368,7 @@ public class Day16 : IDay
instruction.OpCode = opCode;
_dictInstructions.Add(opCode, instruction);
if(debug) { Console.WriteLine($"{instruction.OpName}: {instruction.OpCode}"); }
if (debug) { Console.WriteLine($"{instruction.OpName}: {instruction.OpCode}"); }
}
}
}

View File

@@ -69,7 +69,7 @@ public class Day23 : IDay
{
List<NanoBot> nanoBots = NanoBot.ListFromStrings(inputs);
NanoBot bestNanoBot = nanoBots.OrderBy(nanoBot => nanoBot.Range).LastOrDefault();
int countInRange = nanoBots.Where(nanoBot => bestNanoBot.InRange(nanoBot)).Count();
int countInRange = nanoBots.Count(nanoBot => bestNanoBot.InRange(nanoBot));
return countInRange.ToString();
}
@@ -82,7 +82,7 @@ public class Day23 : IDay
long minX = long.MaxValue;
long minY = long.MaxValue;
long minZ = long.MaxValue;
foreach(NanoBot nanoBot in nanoBots)
foreach (NanoBot nanoBot in nanoBots)
{
if (nanoBot.X < minX) { minX = nanoBot.X; }
if (nanoBot.X > maxX) { maxX = nanoBot.X; }
@@ -95,7 +95,7 @@ public class Day23 : IDay
long sizeY = maxY - minY;
long sizeZ = maxZ - minZ;
long scale = Math.Min(sizeX, Math.Min(sizeY, sizeZ));
do
{
scale /= 2;
@@ -112,11 +112,11 @@ public class Day23 : IDay
for (long i = minX; i <= maxX; i += scale)
{
int count = 0;
foreach(NanoBot nanoBot in nanoBots)
foreach (NanoBot nanoBot in nanoBots)
{
if (nanoBot.InRange(i, j, k, scale)) { count++; }
}
if(count> bestCount)
if (count > bestCount)
{
bestX = i;
bestY = j;
@@ -134,7 +134,7 @@ public class Day23 : IDay
minZ = bestZ - scale;
maxZ = bestZ + scale;
if(scale == 1)
if (scale == 1)
{
long distance = bestX + bestY + bestZ;
return distance.ToString();
@@ -145,14 +145,14 @@ public class Day23 : IDay
public class NanoBot
{
public long X { get; set; }
public long Y { get; set; }
public long Z { get; set; }
public long Range { get; set; }
public long X { get; private init; }
public long Y { get; private init; }
public long Z { get; private init; }
public long Range { get; private init; }
public static NanoBot FromString(string strInput)
private static NanoBot FromString(string strInput)
{
string[] parts = strInput.Split(new[] { "pos=<", ",", ">, r=", }, StringSplitOptions.RemoveEmptyEntries);
string[] parts = strInput.Split(["pos=<", ",", ">, r="], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 4) { return null; }
NanoBot nanoBot = new() {
X = Convert.ToInt64(parts[0]),
@@ -166,18 +166,18 @@ public class Day23 : IDay
public static List<NanoBot> ListFromStrings(string[] inputs)
{
List<NanoBot> nanoBots = inputs
.Select(strInput => FromString(strInput))
.Select(FromString)
.Where(nanoBot => nanoBot != null)
.ToList();
return nanoBots;
}
public long ManhattanDistance(NanoBot other)
private long ManhattanDistance(NanoBot other)
{
return ManhattanDistance(other.X, other.Y, other.Z);
}
public long ManhattanDistance(long x, long y, long z)
private long ManhattanDistance(long x, long y, long z)
{
long distance = Math.Abs(X - x) + Math.Abs(Y - y) + Math.Abs(Z - z);
return distance;