Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace AdventOfCodeDay13
{
class Program
{
static void Main(string[] args)
{
StreamReader ss = new StreamReader("../../input1.txt");
string line;
var input = new List<string>();
while ((line = ss.ReadLine()) != null)
{
input.Add(line);
}
var regex = new Regex("^(?<Name1>.*) would (?<Sign>.*) (?<Value>[0-9]+) happiness units by sitting next to (?<Name2>.*).$");
var persons = new List<Person>();
var happynessChangeDictionary = new Dictionary<string, int>();
foreach (var c in input)
{
var m = regex.Matches(c)[0];
var name1 = m.Groups["Name1"].Value;
var name2 = m.Groups["Name2"].Value;
var sign = m.Groups["Sign"].Value;
var value = int.Parse(m.Groups["Value"].Value);
Console.WriteLine($"{name1}, {name2}, {sign}, {value}");
if (persons.All(a => a.Name != name1))
{
persons.Add(new Person { Name = name1, HappynessChangeLeft = 0, HappynessChangeRight = 0 });
}
happynessChangeDictionary.Add($"{name1}-{name2}", (sign == "lose" ? -1 : 1) * value);
}
var arrangements = persons.Permute().ToList();
var maxHappyness = 0;
foreach (var arrangement in arrangements)
{
var arrangementList = arrangement.ToList();
var cnt = arrangementList.Count();
for (var i = 0; i < cnt; i++)
{
var leftIndex = Mod(i - 1, cnt);
var rightIndex = Mod(i + 1, cnt);
var self = arrangementList[i];
var left = arrangementList[leftIndex];
var right = arrangementList[rightIndex];
var leftKey = $"{self.Name}-{left.Name}";
var rightKey = $"{self.Name}-{right.Name}";
self.HappynessChangeLeft = happynessChangeDictionary[leftKey];
self.HappynessChangeRight = happynessChangeDictionary[rightKey];
}
maxHappyness = Math.Max(maxHappyness, arrangementList.Sum(a => a.TotalHappynessChange));
}
Console.WriteLine($"Optimal change: {maxHappyness}");
Console.ReadLine();
}
public class Person
{
public string Name { get; set; }
public int HappynessChangeLeft { get; set; }
public int HappynessChangeRight { get; set; }
public int TotalHappynessChange => HappynessChangeLeft + HappynessChangeRight;
}
public static int Mod(int x, int m)
{
return (x % m + m) % m;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.