Immune System Simulator 20XX


Fork me on GitHub
2018-12-24

Day 24: Immune System Simulator 20XX

Description:
--- Day 24: Immune System Simulator 20XX ---

After a weird buzzing noise, you appear back at the man's cottage. He seems relieved to see his friend, but quickly notices that the little reindeer caught some kind of cold while out exploring.

The portly man explains that this reindeer's immune system isn't similar to regular reindeer immune systems:

The immune system and the infection each have an army made up of several groups; each group consists of one or more identical units. The armies repeatedly fight until only one army has units remaining.

Units within a group all have the same hit points (amount of damage a unit can take before it is destroyed), attack damage (the amount of damage each unit deals), an attack type, an initiative (higher initiative units attack first and win ties), and sometimes weaknesses or immunities. Here is an example group:

18 units each with 729 hit points (weak to fire; immune to cold, slashing)
with an attack that does 8 radiation damage at initiative 10

Each group also has an effective power: the number of units in that group multiplied by their attack damage. The above group has an effective power of 18 * 8 = 144. Groups never have zero or negative units; instead, the group is removed from combat.

Each fight consists of two phases: target selection and attacking.

During the target selection phase, each group attempts to choose one target. In decreasing order of effective power, groups choose their targets; in a tie, the group with the higher initiative chooses first. The attacking group chooses to target the group in the enemy army to which it would deal the most damage (after accounting for weaknesses and immunities, but not accounting for whether the defending group has enough units to actually receive all of that damage).

If an attacking group is considering two defending groups to which it would deal equal damage, it chooses to target the defending group with the largest effective power; if there is still a tie, it chooses the defending group with the highest initiative. If it cannot deal any defending groups damage, it does not choose a target. Defending groups can only be chosen as a target by one attacking group.

At the end of the target selection phase, each group has selected zero or one groups to attack, and each group is being attacked by zero or one groups.

During the attacking phase, each group deals damage to the target it selected, if any. Groups attack in decreasing order of initiative, regardless of whether they are part of the infection or the immune system. (If a group contains no units, it cannot attack.)

The damage an attacking group deals to a defending group depends on the attacking group's attack type and the defending group's immunities and weaknesses. By default, an attacking group would deal damage equal to its effective power to the defending group. However, if the defending group is immune to the attacking group's attack type, the defending group instead takes no damage; if the defending group is weak to the attacking group's attack type, the defending group instead takes double damage.

The defending group only loses whole units from damage; damage is always dealt in such a way that it kills the most units possible, and any remaining damage to a unit that does not immediately kill it is ignored. For example, if a defending group contains 10 units with 10 hit points each and receives 75 damage, it loses exactly 7 units and is left with 3 units at full health.

After the fight is over, if both armies still contain units, a new fight begins; combat only ends once one army has lost all of its units.

For example, consider the following armies:

Immune System:
17 units each with 5390 hit points (weak to radiation, bludgeoning) with
an attack that does 4507 fire damage at initiative 2
989 units each with 1274 hit points (immune to fire; weak to bludgeoning,
slashing) with an attack that does 25 slashing damage at initiative 3

Infection:
801 units each with 4706 hit points (weak to radiation) with an attack
that does 116 bludgeoning damage at initiative 1
4485 units each with 2961 hit points (immune to radiation; weak to fire,
cold) with an attack that does 12 slashing damage at initiative 4

If these armies were to enter combat, the following fights, including details during the target selection and attacking phases, would take place:

Immune System:
Group 1 contains 17 units
Group 2 contains 989 units
Infection:
Group 1 contains 801 units
Group 2 contains 4485 units

Infection group 1 would deal defending group 1 185832 damage
Infection group 1 would deal defending group 2 185832 damage
Infection group 2 would deal defending group 2 107640 damage
Immune System group 1 would deal defending group 1 76619 damage
Immune System group 1 would deal defending group 2 153238 damage
Immune System group 2 would deal defending group 1 24725 damage

