Compare commits

...

2 Commits

Author SHA1 Message Date
login000
90aa8db5aa Day6 solution 2024-12-06 23:24:37 +10:30
login000
654f7d946b Added Day5 and started adding test input txt files. 2024-12-06 18:59:25 +10:30
6 changed files with 1991 additions and 2 deletions

195
Advent24/Day5.cs Normal file
View File

@ -0,0 +1,195 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace Advent24
{
internal class Day5
{
private static void IngestRule(String rule, Dictionary<Int32, List<(Int32, Int32)>> ruleDict)
{
var ruleArray = rule.Split('|');
var ruleArrayInt32 = Array.ConvertAll(ruleArray, System.Convert.ToInt32);
// if the ruleDict index doesn't already exists, add an empty list to it
ruleDict.TryAdd(ruleArrayInt32[0], new List<(int, int)>(2));
ruleDict[ruleArrayInt32[0]].Add((ruleArrayInt32[0], ruleArrayInt32[1]));
ruleDict.TryAdd(ruleArrayInt32[1], new List<(int, int)>(2));
ruleDict[ruleArrayInt32[1]].Add((ruleArrayInt32[0], ruleArrayInt32[1]));
}
private static void IngestPageRow(String pageRow, List<Dictionary<Int32, Int32>> pageRowDictsList)
{
var pageRowArray = pageRow.Split(',');
var pageRowArrayInt32 = Array.ConvertAll(pageRowArray, System.Convert.ToInt32);
pageRowDictsList.Add(new Dictionary<Int32, Int32>(pageRowArray.Length));
Int32 pageRowIndex = 1;
foreach (var pageInt32 in pageRowArrayInt32)
{
pageRowDictsList[pageRowDictsList.Count - 1].Add(pageInt32, pageRowIndex);
pageRowIndex++;
}
}
private static Int32 GetPageRowMiddle(Dictionary<Int32, Int32> pageRowDict)
{
var pageRowMiddleEnumerable = pageRowDict.Where(keyValuePair => keyValuePair.Value == (pageRowDict.Count + 1) / 2);
return pageRowMiddleEnumerable.ElementAt(0).Key;
}
private static Boolean PageRowIsCorrect(Dictionary<Int32, Int32> pageRowDict, Dictionary<Int32, List<(Int32, Int32)>> ruleDict)
{
Boolean pageRowIsCorrect = true;
foreach(Int32 page in pageRowDict.Keys)
{
if (ruleDict.TryGetValue(page, out List<(int, int)>? rules))
{
foreach (var rule in rules)
{
// check if the rule pertains to our pageRow
if(pageRowDict.TryGetValue(rule.Item1, out Int32 leftHandIndex) &&
pageRowDict.TryGetValue(rule.Item2, out Int32 rightHandIndex))
// if rule violation detected, set pageRowIsCorrect to false
// and break as we don't need to check the rest of the pageRow
if (leftHandIndex >= rightHandIndex)
{
pageRowIsCorrect = false;
break;
}
}
// break out of outer foreach loop if nner foreach
// was broken due to finding a rule violation
if (!pageRowIsCorrect) break;
}
}
return pageRowIsCorrect;
}
private static Int32 GetCorrectMiddlesSum(Dictionary<Int32, List<(Int32, Int32)>> ruleDict, List<Dictionary<Int32, Int32>> pageRowDictsList)
{
Int32 correctMiddlesSum = 0;
foreach (var pageRowDict in pageRowDictsList)
{
if (PageRowIsCorrect(pageRowDict, ruleDict))
{
correctMiddlesSum += GetPageRowMiddle(pageRowDict);
}
}
return correctMiddlesSum;
}
private static void CorrectPageRow(out Dictionary<Int32, Int32> correctedPageRowDict, Dictionary<Int32, Int32> pageRowDict, Dictionary<Int32, List<(Int32, Int32)>> ruleDict)
{
correctedPageRowDict = pageRowDict.ToDictionary();
Boolean correctionWasRequired;
do
{
correctionWasRequired = false;
foreach (Int32 page in pageRowDict.Keys)
{
if (ruleDict.TryGetValue(page, out List<(int, int)>? rules))
{
foreach (var rule in rules)
{
// check if the rule pertains to our pageRow
if (correctedPageRowDict.TryGetValue(rule.Item1, out Int32 leftHandIndex) &&
correctedPageRowDict.TryGetValue(rule.Item2, out Int32 rightHandIndex))
// if rule violation detected, swap the positions
if (leftHandIndex >= rightHandIndex)
{
// swap indices, i.e., swap positions
correctedPageRowDict[rule.Item1] = rightHandIndex;
correctedPageRowDict[rule.Item2] = leftHandIndex;
correctionWasRequired = true;
}
}
}
}
} while(correctionWasRequired);
}
private static Int32 GetCorrectedMiddlesSum(Dictionary<Int32, List<(Int32, Int32)>> ruleDict, List<Dictionary<Int32, Int32>> pageRowDictsList)
{
Int32 correctMiddlesSum = 0;
foreach (var pageRowDict in pageRowDictsList)
{
if (!PageRowIsCorrect(pageRowDict, ruleDict))
{
CorrectPageRow(out Dictionary<int, int> correctedPageRowDict, pageRowDict, ruleDict);
correctMiddlesSum += GetPageRowMiddle(correctedPageRowDict);
}
}
return correctMiddlesSum;
}
public Day5()
{
String fileData = System.IO.File.ReadAllText(@"..\..\..\inputd5.txt");
var rulesAndPageRowsArray = fileData.Split('\n');
// indicates when we stop ingesting rules and start ingesting page rows
Boolean amIngestingRules = true;
// a dictionary to map from a page number to a rule containing that page number
// the rule is that p1 must appear before p2 if the Tuple is (p1, p2), i.e.,
// index of p1 must be less than index of p2
Dictionary<Int32, List<(Int32, Int32)>> ruleDict = [];
// a dictionary to map from a page number to its position in the array
List<Dictionary<Int32, Int32>> pageRowDictsList = [];
Int32 sumOfCorrectMiddles;
Int32 sumOfCorrectedMiddles;
foreach (var ruleOrPageRow in rulesAndPageRowsArray)
{
// empty line indicates end of rules and beginning of page rows
if (ruleOrPageRow == "")
{
amIngestingRules = false;
continue;
}
if(amIngestingRules)
{
IngestRule(ruleOrPageRow, ruleDict);
}
else
{
// am ingesting page rows now
IngestPageRow(ruleOrPageRow, pageRowDictsList);
}
}
sumOfCorrectMiddles = GetCorrectMiddlesSum(ruleDict, pageRowDictsList);
sumOfCorrectedMiddles = GetCorrectedMiddlesSum(ruleDict, pageRowDictsList);
Console.WriteLine("sumOfCorrectMiddles = {0:d}", sumOfCorrectMiddles);
Console.WriteLine("sumOfCorrectedMiddles = {0:d}", sumOfCorrectedMiddles);
// to keep the console window from closing
Console.ReadKey();
}
}
}

