106 lines
3.6 KiB
C#
106 lines
3.6 KiB
C#
using AdventOfCode.Models;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace AdventOfCode._2022.Day11
|
|
{
|
|
public class Monkey
|
|
{
|
|
private AOCVersion _version;
|
|
public int MonkeyId { get; set; }
|
|
public Queue<long> Items { get; set; }
|
|
public Tuple<string, string> Operation { get; set; }
|
|
public long DivisibleNumber { get; set; }
|
|
public Tuple<int, int> TargetMonkeyIds { get; set; }
|
|
public Tuple<Monkey, Monkey> TargetMonkeys { get; set; }
|
|
public long ItemsInspected { get; set; }
|
|
public Monkey(AOCVersion version, string[] monkey)
|
|
{
|
|
_version = version;
|
|
//Pull monkey id
|
|
MonkeyId = Convert.ToInt32(Regex.Replace(monkey.First(), "[^0-9.]", ""));
|
|
|
|
//Item creation
|
|
Items = new Queue<long>();
|
|
Regex.Replace(monkey[1], "[^0-9. ]", "").Trim().Split(' ').ToList().ForEach(x => Items.Enqueue(Convert.ToInt32(x)));
|
|
|
|
//Generate operation
|
|
var splitOperation = monkey[2].Split(' ');
|
|
Operation = Tuple.Create(splitOperation[splitOperation.Length - 2], splitOperation[splitOperation.Length - 1]);
|
|
|
|
//Divisible number
|
|
DivisibleNumber = Convert.ToInt32(Regex.Replace(monkey[3], "[^0-9.]", ""));
|
|
|
|
//TargetMonkey
|
|
TargetMonkeyIds = Tuple.Create(Convert.ToInt32(Regex.Replace(monkey[4], "[^0-9.]", "")), Convert.ToInt32(Regex.Replace(monkey[5], "[^0-9.]", "")));
|
|
|
|
//Set items insepcts to 0
|
|
ItemsInspected = 0;
|
|
}
|
|
|
|
public void MapTargetMonkeys(Monkey trueMonkey, Monkey falseMonkey)
|
|
{
|
|
TargetMonkeys = Tuple.Create(trueMonkey, falseMonkey);
|
|
}
|
|
|
|
public void Business(long lcm = 0)
|
|
{
|
|
while (Items.Any())
|
|
{
|
|
var item = Items.Dequeue();
|
|
ItemsInspected++;
|
|
if (_version == AOCVersion.A)
|
|
{
|
|
item = ExecuteOperation(item); //Worry level
|
|
item = item / 3; //Monkey boredom
|
|
|
|
//Throw item to next monkey
|
|
if (item % DivisibleNumber == 0)
|
|
{
|
|
TargetMonkeys.Item1.Items.Enqueue(item);
|
|
}
|
|
else
|
|
{
|
|
TargetMonkeys.Item2.Items.Enqueue(item);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
long number;
|
|
if (!long.TryParse(Operation.Item2, out number))
|
|
number = item;
|
|
item %= lcm;
|
|
number %= lcm;
|
|
var result = Operation.Item1 == "+" ? item + number : item * number;
|
|
if (result% DivisibleNumber == 0)
|
|
{
|
|
TargetMonkeys.Item1.Items.Enqueue(result);
|
|
}
|
|
else
|
|
{
|
|
TargetMonkeys.Item2.Items.Enqueue(result);
|
|
}
|
|
}
|
|
|
|
|
|
}
|
|
}
|
|
|
|
private long ExecuteOperation(long item)
|
|
{
|
|
long number;
|
|
if (!long.TryParse(Operation.Item2, out number))
|
|
number = item;
|
|
if (Operation.Item1 == "+")
|
|
return number + item;
|
|
else if (Operation.Item1 == "*")
|
|
return number * item;
|
|
throw new ArgumentException("Unknown operation " + Operation.Item1);
|
|
}
|
|
|
|
}
|
|
}
|