Infection group 2 attacks defending group 2, killing 84 units
Immune System group 2 attacks defending group 1, killing 4 units
Immune System group 1 attacks defending group 2, killing 51 units
Infection group 1 attacks defending group 1, killing 17 units

Immune System:
Group 2 contains 905 units
Infection:
Group 1 contains 797 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 184904 damage
Immune System group 2 would deal defending group 1 22625 damage
Immune System group 2 would deal defending group 2 22625 damage

Immune System group 2 attacks defending group 1, killing 4 units
Infection group 1 attacks defending group 2, killing 144 units

Immune System:
Group 2 contains 761 units
Infection:
Group 1 contains 793 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 183976 damage
Immune System group 2 would deal defending group 1 19025 damage
Immune System group 2 would deal defending group 2 19025 damage

Immune System group 2 attacks defending group 1, killing 4 units
Infection group 1 attacks defending group 2, killing 143 units

Immune System:
Group 2 contains 618 units
Infection:
Group 1 contains 789 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 183048 damage
Immune System group 2 would deal defending group 1 15450 damage
Immune System group 2 would deal defending group 2 15450 damage

Immune System group 2 attacks defending group 1, killing 3 units
Infection group 1 attacks defending group 2, killing 143 units

Immune System:
Group 2 contains 475 units
Infection:
Group 1 contains 786 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 182352 damage
Immune System group 2 would deal defending group 1 11875 damage
Immune System group 2 would deal defending group 2 11875 damage

Immune System group 2 attacks defending group 1, killing 2 units
Infection group 1 attacks defending group 2, killing 142 units

Immune System:
Group 2 contains 333 units
Infection:
Group 1 contains 784 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 181888 damage
Immune System group 2 would deal defending group 1 8325 damage
Immune System group 2 would deal defending group 2 8325 damage

Immune System group 2 attacks defending group 1, killing 1 unit
Infection group 1 attacks defending group 2, killing 142 units

Immune System:
Group 2 contains 191 units
Infection:
Group 1 contains 783 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 181656 damage
Immune System group 2 would deal defending group 1 4775 damage
Immune System group 2 would deal defending group 2 4775 damage

Immune System group 2 attacks defending group 1, killing 1 unit
Infection group 1 attacks defending group 2, killing 142 units

Immune System:
Group 2 contains 49 units
Infection:
Group 1 contains 782 units
Group 2 contains 4434 units

Infection group 1 would deal defending group 2 181424 damage
Immune System group 2 would deal defending group 1 1225 damage
Immune System group 2 would deal defending group 2 1225 damage

Immune System group 2 attacks defending group 1, killing 0 units
Infection group 1 attacks defending group 2, killing 49 units

Immune System:
No groups remain.
Infection:
Group 1 contains 782 units
Group 2 contains 4434 units

In the example above, the winning army ends up with 782 + 4434 = 5216 units.

You scan the reindeer's condition (your puzzle input); the white-bearded man looks nervous. As it stands now, how many units would the winning army have?

--- Part Two ---

Things aren't looking good for the reindeer. The man asks whether more milk and cookies would help you think.

If only you could give the reindeer's immune system a boost, you might be able to change the outcome of the combat.

A boost is an integer increase in immune system units' attack damage. For example, if you were to boost the above example's immune system's units by 1570, the armies would instead look like this:

Immune System:
17 units each with 5390 hit points (weak to radiation, bludgeoning) with
an attack that does 6077 fire damage at initiative 2
989 units each with 1274 hit points (immune to fire; weak to bludgeoning,
slashing) with an attack that does 1595 slashing damage at initiative 3

Infection:
801 units each with 4706 hit points (weak to radiation) with an attack
that does 116 bludgeoning damage at initiative 1
4485 units each with 2961 hit points (immune to radiation; weak to fire,
cold) with an attack that does 12 slashing damage at initiative 4

With this boost, the combat proceeds differently:

Immune System:
Group 2 contains 989 units
Group 1 contains 17 units
Infection:
Group 1 contains 801 units
Group 2 contains 4485 units

