-
Notifications
You must be signed in to change notification settings - Fork 0
/
day2.cs
76 lines (73 loc) · 1.71 KB
/
day2.cs
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// https://adventofcode.com/2018/day/2
// Returns checksum of ID's with 2x * 3x of duplicate characters
static int Day2a(string[] lines)
{
int twos = 0;
int threes = 0;
foreach (string id in lines)
{
int[] letters = new int[26];
for (int i = 0; i < id.Length; ++i)
{
int bit = id[i] - 'a';
if (bit >= 0 && bit <= 25)
{
letters[bit] += 1;
}
else
{
throw new Exception("Invalid letter [" + id[i] + "] in line=" + id);
}
}
int b2 = 0;
int b3 = 0;
for (int i = 0; i < letters.Length; ++i)
{
if (letters[i] == 2) b2 = 1;
if (letters[i] == 3) b3 = 1;
}
twos += b2;
threes += b3;
}
return twos * threes;
}
// Returns the index of first different character or (-1) if none
static int Diff(string id1, string id2)
{
if (id1.Length == id2.Length)
{
#if false
for (int i = 0; i < id1.Length; ++i)
{
if (id1[i] != id2[i])
{
return i;
}
}
#else
return id1.TakeWhile((ch,i) => ch == id2[i]).Count();
#endif
}
return -1;
}
// Searches for two ID strings with a single character difference
// Returns the ID without the mis-matched character or null
static string Day2b(string[] lines)
{
for (int i = 0; i < lines.Length-1; ++i)
{
string id1 = lines[i];
for (int j = i+1; j < lines.Length; ++j)
{
int pos = Diff(lines[i], lines[j]);
if (pos >= 0)
{
if (lines[i].Substring(pos + 1) == lines[j].Substring(pos + 1))
{
return lines[i].Remove(pos, 1);
}
}
}
}
return null;
}