ben
/
aoc
1
0
Fork 0

apply editorconfig
continuous-integration/drone/push Build is passing Details

This commit is contained in:
Ben Harris 2023-12-01 02:30:47 -05:00
parent 23c4854938
commit e0699f49ee
109 changed files with 689 additions and 658 deletions

270
.editorconfig Normal file
View File

@ -0,0 +1,270 @@
# Remove the line below if you want to inherit .editorconfig settings from higher directories
root = true
# C# files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_size = 4
indent_style = tab
tab_width = 4
# New line preferences
end_of_line = crlf
insert_final_newline = false
#### .NET Coding Conventions ####
# Organize usings
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = false
file_header_template = unset
# this. and Me. preferences
dotnet_style_qualification_for_event = false
dotnet_style_qualification_for_field = false
dotnet_style_qualification_for_method = false
dotnet_style_qualification_for_property = false
# Language keywords vs BCL types preferences
dotnet_style_predefined_type_for_locals_parameters_members = true
dotnet_style_predefined_type_for_member_access = true
# Parentheses preferences
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_operators = never_if_unnecessary
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
# Modifier preferences
dotnet_style_require_accessibility_modifiers = for_non_interface_members
# Expression-level preferences
dotnet_style_coalesce_expression = true
dotnet_style_collection_initializer = true
dotnet_style_explicit_tuple_names = true
dotnet_style_namespace_match_folder = true
dotnet_style_null_propagation = true
dotnet_style_object_initializer = true
dotnet_style_operator_placement_when_wrapping = beginning_of_line
dotnet_style_prefer_auto_properties = true
dotnet_style_prefer_collection_expression = true
dotnet_style_prefer_compound_assignment = true
dotnet_style_prefer_conditional_expression_over_assignment = true
dotnet_style_prefer_conditional_expression_over_return = true
dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed
dotnet_style_prefer_inferred_anonymous_type_member_names = true
dotnet_style_prefer_inferred_tuple_names = true
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
dotnet_style_prefer_simplified_boolean_expressions = true
dotnet_style_prefer_simplified_interpolation = true
# Field preferences
dotnet_style_readonly_field = true
# Parameter preferences
dotnet_code_quality_unused_parameters = all
# Suppression preferences
dotnet_remove_unnecessary_suppression_exclusions = none
# New line preferences
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = false
#### C# Coding Conventions ####
# var preferences
csharp_style_var_elsewhere = true:silent
csharp_style_var_for_built_in_types = true:silent
csharp_style_var_when_type_is_apparent = true:silent
# Expression-bodied members
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_constructors = true:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_lambdas = true:silent
csharp_style_expression_bodied_local_functions = true:silent
csharp_style_expression_bodied_methods = true:silent
csharp_style_expression_bodied_operators = true:silent
csharp_style_expression_bodied_properties = true:silent
# Pattern matching preferences
csharp_style_pattern_matching_over_as_with_null_check = true:suggestion
csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion
csharp_style_prefer_extended_property_pattern = true:suggestion
csharp_style_prefer_not_pattern = true:suggestion
csharp_style_prefer_pattern_matching = true:silent
csharp_style_prefer_switch_expression = true:suggestion
# Null-checking preferences
csharp_style_conditional_delegate_call = true:suggestion
# Modifier preferences
csharp_prefer_static_local_function = true:suggestion
csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async
csharp_style_prefer_readonly_struct = true:suggestion
csharp_style_prefer_readonly_struct_member = true:suggestion
# Code-block preferences
csharp_prefer_braces = true:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_style_namespace_declarations = file_scoped:silent
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_primary_constructors = true:suggestion
csharp_style_prefer_top_level_statements = true:silent
# Expression-level preferences
csharp_prefer_simple_default_expression = true:suggestion
csharp_style_deconstructed_variable_declaration = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
csharp_style_inlined_variable_declaration = true:suggestion
csharp_style_prefer_index_operator = true:suggestion
csharp_style_prefer_local_over_anonymous_function = true:suggestion
csharp_style_prefer_null_check_over_type_check = true:suggestion
csharp_style_prefer_range_operator = true:suggestion
csharp_style_prefer_tuple_swap = true:suggestion
csharp_style_prefer_utf8_string_literals = true:suggestion
csharp_style_throw_expression = true:suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
csharp_style_unused_value_expression_statement_preference = discard_variable:silent
# 'using' directive preferences
csharp_using_directive_placement = outside_namespace:silent
# New line preferences
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true:silent
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = true:silent
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:silent
csharp_style_allow_embedded_statements_on_same_line_experimental = true:silent
#### C# Formatting Rules ####
# New line preferences
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
# Indentation preferences
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = true
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
# Space preferences
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_name_and_open_parenthesis = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false
# Wrapping preferences
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
[*.{cs,vb}]
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
end_of_line = lf
dotnet_style_coalesce_expression = true:suggestion
dotnet_style_null_propagation = true:suggestion
dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
dotnet_style_prefer_auto_properties = true:silent
dotnet_style_object_initializer = true:suggestion
dotnet_style_prefer_collection_expression = true:suggestion
dotnet_style_collection_initializer = true:suggestion
dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
dotnet_style_prefer_conditional_expression_over_assignment = true:silent
dotnet_style_prefer_conditional_expression_over_return = true:silent
dotnet_style_explicit_tuple_names = true:suggestion
dotnet_style_prefer_inferred_tuple_names = true:suggestion
dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion
dotnet_style_prefer_compound_assignment = true:suggestion
dotnet_style_prefer_simplified_interpolation = true:suggestion
dotnet_style_namespace_match_folder = true:suggestion
indent_style = space
insert_final_newline = true
dotnet_style_readonly_field = true:suggestion
dotnet_style_predefined_type_for_locals_parameters_members = true:silent
dotnet_style_predefined_type_for_member_access = true:silent
dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent
dotnet_style_allow_multiple_blank_lines_experimental = false:silent
dotnet_style_allow_statement_immediately_after_block_experimental = false:silent
dotnet_code_quality_unused_parameters = all:suggestion
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent
dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent
dotnet_style_qualification_for_field = false:silent
dotnet_style_qualification_for_property = false:silent
dotnet_style_qualification_for_method = false:silent
dotnet_style_qualification_for_event = false:silent

View File

@ -16,7 +16,7 @@ public abstract class Day(int year, int day, string puzzleName)
public static bool UseTestInput { get; set; }
private readonly Stopwatch _stopwatch = new();
public abstract void ProcessInput();
public abstract object Part1();
public abstract object Part2();

View File

@ -31,8 +31,8 @@ public static class Extensions
result[i] = new T[array.Length];
for (var i = 0; i < array.Length; i++)
for (var j = 0; j < array[i].Length; j++)
result[i][j] = array[array.Length - j - 1][i];
for (var j = 0; j < array[i].Length; j++)
result[i][j] = array[array.Length - j - 1][i];
return result;
}

View File