257
Advent24/Day6.cs Normal file
View File

@ -0,0 +1,257 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.IO.Compression;
using System.Xml.Serialization;
namespace Advent24
{
internal class Day6
{
private static Boolean simulateGuardPath(String map, ref HashSet<Int32> visited, Int32 newObstacleLinearPosition = -1)
{
// get width of line to be able to navigate the text block in
// both dimensions
Int32 mapWidth = map.IndexOf('\n');
Int32 guardLinearPosition = 0;
Int32 guardDirection = 0; //1 = up, 2 = right, 3 = down, 4 = left
// counts the number of times we go forward in time without
Int32 numberOfIterationsWithoutNewVisits = 0;
Int32 previousNumberOfVisitedPositions = 0;
Int32 numberOfDirectionChanges = 0;
Boolean guardIsInMapBoundary = true;
Boolean wasInfiniteLoop = false;
// Find the initial position and direction of the guard
guardLinearPosition = map.IndexOf('^');
if (guardLinearPosition != -1) // in up direction
{
guardDirection = 1;
// invalid new obstacle position, so return prematurely with
// the assumption that it didn't lead to an infinite loop
if (newObstacleLinearPosition == guardLinearPosition)
return false; // assumed value of wasInfiniteLoop
}
else // not in up direction
{
guardLinearPosition = map.IndexOf('>');
if (guardLinearPosition != -1) // in right direction
guardDirection = 2;
else // not in up or right direction
{
guardLinearPosition = map.IndexOf('v');
if (guardLinearPosition != -1) // in down direction
guardDirection = 3;
else // not in up, right or down direction
{
guardLinearPosition = map.IndexOf('<');
if (guardLinearPosition != -1) // in left direction
guardDirection = 4;
else // guard not found
{
guardDirection = -1;
guardIsInMapBoundary = false;
}
}
}
}
// add intiial guard linear position
if (guardIsInMapBoundary) visited.Add(guardLinearPosition);
while (guardIsInMapBoundary)
{
// check next position of guard
// top
if (guardDirection == 1)
{
// if obstacle detected
if (guardLinearPosition - (mapWidth + 1) >= 0 &&
(
map[guardLinearPosition - (mapWidth + 1)] == '#' ||
guardLinearPosition - (mapWidth + 1) == newObstacleLinearPosition
))
{
// turn 90 deg clockwise
guardDirection = 2;
numberOfDirectionChanges++;
}
// no obstacle detected
else
// go up one position
guardLinearPosition -= mapWidth + 1;
}
// right
else if (guardDirection == 2)
{
// if obstacle detected
if (guardLinearPosition + 1 < map.Length &&
(
map[guardLinearPosition + 1] == '#' ||
guardLinearPosition + 1 == newObstacleLinearPosition
))
{
// turn 90 deg clockwise
guardDirection = 3;
numberOfDirectionChanges++;
}
// no obstacle detected
else
// go up one position
guardLinearPosition += 1;
}
// down
else if (guardDirection == 3)
{
// if obstacle detected
if (guardLinearPosition + (mapWidth + 1) < map.Length &&
(
map[guardLinearPosition + (mapWidth + 1)] == '#' ||
guardLinearPosition + (mapWidth + 1) == newObstacleLinearPosition
))
{
// turn 90 deg clockwise
guardDirection = 4;
numberOfDirectionChanges++;
}
// no obstacle detected
else
// go up one position
guardLinearPosition += (mapWidth + 1);
}
// left
else if (guardDirection == 4)
{
// if obstacle detected
if (guardLinearPosition - 1 >= 0 &&
(
map[guardLinearPosition - 1] == '#' ||
guardLinearPosition - 1 == newObstacleLinearPosition
))
{
// turn 90 deg clockwise
guardDirection = 1;
numberOfDirectionChanges++;
}
// no obstacle detected
else
// go up one position
guardLinearPosition -= 1;
}
// right and left boundary check
if (guardLinearPosition > map.Length ||
guardLinearPosition < 0 ||
map[guardLinearPosition] == '\n')
guardIsInMapBoundary = false;
// top and bottom boundary check
if (guardLinearPosition < 0 ||
guardLinearPosition >= map.Length)
guardIsInMapBoundary = false;
// if boundary check passes, add position to visited
if (guardIsInMapBoundary)
{
previousNumberOfVisitedPositions = visited.Count;
visited.Add(guardLinearPosition);
}
// if there is no change in the number of visited positions
if (previousNumberOfVisitedPositions == visited.Count)
{
numberOfIterationsWithoutNewVisits++;
// we've followed the whole path again, of which a good approximation is
// that the number of unique visited positions plus the number of times
// the direction has changes is equal to the number of iterations without new
// visits - this will undercount intersections
if (numberOfIterationsWithoutNewVisits > (visited.Count + numberOfDirectionChanges))
{
// Console.WriteLine(" numberOfIterationsWithoutNewVisits = {0:d}", numberOfIterationsWithoutNewVisits);
wasInfiniteLoop = true;
break;
}
}
}
return wasInfiniteLoop;
}
public Day6()
{
String fileData = System.IO.File.ReadAllText(@"..\..\..\inputd6.txt");
// set of visited linearPositions
HashSet<Int32> visited = [];
simulateGuardPath(fileData, ref visited);
Int32 numberOfDistinctPositions = visited.Count;
Console.WriteLine("numberOfDistinctPositions = {0:d}", numberOfDistinctPositions);
Int32 numberOfViableNewObstaclePositions = 0;
Boolean wasInfiniteLoop;
// a set of unchecked linearPositions
HashSet<Int32> uncheckedLinearPositions = [.. visited];
// a set of alreaedy-checked linearPositions
HashSet<Int32> checkedLinearPositions = [];
Int32 previousUncheckedLinearPositionsCount = uncheckedLinearPositions.Count;
// while there are unchecked visited positions
while (uncheckedLinearPositions.Count > 0)
{
// clear visited hashset for a fresh start per iteration
visited.Clear();
// get first non-checked linear position
var firstNonCheckedLinearPosition = uncheckedLinearPositions.First();
wasInfiniteLoop = simulateGuardPath(fileData, ref visited, firstNonCheckedLinearPosition);
// if the guard is in a loop, we have a viable obstacle position
if (wasInfiniteLoop)
numberOfViableNewObstaclePositions++;
// update checkedLinearPositions
checkedLinearPositions.Add(firstNonCheckedLinearPosition);
// remove already-checked linear positions from visited
// so it only has new positions to add to our uncheckedLinearPositions
visited.ExceptWith(checkedLinearPositions);
previousUncheckedLinearPositionsCount = uncheckedLinearPositions.Count;
// update uncheckedLinearPositions to remove firstNonCheckedLinearPosition
// and add newly visisted linear positions
uncheckedLinearPositions.Remove(firstNonCheckedLinearPosition);
uncheckedLinearPositions.UnionWith(visited);
// if (uncheckedLinearPositions.Count > previousUncheckedLinearPositionsCount)
// Console.WriteLine("(change) uncheckedLinearPositions.Count = {0:d}", uncheckedLinearPositions.Count - previousUncheckedLinearPositionsCount);
}
Console.WriteLine("numberOfViableNewObstaclePositions = {0:d}", numberOfViableNewObstaclePositions);
// to keep the console window from closing
Console.ReadKey();
}
}
}

