-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay7.cs
More file actions
48 lines (41 loc) · 1.33 KB
/
Day7.cs
File metadata and controls
48 lines (41 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections;
public class Day7
{
public static async Task<string> Part1Async(bool example = false)
{
var data = await ParseInput(example);
var maxpos = data.Max();
var mincost = int.MaxValue;
for (int p = 0; p <= maxpos; p++)
{
var cost = data.Select(d => Math.Abs(d - p)).Sum();
if (cost < mincost)
mincost = cost;
Console.WriteLine($"{p}: {cost} ({mincost})");
}
return mincost.ToString();
}
public static async Task<string> Part2Async(bool example = false)
{
var data = await ParseInput(example);
var maxpos = data.Max();
var mincost = int.MaxValue;
for (int p = 0; p <= maxpos; p++)
{
var cost = data.Select(d =>
{
var n = Math.Abs(d - p);
return (n*(n+1)/2);
}).Sum();
if (cost < mincost)
mincost = cost;
Console.WriteLine($"{p}: {cost} ({mincost})");
}
return mincost.ToString();
}
private static async Task<IEnumerable<int>> ParseInput(bool example)
{
var input = await File.ReadAllTextAsync($"inputs/day7{(example ? ".example" : string.Empty)}.txt");
return input.Split(",").Select(i => int.Parse(i));
}
}