@ -20,7 +20,7 @@ public class Tree<T>(Tree<T>.Node root)
{
public Node? Parent { get; private set; } = parent;
public T Data { get; set; } = data;
private List<Node?> Children { get; } = new();
private List<Node?> Children { get; } = [];
public Node? Left
{

View File

@ -6,14 +6,14 @@ public static class Common
{
Day.UseTestInput = testInput;
var day = Activator.CreateInstance(dayType) as Day;
Assert.IsNotNull(day, "Failed to instantiate day object");
Assert.IsTrue(File.Exists(day.FileName), $"File.Exists(day.FileName) {day.FileName}");
var s = Stopwatch.StartNew();
day.ProcessInput();
s.Stop();
Console.WriteLine(
$"{day.Year} Day {day.DayNumber,2}: {day.PuzzleName,-40} {s.ScaleMilliseconds()} ms elapsed processing input");

View File

@ -7,7 +7,7 @@ public class Test2015
{
[DataTestMethod]
[DataRow(typeof(Day01), "232", "1783")]
[DataRow(typeof(Day02),"1586300", "3737498")]
[DataRow(typeof(Day02), "1586300", "3737498")]
[DataRow(typeof(Day03), "2081", "2341")]
[DataRow(typeof(Day04), "346386", "9958218")]
[DataRow(typeof(Day05), "258", "53")]

View File

@ -16,7 +16,7 @@ public class Test2016
""";
[DataTestMethod]
[DataRow(typeof(Day01), "300", "159")]
[DataRow(typeof(Day02), "76792", "A7AC3")]

View File

@ -9,9 +9,9 @@ public class Test2023
[DataRow(typeof(Day01), "54331", "54518")]
public void CheckAllDays(Type dayType, string part1, string part2) =>
Common.CheckDay(dayType, part1, part2);
[DataTestMethod]
[DataRow(typeof(Day01), "142", "142")] // unfortunately p2 example is different
public void CheckTestInputs(Type dayType, string part1, string part2) =>
Common.CheckDay(dayType, part1, part2, true);
}
}

View File

@ -7,19 +7,16 @@ public sealed class Day02() : Day(2015, 2, "I Was Told There Would Be No Math")
{
private List<List<int>>? _gifts;
public override void ProcessInput()
{
public override void ProcessInput() =>
_gifts = Input.Select(line => line.Split('x').Select(int.Parse).ToList()).ToList();
}
public override object Part1()
{
return _gifts!.Sum(gift =>
public override object Part1() =>
_gifts!.Sum(gift =>
{
var biggestDimension = gift.IndexOf(gift.Max());
var surfaceArea = 2 * gift[0] * gift[1] + 2 * gift[1] * gift[2] + 2 * gift[0] * gift[2];
var smallestSideArea = 1;
for (var i = 0; i < gift.Count; i++)
{
@ -29,11 +26,9 @@ public sealed class Day02() : Day(2015, 2, "I Was Told There Would Be No Math")
return surfaceArea + smallestSideArea;
});
}
public override object Part2()
{
return _gifts!.Sum(gift =>
public override object Part2() =>
_gifts!.Sum(gift =>
{
var biggestDimension = gift.IndexOf(gift.Max());
var bowArea = gift.Aggregate(1, (i, i1) => i * i1);
@ -47,6 +42,4 @@ public sealed class Day02() : Day(2015, 2, "I Was Told There Would Be No Math")
return smallestSide + bowArea;
});
}
}

View File

@ -12,7 +12,7 @@ public sealed class Day03() : Day(2015, 3, "Perfectly Spherical Houses in a Vacu
public override object Part1()
{
int x = 0, y = 0;
Dictionary<(int x, int y), int> map = new() { [(0, 0)] = 1 };
Dictionary<(int x, int y), int> map = new() { [(0, 0)] = 1 };
foreach (var c in Input.First())
{

View File

@ -9,10 +9,7 @@ public sealed class Day04() : Day(2015, 4, "The Ideal Stocking Stuffer")
{
private string? _key;
public override void ProcessInput()
{
_key = Input.First();
}
public override void ProcessInput() => _key = Input.First();
public override object Part1()
{

View File

@ -5,8 +5,8 @@ namespace AOC2015;
/// </summary>
public sealed partial class Day05() : Day(2015, 5, "Doesn't He Have Intern-Elves For This?")
{
private static readonly List<char> Vowels = new() { 'a', 'e', 'i', 'o', 'u' };
private List<string> _strings = new();
private static readonly List<char> Vowels = ['a', 'e', 'i', 'o', 'u'];
private List<string> _strings = [];
[GeneratedRegex(@"(.)\1")]
private static partial Regex DoubleLetter();
@ -17,10 +17,8 @@ public sealed partial class Day05() : Day(2015, 5, "Doesn't He Have Intern-Elves
[GeneratedRegex(@"(..).*\1")]
private static partial Regex TwoPairs();
public override void ProcessInput()
{
public override void ProcessInput() =>
_strings = Input.Where(line => !string.IsNullOrEmpty(line)).ToList();
}
public override object Part1() =>
_strings.Count(s =>

View File

@ -5,8 +5,8 @@ namespace AOC2015;
/// </summary>
public sealed partial class Day06() : Day(2015, 6, "Probably a Fire Hazard")
{
private readonly Dictionary<(int x, int y), int> _brightnessGrid = new();
private readonly Dictionary<(int x, int y), bool> _lightGrid = new();
private readonly Dictionary<(int x, int y), int> _brightnessGrid = [];
private readonly Dictionary<(int x, int y), bool> _lightGrid = [];
[GeneratedRegex(@"(\d+),(\d+) through (\d+),(\d+)")]
private static partial Regex Coords();

View File

@ -5,8 +5,8 @@ namespace AOC2015;
/// </summary>
public sealed class Day07() : Day(2015, 7, "Some Assembly Required")
{
private readonly Dictionary<string, Func<ushort>> _actions = new();
private readonly Dictionary<string, ushort> _wires = new();
private readonly Dictionary<string, Func<ushort>> _actions = [];
private readonly Dictionary<string, ushort> _wires = [];
public override void ProcessInput()
{

View File

@ -5,7 +5,7 @@ namespace AOC2015;
/// </summary>
public sealed class Day09() : Day(2015, 9, "All in a Single Night")
{
private readonly List<Distance> _distances = new();
private readonly List<Distance> _distances = [];
private int _shortest = int.MaxValue, _longest;
public override void ProcessInput()

View File

@ -7,10 +7,7 @@ public sealed class Day10() : Day(2015, 10, "Elves Look, Elves Say")
{
private string? _seed;
public override void ProcessInput()
{
_seed = Input.First();
}
public override void ProcessInput() => _seed = Input.First();
public override object Part1()
{

View File

@ -7,10 +7,7 @@ public sealed class Day11() : Day(2015, 11, "Corporate Policy")
{
private char[]? _password;
public override void ProcessInput()
{
_password = Input.First().ToCharArray();
}
public override void ProcessInput() => _password = Input.First().ToCharArray();
public override object Part1()
{

View File

@ -5,8 +5,8 @@ namespace AOC2015;
/// </summary>
public sealed class Day13() : Day(2015, 13, "Knights of the Dinner Table")
{
private readonly Dictionary<(string person1, string person2), int> _happinessMap = new();
private readonly List<string> _people = new();
private readonly Dictionary<(string person1, string person2), int> _happinessMap = [];
private readonly List<string> _people = [];
public override void ProcessInput()
{
@ -55,7 +55,7 @@ public sealed class Day13() : Day(2015, 13, "Knights of the Dinner Table")
(item, permutation) => new[] { item }.Concat(permutation).ToList()).ToList();
}
return new() { items };
return [items];
}
private long ComputeHappiness()

View File

@ -7,10 +7,7 @@ public sealed class Day14() : Day(2015, 14, "Reindeer Olympics")
{
private List<Reindeer>? _reindeer;
public override void ProcessInput()
{
_reindeer = Input.Select(i => new Reindeer(i)).ToList();
}
public override void ProcessInput() => _reindeer = Input.Select(i => new Reindeer(i)).ToList();
public override object Part1() =>
_reindeer!.Select(r => r.Fly(2503)).Max();
@ -21,12 +18,14 @@ public sealed class Day14() : Day(2015, 14, "Reindeer Olympics")
.GroupBy(r => r)
.Max(g => g.Count());
private class Reindeer {
private class Reindeer
{
private readonly int _duration;
private readonly int _rest;
private readonly int _speed;
public Reindeer(string input) {
public Reindeer(string input)
{
var p = input.Split(' ');
_speed = int.Parse(p[3]);
_duration = int.Parse(p[6]);

View File

@ -9,9 +9,8 @@ public sealed class Day16() : Day(2015, 16, "Aunt Sue")
{
}
private IEnumerable<string> Common()
{
return Input
private IEnumerable<string> Common() =>
Input
.Select(i => Regex.Replace(i, @": \d\d", ": 9"))
.WhereMatch("children: 3")
.WhereMatch("samoyeds: 2")
@ -19,33 +18,28 @@ public sealed class Day16() : Day(2015, 16, "Aunt Sue")
.WhereMatch("vizslas: 0")
.WhereMatch("cars: 2")
.WhereMatch("perfumes: 1");
}
public override object Part1()
{
return Common()
public override object Part1() =>
Common()
.WhereMatch("cats: 7")
.WhereMatch("trees: 3")
.WhereMatch("pomeranians: 3")
.WhereMatch("goldfish: 5")
.Single()
.Split(' ', ':')[1];
}
public override object Part2()
{
return Common()
public override object Part2() =>
Common()
.WhereMatch("cats: [89]")
.WhereMatch("trees: [4-9]")
.WhereMatch("pomeranians: [012]")
.WhereMatch("goldfish: [0-4]")
.Single()
.Split(' ', ':')[1];
}
}
public static class Day16Extensions
{
public static IEnumerable<string> WhereMatch(this IEnumerable<string> input, string pattern) =>
input.Where(i => !i.Contains(pattern.Split(' ')[0]) || Regex.IsMatch(i, pattern));
}
}

View File

@ -31,7 +31,7 @@ public sealed class Day19() : Day(2015, 19, "Medicine for Rudolph")
public override object Part1()
{
HashSet<string> compounds = new();
HashSet<string> compounds = [];
foreach (var rule in _rules!)
foreach (var match in Regex.EnumerateMatches(_compound, rule[0]))
compounds.Add(_compound!.Remove(match.Index, rule[0].Length).Insert(match.Index, rule[1]));

View File

@ -7,10 +7,8 @@ public sealed class Day20() : Day(2015, 20, "Infinite Elves and Infinite Houses"
{
private int _input;
public override void ProcessInput()
{
public override void ProcessInput() =>
_input = int.Parse(Input.First());
}
public override object Part1()
{

View File

@ -63,12 +63,12 @@ public sealed class Day21() : Day(2015, 21, "RPG Simulator 20XX")
private bool StillAlive(Combination combination)
{
var myDamage = Math.Max(combination.TotalDamage - _boss!["Armor"], 1);
var myDamage = Math.Max(combination.TotalDamage - _boss!["Armor"], 1);
var bossDamagePerTurn = Math.Max(_boss["Damage"] - combination.TotalArmor, 1);
var turnsToLose = PlayerHp / bossDamagePerTurn;
if (PlayerHp % bossDamagePerTurn > 0) turnsToLose++;
var turnsToKillBoss = _boss["Hit Points"] / myDamage;
if (_boss["Hit Points"] % myDamage > 0) turnsToKillBoss++;

View File

@ -7,19 +7,26 @@ namespace AOC2015;
/// </summary>
public sealed class Day22() : Day(2015, 22, "Wizard Simulator 20XX")
{
private static readonly List<Spell> Spells = new()
{
private static readonly List<Spell> Spells =
[
new("Magic Missile", Mana: 53, Damage: 4),
new("Drain", Mana: 73, Damage: 2, Heal: 2),
new("Shield", Mana: 113, Armor: 7, Duration: 6),
new("Poison", Mana: 173, Damage: 3, Duration: 6),
new("Recharge", Mana: 229, ManaCharge: 101, Duration: 5)
};
];
private Dictionary<string, int> _boss;
public record Spell(string Name, int Mana, int Duration = 0, int Damage = 0, int Heal = 0, int Armor = 0,
int ManaCharge = 0);
public record Spell(
string Name,
int Mana,
int Duration = 0,
int Damage = 0,
int Heal = 0,
int Armor = 0,
int ManaCharge = 0
);
public struct GameState(bool HardMode = false, int RoundNumber = 0, int TotalManaSpent = 0, int PlayerHealth = 50,
int PlayerMana = 500, int BossHealth = 0, int BossDamage = 0, Dictionary<Spell, int>? ActiveSpells = null)
@ -92,15 +99,11 @@ public sealed class Day22() : Day(2015, 22, "Wizard Simulator 20XX")
return initialState;
}
public override void ProcessInput()
{
public override void ProcessInput() =>
_boss = Input.ToDictionary(k => k.Split(": ")[0], v => int.Parse(v.Split(": ")[1]));
}
public override object Part1()
{
return ProcessStates(new(BossHealth: _boss["Hit Points"], BossDamage: _boss["Damage"]));
}
public override object Part1() =>
ProcessStates(new(BossHealth: _boss["Hit Points"], BossDamage: _boss["Damage"]));
public override object Part2() => "";
}
}

View File

@ -7,10 +7,7 @@ public sealed class Day01() : Day(2016, 1, "No Time for a Taxicab")
{
private string[]? _moves;
public override void ProcessInput()
{
_moves = Input.First().Split(", ");
}
public override void ProcessInput() => _moves = Input.First().Split(", ");
private enum Direction
{
@ -20,9 +17,8 @@ public sealed class Day01() : Day(2016, 1, "No Time for a Taxicab")
West,
}
private static Direction Turn(Direction current, char newDirection)
{
return current switch
private static Direction Turn(Direction current, char newDirection) =>
current switch
{
Direction.North => newDirection == 'L' ? Direction.West : Direction.East,
Direction.South => newDirection == 'L' ? Direction.East : Direction.West,
@ -30,11 +26,9 @@ public sealed class Day01() : Day(2016, 1, "No Time for a Taxicab")
Direction.West => newDirection == 'L' ? Direction.South : Direction.North,
_ => throw new ArgumentException("invalid direction", nameof(current)),
};
}
private static (int x, int y) Move((int x, int y) coord, Direction direction)
{
return direction switch
private static (int x, int y) Move((int x, int y) coord, Direction direction) =>
direction switch
{
Direction.North => (coord.x, coord.y + 1),
Direction.South => (coord.x, coord.y - 1),
@ -42,7 +36,6 @@ public sealed class Day01() : Day(2016, 1, "No Time for a Taxicab")
Direction.West => (coord.x - 1, coord.y),
_ => (0, 0)
};
}
public override object Part1()
{
@ -61,7 +54,7 @@ public sealed class Day01() : Day(2016, 1, "No Time for a Taxicab")
public override object Part2()
{
HashSet<(int x, int y)> visitedLocations = new();
HashSet<(int x, int y)> visitedLocations = [];
var direction = Direction.North;
var location = (x: 0, y: 0);

View File

@ -11,7 +11,7 @@ public sealed class Day02() : Day(2016, 2, "Bathroom Security")
public override object Part1()
{
List<int> answer = new();
List<int> answer = [];
var location = (x: 1, y: 1);
foreach (var line in Input)
@ -42,7 +42,7 @@ public sealed class Day02() : Day(2016, 2, "Bathroom Security")
{ '\0', '\0', 'D', '\0', '\0' },
};
var location = (x: 0, y: 2);
List<char> answer = new();
List<char> answer = [];
foreach (var line in Input)
{
@ -60,4 +60,4 @@ public sealed class Day02() : Day(2016, 2, "Bathroom Security")
return string.Join("", answer);
}
}
}

View File

@ -7,22 +7,19 @@ public sealed class Day03() : Day(2016, 3, "Squares With Three Sides")
{
private List<int[]> _triangles = null!;
public override void ProcessInput()
{
public override void ProcessInput() =>
_triangles = Input
.Select(line => line.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray())
.ToList();
}
public override object Part1() => _triangles.Count(ValidTriangle);
public override object Part1() =>
_triangles.Count(ValidTriangle);
private static bool ValidTriangle(params int[] triangle)
{
return triangle[0] + triangle[1] > triangle[2] &&
triangle[0] + triangle[2] > triangle[1] &&
triangle[1] + triangle[2] > triangle[0];
}
private static bool ValidTriangle(params int[] triangle) =>
triangle[0] + triangle[1] > triangle[2] &&
triangle[0] + triangle[2] > triangle[1] &&
triangle[1] + triangle[2] > triangle[0];
public override object Part2()
{
@ -36,4 +33,4 @@ public sealed class Day03() : Day(2016, 3, "Squares With Three Sides")
return cnt;
}
}
}

View File

@ -29,19 +29,19 @@ public sealed class Day04() : Day(2016, 4, "Security Through Obscurity")
{
var answer = Name.ToCharArray();
for (var i = 0; i < Name.Length; i++)
for (var l = 0; l < SectorId % 26; l++)
answer[i] = answer[i] == 'z' ? 'a' : (char)(answer[i] + 1);
for (var l = 0; l < SectorId % 26; l++)
answer[i] = answer[i] == 'z' ? 'a' : (char)(answer[i] + 1);
return new(answer);
}
}
public override void ProcessInput()
{
public override void ProcessInput() =>
_rooms = Input.Select(Room.FromRawLine).ToList();
}
public override object Part1() => _rooms.Where(r => r.IsRealRoom()).Sum(r => r.SectorId);
public override object Part1() =>
_rooms.Where(r => r.IsRealRoom()).Sum(r => r.SectorId);
public override object Part2() => _rooms.Single(r => r.DecryptedName().Contains("northpole")).SectorId;
}
public override object Part2() =>
_rooms.Single(r => r.DecryptedName().Contains("northpole")).SectorId;
}

View File

@ -7,10 +7,7 @@ public sealed class Day06() : Day(2016, 6, "Signals and Noise")
{
private List<string>? _input;
public override void ProcessInput()
{
_input = Input.ToList();
}
public override void ProcessInput() => _input = Input.ToList();
public override object Part1()
{

View File

@ -41,10 +41,10 @@ public sealed partial class Day07() : Day(2016, 7, "Internet Protocol Version 7"
private static bool SupportsSsl(string input)
{
foreach (var ip in BracketsRegex().Split(input))
foreach (var aba in CheckAba(ip))
foreach (var m in InsideBracketsRegex().Matches(input).Cast<Match>())
if (m.Value.Contains($"{aba[1]}{aba[0]}{aba[1]}"))
return true;
foreach (var aba in CheckAba(ip))
foreach (var m in InsideBracketsRegex().Matches(input).Cast<Match>())
if (m.Value.Contains($"{aba[1]}{aba[0]}{aba[1]}"))
return true;
return false;
}

View File

@ -54,14 +54,12 @@ public sealed class Day08() : Day(2016, 8, "Two-Factor Authentication")
}
}
public override object Part1()
{
return Input.Where(line => line.StartsWith("rect")).Sum(rect =>
public override object Part1() =>
Input.Where(line => line.StartsWith("rect")).Sum(rect =>
{
var s = rect.Split('x', ' ').Skip(1).Select(int.Parse).ToList();
return s[0] * s[1];
});
}
public override object Part2()
{
@ -94,4 +92,4 @@ public sealed class Day08() : Day(2016, 8, "Two-Factor Authentication")
return Environment.NewLine + PrintGrid(screen);
}
}
}

View File

@ -8,7 +8,7 @@ public sealed class Day22() : Day(2016, 22, "Puzzle Name")
public override void ProcessInput()
{
}
public override object Part1() => "";
public override object Part2() => "";

View File

@ -26,8 +26,8 @@ public sealed class Day02() : Day(2018, 2, "Inventory Management System")
var input = Input.ToImmutableList();
foreach (var id1 in input)
foreach (var id2 in input.Where(line2 => id1.HammingDistance(line2) == 1))
return id1.Remove(id1.Zip(id2).Indexed().First(i => i.Value.First != i.Value.Second).Key, 1);
foreach (var id2 in input.Where(line2 => id1.HammingDistance(line2) == 1))
return id1.Remove(id1.Zip(id2).Indexed().First(i => i.Value.First != i.Value.Second).Key, 1);
throw new("Correct IDs not found");
}

View File

@ -6,26 +6,26 @@ namespace AOC2018;
public sealed partial class Day03() : Day(2018, 3, "No Matter How You Slice It")
{
private List<Claim>? _claims;
private readonly Dictionary<(int x, int y), List<int>> _plots = new();
private readonly Dictionary<(int x, int y), List<int>> _plots = [];
[GeneratedRegex(@"\d+")]
private static partial Regex Digits();
private record Claim(int ID, int X, int Y, int SizeX, int SizeY);
public override void ProcessInput()
{
_claims = Input.Select(line => Digits().Matches(line).Select(m => int.Parse(m.Value)).ToList())
.Select(l => new Claim(l[0], l[1], l[2], l[3], l[4])).ToList();
foreach (var claim in _claims)
{
foreach (var y in Enumerable.Range(claim.X, claim.SizeX))
foreach (var x in Enumerable.Range(claim.Y, claim.SizeY))
{
if (!_plots.ContainsKey((x, y))) _plots.Add((x, y), new());
_plots[(x, y)].Add(claim.ID);
}
foreach (var x in Enumerable.Range(claim.Y, claim.SizeY))
{
if (!_plots.ContainsKey((x, y))) _plots.Add((x, y), []);
_plots[(x, y)].Add(claim.ID);
}
}
}

View File

@ -4,10 +4,8 @@ public sealed class Day01() : Day(2019, 1, "The Tyranny of the Rocket Equation")
{
private IEnumerable<int>? _masses;
public override void ProcessInput()
{
public override void ProcessInput() =>
_masses = Input.Select(int.Parse);
}
private static int FuelCost(int weight) => weight / 3 - 2;

View File

@ -4,10 +4,8 @@ public sealed class Day02() : Day(2019, 2, "1202 Program Alarm")
{
private IEnumerable<int>? _input;
public override void ProcessInput()
{
public override void ProcessInput() =>
_input = Input.First().Split(',').Select(int.Parse);
}
private int RunIntCode(int noun, int verb)
{
@ -26,10 +24,7 @@ public sealed class Day02() : Day(2019, 2, "1202 Program Alarm")
return v[0];
}
public override object Part1()
{
return RunIntCode(12, 2);
}
public override object Part1() => RunIntCode(12, 2);
public override object Part2()
{

View File

@ -5,20 +5,15 @@ public sealed class Day05() : Day(2019, 5, "Sunny with a Chance of Asteroids")
private IEnumerable<int>? _tape;
private int _output;
public override void ProcessInput()
{
public override void ProcessInput() =>
_tape = Input.First().Split(',').Select(int.Parse);
}
private void RunIntCode(IList<int> v, int input)
{
var i = 0;
while (i < v.Count && v[i] != 99)
{
int Val(int mode, int val)
{
return mode != 0 ? val : v[val];
}
int Val(int mode, int val) => mode != 0 ? val : v[val];
var mode1 = v[i] / 100 % 10;
var mode2 = v[i] / 1000;
@ -70,4 +65,4 @@ public sealed class Day05() : Day(2019, 5, "Sunny with a Chance of Asteroids")
RunIntCode(_tape!.ToList(), 5);
return _output;
}
}
}

View File

@ -4,16 +4,14 @@ public sealed class Day06() : Day(2019, 6, "Universal Orbit Map")
{
private Dictionary<string, string>? _input;
public override void ProcessInput()
{
public override void ProcessInput() =>
_input = Input.ToDictionary(i => i.Split(')')[1], i => i.Split(')')[0]);
}
private List<string> GetParents(string obj)
{
var res = new List<string>();
for (var curr = obj; curr != "COM"; curr = _input![curr])
res.Add(curr);
for (var current = obj; current != "COM"; current = _input![current])
res.Add(current);
res.Add("COM");
return res;
}
@ -32,4 +30,4 @@ public sealed class Day06() : Day(2019, 6, "Universal Orbit Map")
return you.Count + san.Count - common * 2;
}
}
}

View File

@ -4,10 +4,8 @@ public sealed class Day08() : Day(2019, 8, "Space Image Format")
{
private List<List<char>>? _photo;
public override void ProcessInput()
{
public override void ProcessInput() =>
_photo = Input.First().Chunk(25 * 6).Select(s => s.ToList()).ToList();
}
public override object Part1()
{
@ -15,9 +13,8 @@ public sealed class Day08() : Day(2019, 8, "Space Image Format")
return l.Count(p => p == '1') * l.Count(p => p == '2');
}
public override object Part2()
{
return Enumerable.Range(0, 25 * 6)
public override object Part2() =>
Enumerable.Range(0, 25 * 6)
.Select(p => Enumerable.Range(0, _photo!.Count)
.Select(l => _photo[l][p])
.Aggregate('2', (acc, next) =>
@ -29,5 +26,4 @@ public sealed class Day08() : Day(2019, 8, "Space Image Format")
.Select(s => new string(s).Trim())
.ToDelimitedString(Environment.NewLine)
.Replace('1', 'x');
}
}
}

View File

@ -4,10 +4,8 @@ public sealed class Day09() : Day(2019, 9, "Sensor Boost")
{
private IntCodeVM? _vm;
public override void ProcessInput()
{
public override void ProcessInput() =>
_vm = new(Input.First());
}
public override object Part1()
{
@ -22,4 +20,4 @@ public sealed class Day09() : Day(2019, 9, "Sensor Boost")
_vm.Run(2);
return _vm.Output.ToDelimitedString(",");
}
}
}

View File

@ -6,15 +6,13 @@ public sealed class Day10() : Day(2019, 10, "Monitoring Station")
private (int x, int y) _best = (x: -1, y: -1);
private int _bestCanSee;
public override void ProcessInput()
{
public override void ProcessInput() =>
_asteroids = Input
.Select((r, y) => r.Select((c, x) => (x, y, isAsteroid: c == '#')).ToArray())
.SelectMany(r => r)
.Where(a => a.isAsteroid)
.Select(a => (a.x, a.y))
.ToHashSet();
}
public override object Part1()
{
@ -63,4 +61,4 @@ public sealed class Day10() : Day(2019, 10, "Monitoring Station")
.Select(a => a.x * 100 + a.y)
.Single();
}
}
}

View File

@ -6,11 +6,17 @@ public sealed class Day11() : Day(2019, 11, "Space Police")
private Direction _heading;
private long _x, _y;
public override void ProcessInput()
private enum Direction
{
_vm = new(Input.First());
Up,
Down,
Left,
Right
}
public override void ProcessInput() =>
_vm = new(Input.First());
private void Move()
{
switch (_heading)
@ -36,9 +42,9 @@ public sealed class Day11() : Day(2019, 11, "Space Police")
{
_heading = _heading switch
{
Direction.Up => direction == 0 ? Direction.Left : Direction.Right,
Direction.Down => direction == 0 ? Direction.Right : Direction.Left,
Direction.Left => direction == 0 ? Direction.Down : Direction.Up,
Direction.Up => direction == 0 ? Direction.Left : Direction.Right,
Direction.Down => direction == 0 ? Direction.Right : Direction.Left,
Direction.Left => direction == 0 ? Direction.Down : Direction.Up,
Direction.Right => direction == 0 ? Direction.Up : Direction.Down,
_ => _heading
};
@ -85,12 +91,4 @@ public sealed class Day11() : Day(2019, 11, "Space Police")
.Reverse()
.ToDelimitedString(Environment.NewLine);
}
private enum Direction
{
Up,
Down,
Left,
Right
}
}

View File

@ -58,9 +58,9 @@ public sealed class Day12() : Day(2019, 12, "The N-Body Problem")
public class Position(IList<int> moon)
{
private List<Position> _siblings = new();
private List<Position> _siblings = [];
private int _x = moon[0], _y = moon[1], _z = moon[2];
public int Dx = 0, Dy = 0, Dz = 0;
public int Dx, Dy, Dz;
private int KineticEnergy =>
Math.Abs(_x) + Math.Abs(_y) + Math.Abs(_z);
@ -94,4 +94,4 @@ public sealed class Day12() : Day(2019, 12, "The N-Body Problem")
_z += Dz;
}
}
}
}

View File

@ -3,13 +3,11 @@ namespace AOC2019;
public sealed class Day13() : Day(2019, 13, "Care Package")
{
private IntCodeVM? _vm;
private readonly Dictionary<(long x, long y), long> _board = new();
private readonly List<(long x, long y)> _updatedCoordinates = new();
private readonly Dictionary<(long x, long y), long> _board = [];
private readonly List<(long x, long y)> _updatedCoordinates = [];
public override void ProcessInput()
{
public override void ProcessInput() =>
_vm = new(Input.First());
}
private void PrintBoard()
{
@ -64,7 +62,7 @@ public sealed class Day13() : Day(2019, 13, "Care Package")
if (printBoard) PrintBoard();
var (ball, _) = _board.Single(t => t.Value == 4).Key;
var (ball, _) = _board.Single(t => t.Value == 4).Key;
var (paddle, _) = _board.Single(t => t.Value == 3).Key;
_vm.AddInput(Math.Sign(ball.CompareTo(paddle)));
@ -73,4 +71,4 @@ public sealed class Day13() : Day(2019, 13, "Care Package")
return $"after {gameTicks} moves, the score is: {_board[(-1, 0)]}";
}
}
}

View File

@ -3,14 +3,12 @@ namespace AOC2019;
public sealed class Day14() : Day(2019, 14, "Space Stoichiometry")
{
private Dictionary<string, Reaction>? _reactions;
private Dictionary<string, long> _available = new();
private Dictionary<string, long> _available = [];
public override void ProcessInput()
{
public override void ProcessInput() =>
_reactions = Input
.Select(Reaction.Parse)
.ToDictionary(r => r.Product.Name);
}
private bool Consume(string chem, long quantity)
{

View File

@ -2,13 +2,11 @@ namespace AOC2019;
public sealed class Day15() : Day(2019, 15, "Oxygen System")
{
private readonly bool _verbose = false;
private const bool Verbose = false;
private IntCodeVM? _vm;
public override void ProcessInput()
{
public override void ProcessInput() =>
_vm = new(Input.First());
}
public override object Part1()
{
@ -54,7 +52,7 @@ public sealed class Day15() : Day(2019, 15, "Oxygen System")
}
else
{
if (_verbose)
if (Verbose)
{
// find extents of canvas
int yMin, yMax;
@ -125,7 +123,7 @@ public sealed class Day15() : Day(2019, 15, "Oxygen System")
private static readonly int[] Dy = { 0, 1, -1, 0, 0 };
public static readonly int[] Opposites = { 0, 2, 1, 4, 3 };
public static readonly Dictionary<(int x, int y), Location> AllLocations = new();
public static readonly Dictionary<(int x, int y), Location> AllLocations = [];
private readonly int _currentType;
@ -156,16 +154,13 @@ public sealed class Day15() : Day(2019, 15, "Oxygen System")
public bool IsWall => _currentType == Wall;
public string Image()
public string Image() => _currentType switch
{
return _currentType switch
{
Wall => "\u2587",
Empty => X == 0 && Y == 0 ? "S" : " ",
System => "O",
_ => "?"
};
}
Wall => "\u2587",
Empty => X == 0 && Y == 0 ? "S" : " ",
System => "O",
_ => "?"
};
public bool UpdateDistanceToOxygenSystem()
{
@ -184,29 +179,14 @@ public sealed class Day15() : Day(2019, 15, "Oxygen System")
return false;
}
public (int, int) Neighbor(int direction)
{
return (X + Dx[direction], Y + Dy[direction]);
}
public (int, int) Neighbor(int direction) => (X + Dx[direction], Y + Dy[direction]);
public (int, int) PreviousLocation()
{
return Neighbor(PreviousDirection);
}
public (int, int) PreviousLocation() => Neighbor(PreviousDirection);
public int NextDirection()
{
return _searchDirection++;
}
public int NextDirection() => _searchDirection++;
public static Location? GetLocation(int x, int y)
{
return AllLocations.ContainsKey((x, y)) ? AllLocations[(x, y)] : null;
}
public static Location? GetLocation(int x, int y) => AllLocations.ContainsKey((x, y)) ? AllLocations[(x, y)] : null;
public static Location? GetLocation((int x, int y) coords)
{
return GetLocation(coords.x, coords.y);
}
public static Location? GetLocation((int x, int y) coords) => GetLocation(coords.x, coords.y);
}
}

View File

@ -5,10 +5,8 @@ public sealed class Day16() : Day(2019, 16, "Flawed Frequency Transmission")
private static readonly int[] BasePattern = { 0, 1, 0, -1 };
private int[]? _initialList;
public override void ProcessInput()
{
public override void ProcessInput() =>
_initialList = Input.First().Select(c => c - '0').ToArray();
}
public override object Part1()
{
@ -49,4 +47,4 @@ public sealed class Day16() : Day(2019, 16, "Flawed Frequency Transmission")
.Take(input.Length)
.Select((pv, i) => pv * input[i] % 10).Sum()) % 10;
}
}
}

View File

@ -4,10 +4,8 @@ public sealed class Day17() : Day(2019, 17, "Set and Forget")
{
private IntCodeVM? _vm;
public override void ProcessInput()
{
public override void ProcessInput() =>
_vm = new(Input.First());
}
public override object Part1()
{
@ -21,19 +19,18 @@ public sealed class Day17() : Day(2019, 17, "Set and Forget")
var sum = 0;
for (var y = 1; y < grid.Length - 1; y++)
for (var x = 1; x < grid[y].Length - 1; x++)
if (grid[y][x] == '#' &&
grid[y - 1][x] == '#' &&
grid[y + 1][x] == '#' &&
grid[y][x - 1] == '#' &&
grid[y][x + 1] == '#')
sum += x * y;
for (var x = 1; x < grid[y].Length - 1; x++)
if (grid[y][x] == '#' &&
grid[y - 1][x] == '#' &&
grid[y + 1][x] == '#' &&
grid[y][x - 1] == '#' &&
grid[y][x + 1] == '#')
sum += x * y;
return sum;
}
public override object Part2()
{
public override object Part2() =>
//vm.Reset();
//vm.memory[0] = 2;
//var halt = IntCodeVM.HaltType.Waiting;
@ -41,6 +38,5 @@ public sealed class Day17() : Day(2019, 17, "Set and Forget")
//{
// halt = vm.Run();
//}
return "";
}
"";
}

View File

@ -6,13 +6,7 @@ public sealed class Day18() : Day(2019, 18, "Many-Worlds Interpretation")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -5,7 +5,8 @@ public sealed class Day19() : Day(2019, 19, "Tractor Beam")
private long[,]? _grid;
private IntCodeVM? _vm;
public override void ProcessInput(){
public override void ProcessInput()
{
_vm = new(Input.First());
_grid = new long[50, 50];
}

View File

@ -6,13 +6,7 @@ public sealed class Day20() : Day(2019, 20, "Donut Maze")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -4,11 +4,9 @@ public sealed class Day21 : Day
{
private readonly IntCodeVM _vm;
public Day21() : base(2019, 21, "Springdroid Adventure")
{
public Day21() : base(2019, 21, "Springdroid Adventure") =>
_vm = new(Input.First());
}
public override void ProcessInput()
{
}
@ -20,8 +18,5 @@ public sealed class Day21 : Day
return "";
}
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -6,13 +6,7 @@ public sealed class Day22() : Day(2019, 22, "Slam Shuffle")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -6,13 +6,7 @@ public sealed class Day24() : Day(2019, 24, "Planet of Discord")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -6,13 +6,7 @@ public sealed class Day25() : Day(2019, 25, "Cryostasis")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -7,10 +7,8 @@ public sealed class Day01() : Day(2020, 1, "Report Repair")
{
private ImmutableHashSet<int>? _entries;
public override void ProcessInput()
{
public override void ProcessInput() =>
_entries = Input.Select(int.Parse).ToImmutableHashSet();
}
public override object Part1()
{
@ -25,7 +23,7 @@ public sealed class Day01() : Day(2020, 1, "Report Repair")
foreach (var k in _entries)
if (i + j + k == 2020)
return i * j * k;
return default!;
}
}

View File

@ -7,10 +7,8 @@ public sealed class Day02() : Day(2020, 2, "Password Philosophy")
{
private ImmutableList<Password>? _passwords;
public override void ProcessInput()
{
public override void ProcessInput() =>
_passwords = Input.Select(p => new Password(p)).ToImmutableList();
}
public override object Part1() =>
_passwords!.Count(p => p.IsValid);

View File

@ -7,10 +7,8 @@ public sealed class Day03() : Day(2020, 3, "Toboggan Trajectory")
{
private string[]? _grid;
public override void ProcessInput()
{
public override void ProcessInput() =>
_grid = Input.ToArray();
}
private long CountSlope(int dx, int dy)
{

View File

@ -7,14 +7,12 @@ public sealed class Day05() : Day(2020, 5, "Binary Boarding")
{
private ImmutableHashSet<int>? _ids;
public override void ProcessInput()
{
public override void ProcessInput() =>
_ids = Input
.Select(s =>
Convert.ToInt32(s.Replace('F', '0').Replace('B', '1').Replace('L', '0').Replace('R', '1'), 2))
.OrderBy(i => i)
.ToImmutableHashSet();
}
public override object Part1() => _ids!.Last();

View File

@ -7,8 +7,7 @@ public sealed class Day07() : Day(2020, 7, "Handy Haversacks")
{
private Dictionary<string, IEnumerable<(int Weight, string Name)?>>? _rules;
public override void ProcessInput()
{
public override void ProcessInput() =>
_rules = Input
.Select(rule =>
{
@ -18,7 +17,6 @@ public sealed class Day07() : Day(2020, 7, "Handy Haversacks")
return (outer, inner);
})
.ToDictionary(t => t.outer, t => t.inner);
}
private static (int, string)? ParseQuantity(string arg)
{

View File

@ -9,10 +9,8 @@ public sealed class Day08() : Day(2020, 8, "Handheld Halting")
private int _accumulator;
private int _currentInstruction;
public override void ProcessInput()
{
public override void ProcessInput() =>
_instructions = Input.Select(ParseLine).ToArray();
}
private static (string, int) ParseLine(string line)
{

View File

@ -8,10 +8,8 @@ public sealed class Day09() : Day(2020, 9, "Encoding Error")
private long[]? _list;
private long _part1;
public override void ProcessInput()
{
public override void ProcessInput() =>
_list = Input.Select(long.Parse).ToArray();
}
public override object Part1()
{

View File

@ -10,8 +10,8 @@ public sealed class Day16() : Day(2020, 16, "Ticket Translation")
public override void ProcessInput()
{
_tickets = new();
_rules = new();
_tickets = [];
_rules = [];
foreach (var line in Input)
{

View File

@ -5,8 +5,8 @@ namespace AOC2020;
/// </summary>
public sealed class Day17() : Day(2020, 17, "Conway Cubes")
{
private readonly Dictionary<(int x, int y, int z), char> _plane = new();
private readonly Dictionary<(int x, int y, int z, int w), char> _plane4 = new();
private readonly Dictionary<(int x, int y, int z), char> _plane = [];
private readonly Dictionary<(int x, int y, int z, int w), char> _plane4 = [];
public override void ProcessInput()
{
@ -103,15 +103,9 @@ public sealed class Day17() : Day(2020, 17, "Conway Cubes")
return next;
}
public override object Part1()
{
var plane = Enumerable.Range(0, 6).Aggregate(_plane, (current, _) => Iterate(current));
return plane.Values.Count(v => v == '#');
}
public override object Part1() =>
Enumerable.Range(0, 6).Aggregate(_plane, (current, _) => Iterate(current)).Values.Count(v => v == '#');
public override object Part2()
{
var plane = Enumerable.Range(0, 6).Aggregate(_plane4, (current, _) => Iterate4(current));
return plane.Values.Count(v => v == '#');
}
}
public override object Part2() =>
Enumerable.Range(0, 6).Aggregate(_plane4, (current, _) => Iterate4(current)).Values.Count(v => v == '#');
}

View File

@ -7,10 +7,8 @@ public sealed class Day18() : Day(2020, 18, "Operation Order")
{
private List<string>? _expressions;
public override void ProcessInput()
{
public override void ProcessInput() =>
_expressions = Input.Select(line => line.Replace(" ", "")).ToList();
}
private static long Calculate(string expr, Func<char, int> precedence)
{

View File

@ -53,29 +53,29 @@ public sealed class Day20() : Day(2020, 20, "Jurassic Jigsaw")
void AddConnection(PuzzlePiece p1, PuzzlePiece p2)
{
if (!connections.ContainsKey(p1)) connections.Add(p1, new());
if (!connections.ContainsKey(p2)) connections.Add(p2, new());
if (!connections.ContainsKey(p1)) connections.Add(p1, []);
if (!connections.ContainsKey(p2)) connections.Add(p2, []);
connections[p1].Add(p2);
connections[p2].Add(p1);
}
foreach (var piece in puzzlePieces)
foreach (var (original, flipped) in piece.SidesWithFlippedPaired.Value)
{
if (sides.TryGetValue(original, out var side))
foreach (var (original, flipped) in piece.SidesWithFlippedPaired.Value)
{
AddConnection(piece, side);
if (sides.TryGetValue(original, out var side))
{
AddConnection(piece, side);
}
else if (sides.TryGetValue(flipped, out var otherPiece))
{
AddConnection(piece, otherPiece);
}
else
{
sides.Add(original, piece);
sides.Add(flipped, piece);
}
}
else if (sides.TryGetValue(flipped, out var otherPiece))
{
AddConnection(piece, otherPiece);
}
else
{
sides.Add(original, piece);
sides.Add(flipped, piece);
}
}
return connections;
}

View File

@ -8,10 +8,7 @@ public sealed class Day22() : Day(2020, 22, "Crab Combat")
private readonly Queue<int> _deck1 = new();
private readonly Queue<int> _deck2 = new();
public override void ProcessInput()
{
Reset();
}
public override void ProcessInput() => Reset();
private void Reset()
{

View File

@ -5,7 +5,7 @@ namespace AOC2020;
/// </summary>
public sealed class Day23() : Day(2020, 23, "Crab Cups")
{
private readonly Dictionary<long, long> _cups = new();
private readonly Dictionary<long, long> _cups = [];
private ImmutableList<long>? _initialCups;
private long[]? _move;
private long _current;

View File

@ -17,15 +17,12 @@ public sealed class Day24() : Day(2020, 24, "Lobby Layout")
private Dictionary<(int q, int r, int s), Tile>? _tiles;
public override void ProcessInput()
{
_tiles = Input
public override void ProcessInput() => _tiles = Input
.Select(Tile.FromLine)
.GroupBy(t => t.Location)
.Where(g => g.Count() % 2 == 1)
.Select(t => t.First())
.ToDictionary(t => t.Location);
}
public override object Part1() => _tiles!.Count;

View File

@ -9,15 +9,6 @@ public sealed class Day25() : Day(2020, 25, "Combo Breaker")
{
}
public override object Part1()
{
var cardKey = int.Parse(Input.First());
var doorKey = int.Parse(Input.Last());
return Transform(doorKey, FindLoopSize(7, cardKey));
}
public override object Part2() => "";
private static long Transform(long subject, int loopSize)
{
var value = 1L;
@ -40,4 +31,13 @@ public sealed class Day25() : Day(2020, 25, "Combo Breaker")
}
return loops;
}
public override object Part1()
{
var cardKey = int.Parse(Input.First());
var doorKey = int.Parse(Input.Last());
return Transform(doorKey, FindLoopSize(7, cardKey));
}
public override object Part2() => "";
}

View File

@ -7,10 +7,8 @@ public sealed class Day01() : Day(2021, 1, "Sonar Sweep")
{
private List<int>? _readings;
public override void ProcessInput()
{
public override void ProcessInput() =>
_readings = Input.Select(int.Parse).ToList();
}
public override object Part1() =>
Enumerable.Range(0, _readings!.Count - 1).Count(i => _readings[i + 1] > _readings[i]);

View File

@ -7,17 +7,15 @@ public sealed class Day03() : Day(2021, 3, "Binary Diagnostic")
{
private List<string>? _report;
public override void ProcessInput()
{
public override void ProcessInput() =>
_report = Input.ToList();
}
public override object Part1()
{
var l = _report!.Count / 2;
var g = new StringBuilder();
var e = new StringBuilder();
foreach (var i in Enumerable.Range(0, _report[0].Length))
{
var ones = _report.Select(r => r[i]).Count(c => c == '1');
@ -25,7 +23,7 @@ public sealed class Day03() : Day(2021, 3, "Binary Diagnostic")
e.Append(ones > l ? '0' : '1');
}
var gamma = g.ToString().BigIntegerFromBinaryString();
var gamma = g.ToString().BigIntegerFromBinaryString();
var epsilon = e.ToString().BigIntegerFromBinaryString();
return gamma * epsilon;
@ -38,7 +36,7 @@ public sealed class Day03() : Day(2021, 3, "Binary Diagnostic")
char MostCommon(int i, IReadOnlyCollection<string> report) =>
report.Count(r => r[i] == '1') >= report.Count / 2.0 ? '1' : '0';
var i = 0;
while (o.Count > 1)
{

View File

@ -12,15 +12,15 @@ public sealed class Day04() : Day(2021, 4, "Giant Squid")
public override void ProcessInput()
{
_call = Input.First().Split(',').Select(int.Parse).ToList();
_boards = new();
_boards = [];
List<int> currentBoard = new();
List<int> currentBoard = [];
foreach (var line in Input.Skip(2))
{
if (string.IsNullOrWhiteSpace(line))
{
_boards.Add(currentBoard);
currentBoard = new();
currentBoard = [];
continue;
}
@ -47,7 +47,7 @@ public sealed class Day04() : Day(2021, 4, "Giant Squid")
public override object Part2()
{
Dictionary<int, bool> wonBoards = new();
Dictionary<int, bool> wonBoards = [];
for (var i = 0; i < _boards!.Count; i++)
wonBoards[i] = false;

View File

@ -10,11 +10,11 @@ public sealed class Day06() : Day(2021, 6, "Lanternfish")
public override void ProcessInput()
{
var fishes = Input.First().Split(',').Select(long.Parse).ToList();
Dictionary<long, long> counts = new();
Dictionary<long, long> counts = [];
for (var i = 0; i <= 8; i++)
counts[i] = fishes.Count(x => x == i);
for (var i = 0; i < 256; i++)
{
var breeders = counts[0];

View File

@ -7,10 +7,8 @@ public sealed class Day07() : Day(2021, 7, "The Treachery of Whales")
{
private List<long>? _tape;
public override void ProcessInput()
{
public override void ProcessInput() =>
_tape = Input.First().Split(',').Select(long.Parse).OrderBy(i => i).ToList();
}
private static long ArithmeticSumTo(long n) => n * (n + 1) / 2L;
@ -24,7 +22,7 @@ public sealed class Day07() : Day(2021, 7, "The Treachery of Whales")
{
var avg = (decimal)_tape!.Sum() / _tape!.Count;
var floor = _tape.Select(t => ArithmeticSumTo(Math.Abs(t - (long)Math.Floor(avg)))).Sum();
var ceil = _tape.Select(t => ArithmeticSumTo(Math.Abs(t - (long)Math.Ceiling(avg)))).Sum();
var ceil = _tape.Select(t => ArithmeticSumTo(Math.Abs(t - (long)Math.Ceiling(avg)))).Sum();
return Math.Min(floor, ceil);
}
}

View File

@ -42,7 +42,7 @@ public sealed class Day08() : Day(2021, 8, "Seven Segment Search")
lit = "0000000".ToCharArray();
foreach (var c in signal)
lit[Array.IndexOf(PossibleMappings[i], c)] = '1';
var match = MatchDigit(new(lit));
if (match == -1)
{
@ -68,7 +68,7 @@ public sealed class Day08() : Day(2021, 8, "Seven Segment Search")
lit = "0000000".ToCharArray();
foreach (var c in o)
lit[Array.IndexOf(PossibleMappings[i], c)] = '1';
digits.Append(MatchDigit(new(lit)));
}

View File

@ -14,21 +14,21 @@ public sealed class Day09() : Day(2021, 9, "Smoke Basin")
public override void ProcessInput()
{
_part1Sum = 0;
_lowPoints = new();
_lowPoints = [];
_map = Input.ToList();
for (var y = 0; y < _map.Count; y++)
for (var x = 0; x < _map[y].Length; x++)
{
var c = _map[y][x];
if (y > 0 && _map[y - 1][x] <= c) continue;
if (y < _map.Count - 1 && _map[y + 1][x] <= c) continue;
if (x > 0 && _map[y][x - 1] <= c) continue;
if (x < _map[y].Length - 1 && _map[y][x + 1] <= c) continue;
for (var x = 0; x < _map[y].Length; x++)
{
var c = _map[y][x];
if (y > 0 && _map[y - 1][x] <= c) continue;
if (y < _map.Count - 1 && _map[y + 1][x] <= c) continue;
if (x > 0 && _map[y][x - 1] <= c) continue;
if (x < _map[y].Length - 1 && _map[y][x + 1] <= c) continue;
_lowPoints.Add((x, y));
_part1Sum += c - '0' + 1;
}
_lowPoints.Add((x, y));
_part1Sum += c - '0' + 1;
}
}
public override object Part1() => _part1Sum;

View File

@ -29,7 +29,7 @@ public sealed class Day10() : Day(2021, 10, "Syntax Scoring")
{ '<', 4 }
};
private readonly List<long> _scores2 = new();
private readonly List<long> _scores2 = [];
private long _score1;

View File

@ -15,12 +15,12 @@ public sealed class Day11() : Day(2021, 11, "Dumbo Octopus")
while (true)
{
_totalTurns++;
// increment all octopuses
for (var row = 0; row < _octopusField.Length; row++)
for (var col = 0; col < _octopusField[row].Length; col++)
_octopusField[row][col]++;
// flash any that exceeded 10
for (var row = 0; row < _octopusField.Length; row++)
for (var col = 0; col < _octopusField[row].Length; col++)
@ -34,7 +34,7 @@ public sealed class Day11() : Day(2021, 11, "Dumbo Octopus")
_octopusField[row][col] = 0;
else
done = false;
if (_totalTurns == 100) _flashesAfter100 = _flashTally;
if (done) break;
}

View File

@ -5,7 +5,7 @@ namespace AOC2021;
/// </summary>
public sealed class Day12() : Day(2021, 12, "Passage Pathing")
{
private readonly Dictionary<string, List<string>> _edges = new();
private readonly Dictionary<string, List<string>> _edges = [];
public override void ProcessInput()
{
@ -14,10 +14,10 @@ public sealed class Day12() : Day(2021, 12, "Passage Pathing")
var s = line.Split('-', 2);
if (_edges.ContainsKey(s[0])) _edges[s[0]].Add(s[1]);
else _edges[s[0]] = new() { s[1] };
else _edges[s[0]] = [s[1]];
if (_edges.ContainsKey(s[1])) _edges[s[1]].Add(s[0]);
else _edges[s[1]] = new() { s[0] };
else _edges[s[1]] = [s[0]];
}
}
@ -49,14 +49,14 @@ public sealed class Day12() : Day(2021, 12, "Passage Pathing")
return true;
if (seen.GetValueOrDefault("_twice", false))
return false;
seen["_twice"] = true;
return true;
}
public override object Part1() =>
WalkGraph(_edges, "start", new());
WalkGraph(_edges, "start", []);
public override object Part2() =>
TraverseGraph(_edges, "start", new());
TraverseGraph(_edges, "start", []);
}

View File

@ -13,24 +13,24 @@ public sealed class Day13() : Day(2021, 13, "Transparent Origami")
public override void ProcessInput()
{
var s = Input.Split("").ToList();
_dots = s[0].Select(p =>
{
var i = p.Split(',', 2).Select(int.Parse).ToList();
return (i[0], i[1]);
}).ToList();
_folds = s[1].Select(p => p.Split(' ').Skip(2).First()).Select(p =>
{
var i = p.Split('=', 2);
return (i[0][0], int.Parse(i[1]));
}).ToList();
}
private static List<(int x, int y)> DoFold(List<(int x, int y)> grid, char axis, int at)
{
List<(int, int)> result = new();
List<(int, int)> result = [];
switch (axis)
{
case 'x':

View File

@ -34,7 +34,7 @@ public sealed class Day16() : Day(2021, 16, "Packet Decoder")
if (chunk[0] == '0') break;
}
return (new(version, typeId, Convert.ToInt64(literalBits.ToString(), 2), new()), index);
return (new(version, typeId, Convert.ToInt64(literalBits.ToString(), 2), []), index);
}
switch (input[index++])

View File

@ -7,8 +7,7 @@ public sealed class Day17() : Day(2021, 17, "Trick Shot")
{
private List<int>? _target;
public override void ProcessInput()
{
public override void ProcessInput() =>
_target = Input.First()
.Split(' ', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Skip(2)
@ -16,7 +15,6 @@ public sealed class Day17() : Day(2021, 17, "Trick Shot")
.Select(i => i.TrimEnd(','))
.Select(int.Parse)
.ToList();
}
public override object Part1()
{

View File

@ -7,13 +7,13 @@ public sealed class Day18() : Day(2021, 18, "Snailfish")
{
private List<string>? _fishes;
public override void ProcessInput()
{
_fishes = Input.ToList();
}
public override void ProcessInput() => _fishes = Input.ToList();
private static Tree<int> Parse(string input)
{
var cursor = 0;
return new(ParseFish(null, input, ref cursor));
static Tree<int>.Node ParseFish(Tree<int>.Node? parent, string input, ref int cursor)
{
if (input[cursor] != '[') return new(parent, input[cursor++] - '0');
@ -26,14 +26,11 @@ public sealed class Day18() : Day(2021, 18, "Snailfish")
cursor++;
return node;
}
var cursor = 0;
return new(ParseFish(null, input, ref cursor));
}
private static Tree<int> Add(Tree<int> a, Tree<int> b)
{
var reduced = new Tree<int>(new(null, -1) {Left = a.Root, Right = b.Root});
var reduced = new Tree<int>(new(null, -1) { Left = a.Root, Right = b.Root });
Reduce(reduced);
return reduced;
}
@ -60,13 +57,16 @@ public sealed class Day18() : Day(2021, 18, "Snailfish")
private static void Reduce(Tree<int> tree)
{
bool ReduceRecurse(Tree<int>.Node node, Func<Tree<int>, Tree<int>.Node, bool> reducer)
var changed = true;
while (changed)
{
if (reducer(tree, node)) return true;
if (node.Left != null && ReduceRecurse(node.Left, reducer)) return true;
return node.Right != null && ReduceRecurse(node.Right, reducer);
changed = false;
while (ReduceRecurse(tree.Root, Explode)) changed = true;
if (ReduceRecurse(tree.Root, Split)) changed = true;
}
return;
bool Explode(Tree<int> t, Tree<int>.Node node)
{
if (node.Data != -1 || node.DistanceToParent(t.Root) < 4) return false;
@ -90,12 +90,11 @@ public sealed class Day18() : Day(2021, 18, "Snailfish")
return true;
}
var changed = true;
while (changed)
bool ReduceRecurse(Tree<int>.Node node, Func<Tree<int>, Tree<int>.Node, bool> reducer)
{
changed = false;
while (ReduceRecurse(tree.Root, Explode)) changed = true;
if (ReduceRecurse(tree.Root, Split)) changed = true;
if (reducer(tree, node)) return true;
if (node.Left != null && ReduceRecurse(node.Left, reducer)) return true;
return node.Right != null && ReduceRecurse(node.Right, reducer);
}
}

View File

@ -9,10 +9,9 @@ public sealed class Day19() : Day(2021, 19, "Beacon Scanner")
{ (0, 1, 0), (0, -1, 0), (1, 0, 0), (-1, 0, 0), (0, 0, 1), (0, 0, -1) };
private List<HashSet<Vector3>>? _scans;
private List<HashSet<Vector3>> _scanners = new();
private List<HashSet<Vector3>> _scanners = [];
public override void ProcessInput()
{
public override void ProcessInput() =>
_scans = Input
.Aggregate(new List<HashSet<Vector3>>(), (list, line) =>
{
@ -20,7 +19,7 @@ public sealed class Day19() : Day(2021, 19, "Beacon Scanner")
if (line.StartsWith("---"))
{
list.Add(new());
list.Add([]);
return list;
}
@ -28,7 +27,6 @@ public sealed class Day19() : Day(2021, 19, "Beacon Scanner")
list[^1].Add((parts[0], parts[1], parts[2]));
return list;
});
}
private static Vector3 Transform(Vector3 pt, Vector3 up, int rotation)
{

View File

@ -6,7 +6,7 @@ namespace AOC2021;
public sealed class Day21() : Day(2021, 21, "Dirac Dice")
{
private int _player1, _player2;
private readonly Dictionary<int, ulong> _possibleRollOutComes = new();
private readonly Dictionary<int, ulong> _possibleRollOutComes = [];
private int _deterministicDie = 1;
private int _rollCount;
private ulong _player1Victories, _player2Victories;

View File

@ -5,7 +5,7 @@ namespace AOC2021;
/// </summary>
public sealed class Day22() : Day(2021, 22, "Reactor Reboot")
{
private readonly List<Instruction> _instructions = new();
private readonly List<Instruction> _instructions = [];
public override void ProcessInput()
{
@ -18,7 +18,7 @@ public sealed class Day22() : Day(2021, 22, "Reactor Reboot")
.SelectMany(l => l.Split(".."))
.Select(int.Parse)
.ToList();
_instructions.Add(new(s[0] == "off", new(new(e[0], e[1]), new(e[2], e[3]), new(e[4], e[5]))));
}
}
@ -26,7 +26,7 @@ public sealed class Day22() : Day(2021, 22, "Reactor Reboot")
private long ActiveCubes(int x, Region3D region)
{
if (region.IsEmpty || x < 0) return 0;
var intersection = region.Intersect(_instructions[x].Region);
var activeInRegion = ActiveCubes(x - 1, region);
var activeInIntersection = ActiveCubes(x - 1, intersection);
@ -34,7 +34,7 @@ public sealed class Day22() : Day(2021, 22, "Reactor Reboot")
// outside the intersection is unaffected, the rest is either on or off:
return _instructions[x].Disable ? activeOutsideIntersection : activeOutsideIntersection + intersection.Volume;
}
public override object Part1()

View File

@ -7,10 +7,8 @@ public sealed class Day23() : Day(2021, 23, "Amphipod")
{
private List<char>? _crabs;
public override void ProcessInput()
{
public override void ProcessInput() =>
_crabs = Input.SelectMany(l => l).Where(char.IsLetter).ToList();
}
private static IEnumerable<int> BreadthFirstSearch(string s, int i)
{
@ -32,53 +30,50 @@ public sealed class Day23() : Day(2021, 23, "Amphipod")
}
}
private static Dijkstra<State, (State state, int distance)> GetPathFinder(int size)
private static Dijkstra<State, (State state, int distance)> GetPathFinder(int size) => new()
{
return new()
Neighbors = state =>
{
Neighbors = state =>
// Find all neighbors from the current state
var possible = new List<(State, int)>();
var entries = new[] { 2, 4, 6, 8 };
// Add each way of taking an item out of a hole into the hallway
foreach (var i in entries)
{
// Find all neighbors from the current state
var possible = new List<(State, int)>();
var entries = new[] { 2, 4, 6, 8 };
// Add each way of taking an item out of a hole into the hallway
foreach (var i in entries)
var hole = state[i / 2 - 1];
if (string.IsNullOrWhiteSpace(hole)) continue;
var targets = BreadthFirstSearch(state.Hallway, i).Except(entries).ToList();
foreach (var target in targets)
{
var hole = state[i / 2 - 1];
if (string.IsNullOrWhiteSpace(hole)) continue;
var targets = BreadthFirstSearch(state.Hallway, i).Except(entries).ToList();
foreach (var target in targets)
{
var data = state.Hallway.ToCharArray();
data[target] = hole.Trim()[0];
var newHole = hole.Trim()[1..].PadLeft(size);
var next = State.New(state, data, i / 2 - 1, newHole);
var cost = Math.Abs(target - i) + (size - newHole.Trim().Length);
cost *= 10.Pow(data[target] - 'A');
possible.Add((next, cost));
}
}
foreach (var (at, which) in state.Hallway.Indexed().WhereValue(char.IsLetter))
{
var dest = which - 'A';
if (!BreadthFirstSearch(state.Hallway, at).Intersect(entries).Select(i => i / 2 - 1)
.Contains(dest)) continue;
if (state[dest]!.Trim().Any(c => c != which)) continue;
var data = state.Hallway.ToCharArray();
data[at] = ' ';
var next = State.New(state, data, dest, (which + state[dest]!.Trim()).PadLeft(size));
var cost = Math.Abs(at - (dest + 1) * 2) + (size - state[dest]!.Trim().Length);
cost *= 10.Pow(dest);
data[target] = hole.Trim()[0];
var newHole = hole.Trim()[1..].PadLeft(size);
var next = State.New(state, data, i / 2 - 1, newHole);
var cost = Math.Abs(target - i) + (size - newHole.Trim().Length);
cost *= 10.Pow(data[target] - 'A');
possible.Add((next, cost));
}
}
return possible;
},
Distance = tuple => tuple.distance,
Cell = (_, tuple) => tuple.state
};
}
foreach (var (at, which) in state.Hallway.Indexed().WhereValue(char.IsLetter))
{
var dest = which - 'A';
if (!BreadthFirstSearch(state.Hallway, at).Intersect(entries).Select(i => i / 2 - 1)
.Contains(dest)) continue;
if (state[dest]!.Trim().Any(c => c != which)) continue;
var data = state.Hallway.ToCharArray();
data[at] = ' ';
var next = State.New(state, data, dest, (which + state[dest]!.Trim()).PadLeft(size));
var cost = Math.Abs(at - (dest + 1) * 2) + (size - state[dest]!.Trim().Length);
cost *= 10.Pow(dest);
possible.Add((next, cost));
}
return possible;
},
Distance = tuple => tuple.distance,
Cell = (_, tuple) => tuple.state
};
public override object Part1()
{

View File

@ -5,7 +5,7 @@ namespace AOC2021;
/// </summary>
public sealed class Day24() : Day(2021, 24, "Arithmetic Logic Unit")
{
private readonly Dictionary<int, (int x, int y)> _keys = new();
private readonly Dictionary<int, (int x, int y)> _keys = [];
public override void ProcessInput()
{

View File

@ -7,10 +7,8 @@ public sealed class Day25() : Day(2021, 25, "Sea Cucumber")
{
private char[][]? _cucumbers;
public override void ProcessInput()
{
public override void ProcessInput() =>
_cucumbers = Input.Select(l => l.ToCharArray()).ToArray();
}
private static char[][]? DoStep(IReadOnlyList<char[]> arr)
{
@ -38,15 +36,15 @@ public sealed class Day25() : Day(2021, 25, "Sea Cucumber")
result2[i] = new char[w];
for (var i = 0; i < h; i++)
for (var j = 0; j < w; j++)
{
if (result2[i][j] == 0) result2[i][j] = result[i][j];
if (result[i][j] != 'v') continue;
if (result[(i + 1) % h][j] != '.') continue;
result2[i][j] = '.';
result2[(i + 1) % h][j] = 'v';
moved = true;
}
for (var j = 0; j < w; j++)
{
if (result2[i][j] == 0) result2[i][j] = result[i][j];
if (result[i][j] != 'v') continue;
if (result[(i + 1) % h][j] != '.') continue;
result2[i][j] = '.';
result2[(i + 1) % h][j] = 'v';
moved = true;
}
return moved ? result2 : null;
}

View File

@ -5,7 +5,7 @@ namespace AOC2022;
/// </summary>
public sealed class Day07() : Day(2022, 7, "No Space Left On Device")
{
private readonly DefaultDictionary<string, long> _dirs = new();
private readonly DefaultDictionary<string, long> _dirs = [];
public override void ProcessInput()
{
@ -23,7 +23,7 @@ public sealed class Day07() : Day(2022, 7, "No Space Left On Device")
else
{
if (!long.TryParse(line.Split(' ')[0], out var filesize)) continue;
var pathList = path.ToList();
pathList.Reverse();

View File

@ -67,12 +67,12 @@ public sealed class Day08() : Day(2022, 8, "Treetop Tree House")
{
var max = 0;
for (var y = 0; y < _trees!.Length; y++)
for (var x = 0; x < _trees[0].Length; x++)
{
var (_, score) = ScoreCoord(x, y);
if (score > max) max = score;
}
for (var x = 0; x < _trees[0].Length; x++)
{
var (_, score) = ScoreCoord(x, y);
if (score > max) max = score;
}
return max;
}
}
}

View File

@ -24,7 +24,7 @@ public sealed class Day09() : Day(2022, 9, "Rope Bridge")
case 'L': rope[0].x--; break;
case 'R': rope[0].x++; break;
}
foreach (var i in Enumerable.Range(1, ropeLength - 1))
{
int dx = rope[i - 1].x - rope[i].x, dy = rope[i - 1].y - rope[i].y;

View File

@ -5,17 +5,17 @@ namespace AOC2022;
/// </summary>
public sealed class Day10() : Day(2022, 10, "Cathode-Ray Tube")
{
private readonly List<int> _interestingSignals = new();
private readonly List<int> _interestingSignals = [];
private readonly List<char> _charMap = Enumerable.Range(0, 6 * 40).Select(_ => ' ').ToList();
public override void ProcessInput()
{
int x = 1, cycle = 1;
foreach (var line in Input)
{
{
CpuTick(ref cycle, x);
if (!line.StartsWith("addx")) continue;
CpuTick(ref cycle, x);
x += int.Parse(line.Split(' ')[1]);
}

View File

@ -26,7 +26,7 @@ public sealed class Day11() : Day(2022, 11, "Monkey in the Middle")
item = monkey.Operation(item);
if (part1) item /= 3;
item %= _lcm;
monkey.InspectionCount++;
var dest = item % monkey.ModTest == 0 ? monkey.TrueDest : monkey.FalseDest;
_monkeys[dest].Items.Enqueue(item);
@ -90,4 +90,4 @@ public sealed class Day11() : Day(2022, 11, "Monkey in the Middle")
return m;
}
}
}
}

View File

@ -5,8 +5,8 @@ namespace AOC2022;
/// </summary>
public sealed class Day12() : Day(2022, 12, "Hill Climbing Algorithm")
{
private readonly Dictionary<(int x, int y), int> _grid = new();
private static readonly List<(int x, int y)> Directions = new() { (-1, 0), (1, 0), (0, -1), (0, 1) };
private readonly Dictionary<(int x, int y), int> _grid = [];
private static readonly List<(int x, int y)> Directions = [(-1, 0), (1, 0), (0, -1), (0, 1)];
private (int x, int y) _startCoord, _destCoord;
public override void ProcessInput()
@ -53,4 +53,4 @@ public sealed class Day12() : Day(2022, 12, "Hill Climbing Algorithm")
public override object Part1() => ShortestDistance(_destCoord, _startCoord);
public override object Part2() => ShortestDistance(_destCoord, null, 0);
}
}

View File

@ -17,7 +17,7 @@ public sealed class Day14() : Day(2022, 14, "Regolith Reservoir")
private static HashSet<(int x, int y)> PourSand((int x, int y) start, int bottom, Func<(int x, int y), bool> wall)
{
HashSet<(int x, int y)> sand = new();
HashSet<(int x, int y)> sand = [];
while (true)
{
@ -77,4 +77,4 @@ public sealed class Day14() : Day(2022, 14, "Regolith Reservoir")
public override object Part2() =>
PourSand(_start, int.MaxValue, p => p.y == _bottom + 2 || _walls!.Contains(p)).Count;
}
}

View File

@ -9,13 +9,7 @@ public sealed class Day15() : Day(2022, 15, "Beacon Exclusion Zone")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -9,13 +9,7 @@ public sealed class Day16() : Day(2022, 16, "Proboscidea Volcanium")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

View File

@ -9,13 +9,7 @@ public sealed class Day17() : Day(2022, 17, "Pyroclastic Flow")
{
}
public override object Part1()
{
return "";
}
public override object Part1() => "";
public override object Part2()
{
return "";
}
public override object Part2() => "";
}

Some files were not shown because too many files have changed in this diff Show More