Infection group 1 would deal defending group 2 185832 damage
Infection group 1 would deal defending group 1 185832 damage
Infection group 2 would deal defending group 1 53820 damage
Immune System group 2 would deal defending group 1 1577455 damage
Immune System group 2 would deal defending group 2 1577455 damage
Immune System group 1 would deal defending group 2 206618 damage

Infection group 2 attacks defending group 1, killing 9 units
Immune System group 2 attacks defending group 1, killing 335 units
Immune System group 1 attacks defending group 2, killing 32 units
Infection group 1 attacks defending group 2, killing 84 units

Immune System:
Group 2 contains 905 units
Group 1 contains 8 units
Infection:
Group 1 contains 466 units
Group 2 contains 4453 units

Infection group 1 would deal defending group 2 108112 damage
Infection group 1 would deal defending group 1 108112 damage
Infection group 2 would deal defending group 1 53436 damage
Immune System group 2 would deal defending group 1 1443475 damage
Immune System group 2 would deal defending group 2 1443475 damage
Immune System group 1 would deal defending group 2 97232 damage

Infection group 2 attacks defending group 1, killing 8 units
Immune System group 2 attacks defending group 1, killing 306 units
Infection group 1 attacks defending group 2, killing 29 units

Immune System:
Group 2 contains 876 units
Infection:
Group 2 contains 4453 units
Group 1 contains 160 units

Infection group 2 would deal defending group 2 106872 damage
Immune System group 2 would deal defending group 2 1397220 damage
Immune System group 2 would deal defending group 1 1397220 damage

Infection group 2 attacks defending group 2, killing 83 units
Immune System group 2 attacks defending group 2, killing 427 units

After a few fights...

Immune System:
Group 2 contains 64 units
Infection:
Group 2 contains 214 units
Group 1 contains 19 units

Infection group 2 would deal defending group 2 5136 damage
Immune System group 2 would deal defending group 2 102080 damage
Immune System group 2 would deal defending group 1 102080 damage

Infection group 2 attacks defending group 2, killing 4 units
Immune System group 2 attacks defending group 2, killing 32 units

Immune System:
Group 2 contains 60 units
Infection:
Group 1 contains 19 units
Group 2 contains 182 units

Infection group 1 would deal defending group 2 4408 damage
Immune System group 2 would deal defending group 1 95700 damage
Immune System group 2 would deal defending group 2 95700 damage

Immune System group 2 attacks defending group 1, killing 19 units

Immune System:
Group 2 contains 60 units
Infection:
Group 2 contains 182 units

Infection group 2 would deal defending group 2 4368 damage
Immune System group 2 would deal defending group 2 95700 damage

Infection group 2 attacks defending group 2, killing 3 units
Immune System group 2 attacks defending group 2, killing 30 units

After a few more fights...

Immune System:
Group 2 contains 51 units
Infection:
Group 2 contains 40 units

Infection group 2 would deal defending group 2 960 damage
Immune System group 2 would deal defending group 2 81345 damage

Infection group 2 attacks defending group 2, killing 0 units
Immune System group 2 attacks defending group 2, killing 27 units

Immune System:
Group 2 contains 51 units
Infection:
Group 2 contains 13 units

Infection group 2 would deal defending group 2 312 damage
Immune System group 2 would deal defending group 2 81345 damage

Infection group 2 attacks defending group 2, killing 0 units
Immune System group 2 attacks defending group 2, killing 13 units

Immune System:
Group 2 contains 51 units
Infection:
No groups remain.

This boost would allow the immune system's armies to win! It would be left with 51 units.

You don't even know how you could boost the reindeer's immune system or what effect it might have, so you need to be cautious and find the smallest boost that would allow the immune system to win.

How many units does the immune system have left after getting the smallest boost it needs to win?