View File

@ -10,7 +10,9 @@ namespace Advent24
//_ = new Day1();
//_ = new Day2();
//_ = new Day3();
_ = new Day4();
//_ = new Day4();
// _ = new Day5();
_ = new Day6();
}
}
}

1377
Advent24/inputd5.txt Normal file

File diff suppressed because it is too large Load Diff

28
Advent24/inputd5test.txt Normal file
View File

@ -0,0 +1,28 @@
47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47

130
Advent24/inputd6.txt Normal file
View File

@ -0,0 +1,130 @@
..........#...........#...........#.............................#......................#.........#................................
..........................#.........#......#.................................#...........................#........................
..................................#...#................................................................................#..........
.#...............#.....#..........#.........#......#........#................................#......#.............................
...#.......#.............#.............................................#.........##...............#.................#.............
.......................................#.............#..................#........#.......#.........#...............#.........#....
.....#..................#..#..#.........................#...................#....#........#.............................#.........
.......#.............................#..........#......#..........................##......#.......................##..............
.....#.....#........................................................................................#.......#.....................
.................................#............#...#.....................................................#.........#...............
...............#.....#..#....#....#.....................................................#............#........#.#.................
.......#.....#...........................................................#............................#.................#....#....
...........................#.................#....................................#...............#..#........................#...
.....#.........................................#.................#...##....................................#......................
.............#...#..................#......#.................#..........................................#.....#..........#........
.................#...............#............#.......#.#...............................................#..................#......
.....#..#.....................#.......................................................#..............#..............#.......##....
..##........#....................................................#.............#..............#........................#..#.......
..............................#...........#...#........................#............#..........................#........#........#
.....................................##...............................#............#............#....#............................
...##........................#.....#....#.........#.................................................#.............................
...............................#................................#...............#.....#.....................#.....................
................................................#..........#....#............................#.....#.......#..................#...
.............#.....#.........#.#....#................##......#.............#......................................................
..........#..............#..........#......#.........#...#.........................................#.#.....#.........#............
..................#......................#.............................#...................#.....................................#
................#.....#..............................#.............#.............#..#.....#....................................#..
.........#.#................#.........#.................#...................#................................#................#...
.............................................................#..............#.....................................................
......#.........................#...........#.........#..................#....................................#..#...........##...
.............................................................................#.............#........................#...#.........
......#......#..#............#..............................................#....#..#..#................#.........#....#..........
........#........#.........#....................................................^..#...#....................#...............#.....
..#....#...#.......................................................................................................#..............
.....#...........................................#..............#.........#....#........................................#.........
.....................................#..............#............................................................#................
.....#.......................#........................#..........#.............#.................#..................#.............
.......................................#......#.....................................#.........................#...................
...........................................................................................#............................##........
..#............#..........................#...........#...#..................#......#.................#.#.................#......#
.###......#....................#...#...........................................................#.........#.....#..............#.#.
....................................#..........#.....#.......................#...............#.....#......#...................#...
...#......#..................#......#.......#..............#..............#.......................................................
..........#....................................................................#................##.#...#..........................
.........................................................#..................##.....................#..##..........................
..................#......#.................................#.................#.##................................................#
...#..........#...#..#..............................................#...........................##........#.......................
.....#................................................#...........#..................#...#.................................#......
.......#.....#.........................#..........................................................................................
....................................................#........#....#....................................##..............#.....#....
............#........#.........................#.................................#..........................................#...#.
.....................................#........................#...................#......#.#...........#..#..........#...........#
................#...............#.........................#.........................#........#..#.................................
.............#.........#.............#.#.#.........#...................#.......#.......................#..........................
.............#......................................................#................................................#.......#....
....#....................................................................#.#........#.................#..........................#
.................................#......#....................................................................#.....#..............
............##...................#.......................................................................#.........#........#.....
#..................................................#..#...............#............#.............#...............................#
.............................#.................................#.....#..........................#.............#..#...#...#........
...#.....#..............................#.#......................................#................................................
...#............##...............................#............#..............................#................................#...
#.................#......##..............................................................#...........#........#...#...............
....##.....................................................................................................#.#....................
#.................#..................................................#..................................................#.........
.........#.........#...........................#.................#.#.............................#................................
................................#............#................................................................#...................
.....................................#............................................#.##......##........#...........................
....#....................................................#...#.#.#....................................................#...........
.........................#.#...................#...................##...............#........................#....................
..................................#...................................................................#.......#..................#
...................#.............................................#.......................#.#.....................#....#...........
#....................................#.#..#.#..........#.........#.........##.........#......................#............#.......
...............................................................#.............................##....#.......#......................
.............#......#.#.........#............................#............................#.......................................
......................#.........#.........................................................#...#............#......................
...................#.....#.....................................................#.....................................#............
...............................#.....#..................#.......##................................................................
.............................................#.........................#...........#..............................#..#............
#..##..................................................................................................#......#...........#.....#.
.......................................................#.....................#.............................#......................
...........................................................................................................#......................
......................#..............................................................#............................................
...........................#.....#......................................#.........#........#..#.#.................................
.#.......#........................................................................................................................
.#.......#...........................................#................................#...........................................
.........................................................#........................................#......#........................
...............................#...#........#............................................#.................#......................
......#.........................#......................#.....#.#..............#..................#.......#..................#.....
.................#........#...#........................#.............................#............................................
#...........................................................................#............................#................#.......
..........................................................................#................#......................................
.............#.............................................................................#.........................#............
.#...........#.......#.......#.....#....#.......#........#....................#........................#........................#.
...#..............#.............................#.............................................................#...#..#..........#.
......#......#.#...............##................................................................................................#
....#........#.##......#...#......................................................................................................
..#..#.#.#.....................#................................#...................................#.....#...#...................
.....................#.#........#..............##..............#.................#..............................................#.
...................................................................................#........#.......#....#............#...........
.....#....#..................#...............#.............................................#.#....................#...............
.....................#..........#............#..................................#......................#.#.....#................#.
..........#.........................................#...............#.............................................................
.......#......................#.............#.....#..............#........................#.....#.........#.................#...#.
..................................................................#.....#...............................................#........#
.......#..........#.......#....#.......#..........#....#............................................#.#...........................
..#...........#..............................#....................#....................#...#......................................
.......#...............................#............#.....#.....................#.................................................
.........#..................#..................#..................................................................................
..........................................................................................#....#...................#.......##.....
..................#.............................##.......................................................#.......#......#......#..
...#.......#..............................................................................................#.......................
............#..#..............................................................#...........##....#....#.#................#........#
............#.........................#........#....#..#..................................#..................#....................
......##......................#...##..............................#...............................................................
........................#................#..............#...##...............................#..................##....#...........
....#.#...#.....#..................................#..............................#...........#.....................#.............
......................#.........................................................................#..........#.............#........
.#......#............................................................#...............................#...#........................
.......##.....................#.....#...........#......##.......##...................#...............................#............
...#...#........#...............#......#......#.....#...#.................................................................#.......
..................#.......................#...............................................#.................#.............#..#....
.....................#.......#....#...#............................#.....................#............#.....................#.....
................................................................#....#......#............#..................#.........#...........
.......................#...................#..............................................................................###.....
...............................#...........#................................#........#..#....#............................#.......
....#......#...............................#...............#......................................#...............................
...........#...........................##.........................................................................#.#.............
.........................#.........#.........................................#.....#...................#.....#.......#............
.............................#.....#................##..#.....................#...................................................