Input:
Immune System:
337 units each with 6482 hit points (weak to radiation, fire; immune to cold, bludgeoning) with an attack that does 189 slashing damage at initiative 15
571 units each with 3178 hit points (weak to fire) with an attack that does 47 slashing damage at initiative 12
116 units each with 7940 hit points with an attack that does 638 fire damage at initiative 18
6017 units each with 9349 hit points (weak to cold) with an attack that does 14 cold damage at initiative 6
2246 units each with 4002 hit points (weak to radiation, slashing) with an attack that does 16 cold damage at initiative 3
3950 units each with 4493 hit points (weak to bludgeoning; immune to radiation, fire) with an attack that does 10 radiation damage at initiative 8
7494 units each with 1141 hit points (immune to bludgeoning) with an attack that does 1 cold damage at initiative 17
2501 units each with 9007 hit points with an attack that does 35 cold damage at initiative 7
844 units each with 3222 hit points (immune to bludgeoning, slashing) with an attack that does 37 radiation damage at initiative 9
1371 units each with 3695 hit points (immune to cold) with an attack that does 25 cold damage at initiative 10

Infection:
2295 units each with 16577 hit points (immune to radiation) with an attack that does 12 fire damage at initiative 13
837 units each with 6736 hit points (weak to fire) with an attack that does 14 radiation damage at initiative 19
2841 units each with 9360 hit points (immune to bludgeoning; weak to radiation, cold) with an attack that does 6 fire damage at initiative 14
7374 units each with 51597 hit points (weak to cold; immune to bludgeoning, fire) with an attack that does 12 radiation damage at initiative 1
1544 units each with 29226 hit points (weak to fire, bludgeoning) with an attack that does 35 bludgeoning damage at initiative 5
293 units each with 13961 hit points (immune to slashing; weak to radiation) with an attack that does 79 radiation damage at initiative 2
1219 units each with 38142 hit points (immune to cold, fire) with an attack that does 53 bludgeoning damage at initiative 4
5233 units each with 30595 hit points (weak to bludgeoning, cold; immune to fire) with an attack that does 11 radiation damage at initiative 11
397 units each with 43710 hit points (weak to slashing, radiation; immune to cold, bludgeoning) with an attack that does 171 slashing damage at initiative 16
1316 units each with 36203 hit points (weak to slashing, bludgeoning) with an attack that does 50 cold damage at initiative 20

Part 1:
class ArmyGroup
{
	public string Source;
	
	public int UnitCount;
	public int HitPoints;
	public List<string> Weakness = new List<string>();
	public List<string> Immunity = new List<string>();
	public string DamageType;
	public int DamageValue;
	public int Initiative;

	public int EffectivePower => UnitCount * DamageValue;
	public bool Alive => UnitCount>0;
	
	public ArmyGroup NextTarget = null;
	public bool IsTargeted = false;
}

void Main()
{
	var groups = Load(File.ReadAllLines(Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath), @"24_input.txt")));

	for(int gen=0;;gen++) 
	{
		if (!(groups.GroupBy(g => g.Source).All(g => g.Any(a => a.Alive)))) break;

		Fight(groups);
	}

	groups
		.GroupBy(g => g.Source)
		.Select(g => (g.Key, g.Sum(a => a.UnitCount)))
		.Dump();
}

List<ArmyGroup> Load(string[] lines)
{
	return new[]
	{
		lines.Skip(1).TakeWhile(l => !string.IsNullOrWhiteSpace(l)).Select(l => LoadSingle("ImmuneSystem", l)),
		lines.Skip(1).SkipWhile(l => !string.IsNullOrWhiteSpace(l)).Skip(2).Select(l => LoadSingle("Infection", l))
	}
	.SelectMany(p=>p)
	.ToList();
}

ArmyGroup LoadSingle(string src, string line)
{
	var ag = new ArmyGroup { Source=src };

	var i1 = line.IndexOf(' ');
	ag.UnitCount = int.Parse(line.Substring(0, i1).Trim());
	line = line.Substring(i1).Trim().Substring(15).Trim();

	var i6 = line.IndexOf(' ');
	ag.HitPoints = int.Parse(line.Substring(0, i6).Trim());
	line = line.Substring(i6).Trim().Substring(11).Trim();
	
	var i2 = line.IndexOf(')');
	if (i2 != -1)
	{
		var spec0 = line.Substring(1, i2).TrimEnd(')');
		line = line.Substring(1).Substring(i2).Substring(1).Trim();

		foreach (var spc in spec0.Split(';').Select(p => p.Trim()))
		{
			if (spc.StartsWith("weak to")) ag.Weakness.AddRange(spc.Substring("weak to".Length).Trim().Split(',').Select(p => p.Trim()));
			if (spc.StartsWith("immune to")) ag.Immunity.AddRange(spc.Substring("immune to".Length).Trim().Split(',').Select(p => p.Trim()));
		}
	}
	line = line.Substring(25).Trim();

	var i3 = line.IndexOf(' ');
	ag.DamageValue = int.Parse(line.Substring(0, i3).Trim());
	line = line.Substring(i3).Trim().Trim();

	var i4 = line.IndexOf(' ');
	ag.DamageType = line.Substring(0, i4).Trim();
	line = line.Substring(i4).Trim().Trim();

	var i5 = line.LastIndexOf(' ');
	ag.Initiative = int.Parse(line.Substring(i5).Trim());

	return ag;
}

void Fight(List<ArmyGroup> groups)
{
	// PHASE 1

	foreach (var g in groups) { g.IsTargeted=false; g.NextTarget=null; }
	
	foreach (var g in groups.Where(g => g.Alive).OrderByDescending(g => g.EffectivePower).ThenByDescending(g => g.Initiative))
	{
		SelectTarget(g, groups);
	}

	// PHASE 2

	foreach (var g in groups.Where(g => g.Alive).OrderByDescending(g => g.Initiative).Where(g => g.NextTarget!=null))
	{
		Attack(g, g.NextTarget);
	}
}

void SelectTarget(ArmyGroup att, List<ArmyGroup> groups)
{
	att.NextTarget = groups
		.Where(g => g.Alive)
		.Where(g => g.Source != att.Source)
		.Where(g => !g.IsTargeted)
		.Where(g => CalcFullDamage(att, g)>0)
		.OrderByDescending(g => CalcFullDamage(att, g))
		.ThenByDescending(g => g.EffectivePower)
		.ThenByDescending(g => g.Initiative)
		.FirstOrDefault();
	if (att.NextTarget != null) att.NextTarget.IsTargeted = true;
}

int CalcFullDamage(ArmyGroup att, ArmyGroup def)
{
	if (att.UnitCount==0) return 0;

	var dmg = att.EffectivePower;
	if (def.Immunity.Contains(att.DamageType)) return 0;
	if (def.Weakness.Contains(att.DamageType)) return dmg*2;
	return dmg;
}

void Attack(ArmyGroup att, ArmyGroup def)
{
	var dmg = CalcFullDamage(att, def);

	def.UnitCount -= (int)(dmg / def.HitPoints);
	if (def.UnitCount<0) def.UnitCount = 0;
	
}
Result: 21070

Part 2:
class ArmyGroup
{
	public string Source;
	
	public int UnitCount;
	public int HitPoints;
	public List<string> Weakness = new List<string>();
	public List<string> Immunity = new List<string>();
	public string DamageType;
	public int DamageValue;
	public int Initiative;

	public int EffectivePower => UnitCount * DamageValue;
	public bool Alive => UnitCount>0;
	
	public ArmyGroup NextTarget = null;
	public bool IsTargeted = false;
}

void Main() => Enumerable.Range(0, int.MaxValue).Select(Calc).First(b=>b>0).Dump();

int Calc(int boost)
{
	var groups = Load(File.ReadAllLines(Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath), @"24_input.txt")));

	foreach(var g in groups.Where(p => p.Source=="ImmuneSystem")) g.DamageValue += boost;

	for (int gen = 0; ; gen++)
	{
		if (!(groups.GroupBy(g => g.Source).All(g => g.Any(a => a.Alive)))) break;

		bool dmg = Fight(groups);
		
		if (!dmg) return 0;
	}

	return groups.Where(p => p.Source=="ImmuneSystem").Sum(p => p.UnitCount) - groups.Where(p => p.Source=="Infection").Sum(p => p.UnitCount);
}

List<ArmyGroup> Load(string[] lines)
{
	return new[]
	{
		lines.Skip(1).TakeWhile(l => !string.IsNullOrWhiteSpace(l)).Select(l => LoadSingle("ImmuneSystem", l)),
		lines.Skip(1).SkipWhile(l => !string.IsNullOrWhiteSpace(l)).Skip(2).Select(l => LoadSingle("Infection", l))
	}
	.SelectMany(p=>p)
	.ToList();
}

ArmyGroup LoadSingle(string src, string line)
{
	var ag = new ArmyGroup { Source=src };

	var i1 = line.IndexOf(' ');
	ag.UnitCount = int.Parse(line.Substring(0, i1).Trim());
	line = line.Substring(i1).Trim().Substring(15).Trim();

	var i6 = line.IndexOf(' ');
	ag.HitPoints = int.Parse(line.Substring(0, i6).Trim());
	line = line.Substring(i6).Trim().Substring(11).Trim();
	
	var i2 = line.IndexOf(')');
	if (i2 != -1)
	{
		var spec0 = line.Substring(1, i2).TrimEnd(')');
		line = line.Substring(1).Substring(i2).Substring(1).Trim();

		foreach (var spc in spec0.Split(';').Select(p => p.Trim()))
		{
			if (spc.StartsWith("weak to")) ag.Weakness.AddRange(spc.Substring("weak to".Length).Trim().Split(',').Select(p => p.Trim()));
			if (spc.StartsWith("immune to")) ag.Immunity.AddRange(spc.Substring("immune to".Length).Trim().Split(',').Select(p => p.Trim()));
		}
	}
	line = line.Substring(25).Trim();

	var i3 = line.IndexOf(' ');
	ag.DamageValue = int.Parse(line.Substring(0, i3).Trim());
	line = line.Substring(i3).Trim().Trim();

	var i4 = line.IndexOf(' ');
	ag.DamageType = line.Substring(0, i4).Trim();
	line = line.Substring(i4).Trim().Trim();

	var i5 = line.LastIndexOf(' ');
	ag.Initiative = int.Parse(line.Substring(i5).Trim());

	return ag;
}

bool Fight(List<ArmyGroup> groups)
{
	// PHASE 1

	foreach (var g in groups) { g.IsTargeted=false; g.NextTarget=null; }
	
	foreach (var g in groups.Where(g => g.Alive).OrderByDescending(g => g.EffectivePower).ThenByDescending(g => g.Initiative))
	{
		SelectTarget(g, groups);
	}

	// PHASE 2

	bool d = false;

	foreach (var g in groups.Where(g => g.Alive).OrderByDescending(g => g.Initiative).Where(g => g.NextTarget!=null))
	{
		var a = Attack(g, g.NextTarget);
		if (a)d=true;
	}
	return d;
}

void SelectTarget(ArmyGroup att, List<ArmyGroup> groups)
{
	att.NextTarget = groups
		.Where(g => g.Alive)
		.Where(g => g.Source != att.Source)
		.Where(g => !g.IsTargeted)
		.Where(g => CalcFullDamage(att, g)>0)
		.OrderByDescending(g => CalcFullDamage(att, g))
		.ThenByDescending(g => g.EffectivePower)
		.ThenByDescending(g => g.Initiative)
		.FirstOrDefault();
	if (att.NextTarget != null) att.NextTarget.IsTargeted = true;
}

int CalcFullDamage(ArmyGroup att, ArmyGroup def)
{
	if (att.UnitCount==0) return 0;

	var dmg = att.EffectivePower;
	if (def.Immunity.Contains(att.DamageType)) return 0;
	if (def.Weakness.Contains(att.DamageType)) return dmg*2;
	return dmg;
}

bool Attack(ArmyGroup att, ArmyGroup def)
{
	var dmg = CalcFullDamage(att, def);
	var kill = (int)(dmg / def.HitPoints);
	def.UnitCount -= kill;
	if (def.UnitCount<0) def.UnitCount = 0;
	return kill>0;
	
}
Result: 7500


made with vanilla PHP and MySQL, no frameworks, no bootstrap, no unnecessary* javascript