-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
327 lines (302 loc) · 12.7 KB
/
Program.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
using Advent_of_Code_2020.StatsBuilder;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
//using System.Text.Json;
using System.Threading.Tasks;
using Draco18s.AoCLib;
namespace AdventofCode2022 {
static class Program {
private const bool CUSTOM_LEADERBOARD = true;
private const float MAX_EXPECTED = 4f;
private const string year = "2022";
private static readonly Uri baseAddress = new Uri("https://adventofcode.com");
private const string leaderboardURI = "{0}/leaderboard/private/view/{1}.json";
private static Dictionary<string,List<string>> conf;
private static string puzzleNum = "25";
static void Main(string[] args) {
#region config
string path = Path.GetFullPath("./../../../inputs/config.json");
if (!File.Exists(path))
{
Console.WriteLine("Create config file");
conf = new Dictionary<string, List<string>>();
conf.Add("sessionID", new List<string>(new string[] { "leaderboard" }));
string dat = System.Text.Json.JsonSerializer.Serialize<Dictionary<string, List<string>>>(conf);
StreamWriter writer = File.CreateText(path);
writer.Write(dat);
writer.Flush();
writer.Close();
return;
}
string confj = File.ReadAllText(path);
conf = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,List<string>>>(confj);
#endregion
#region puzzle input
string p = Path.GetFullPath(string.Format("./../../../inputs/day{0}.txt", puzzleNum));
if(!File.Exists(p)) {
Task.Run(async () => {
string puzzleInput = await GetInputFor(puzzleNum, conf.Keys.First());
File.WriteAllText(p, puzzleInput);
Main(args);
});
}
#endregion
else
{
string input = File.ReadAllText(p);
input = input.Replace("\r", "");
if(input[input.Length - 1] == '\n')
input = input.Substring(0, input.Length - 1); //stupid trailing newline
//string input = @"";
DateTime s = DateTime.Now;
long result = DayTwentyfive.Part1(input);
DateTime e = DateTime.Now;
Console.WriteLine(result);
Console.WriteLine("Time: " + (e - s).TotalMilliseconds);
s = DateTime.Now;
result = DayTwentyfive.Part2(input);
e = DateTime.Now;
Console.WriteLine(result);
Console.WriteLine("Time: " + (e - s).TotalMilliseconds);
BuildLeaderboard();
}
Console.Read();
}
static void BuildLeaderboard() {
Task.Run(async () => {
AoCLeaderboard obj;
List<AoCUser> users = new List<AoCUser>();
foreach(string k in conf.Keys) {
List<string> boards = conf[k];
foreach(string b in boards) {
string input = await GetFromAsync(string.Format(leaderboardURI,year,b), k);
//string input = Path.GetFullPath("./../../../inputs/lb.txt");
try
{
obj = Newtonsoft.Json.JsonConvert.DeserializeObject<AoCLeaderboard>(input);
//obj = JsonSerializer.Deserialize<AoCLeaderboard>(input);
foreach (AoCUser u in obj.members.Values)
{
if (u.name == null)
{
u.name = "(anonymous user #" + u.id + ")";
}
if (u.id.Equals("1081403") || users.Contains(u)) continue;
users.Add(u);
}
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
}
string mainTable = "<table> <tbody> <tr> <td class=\"typeheader\" colspan=\"3\">(25 items)<span class=\"fixedextenser\">4</span></td></tr><tr> <th title=\"System.String\">day</th> <th title=\"System.String,System.DateTime,System.Int32[]\">silver_order</th> <th title=\"System.String,System.DateTime,System.Int32[]\">gold_order</th> </tr>{0}</tbody></table>";
StringBuilder builder = new StringBuilder();
for(int d = 1; d <= 25; d++) {
if(Count(users, d.ToString(), "1") == 0) break;
builder.Append(GetTableRow(users, d));
}
builder.Append(GetTableRowScores(users));
string htmlTemplate = File.ReadAllText(Path.GetFullPath("./../../../inputs/leaderboard_html.txt"));
htmlTemplate = htmlTemplate.Replace("{", "{{").Replace("}", "}}").Replace("{{0}}", "{0}");
string outputFile = Path.GetFullPath("./../../../leaderboard.html");
if(File.Exists(outputFile)) {
File.Delete(outputFile);
}
File.WriteAllText(outputFile, string.Format(htmlTemplate, string.Format(mainTable, builder.ToString())));
Console.WriteLine("Finished writing leaderboard.");
});
}
private static async Task<string> GetInputFor(string day, string sessionID) {
//var url = new Uri(baseAddress + jsonurl);
var jsonurl = string.Format("{0}{1}/day/{2}/input", baseAddress, year, day);
var cookieContainer = new CookieContainer();
cookieContainer.Add(baseAddress, new Cookie("session", sessionID));
HttpClient httpClient = new HttpClient(
new HttpClientHandler {
CookieContainer = cookieContainer,
AutomaticDecompression = DecompressionMethods.Deflate|DecompressionMethods.GZip,
}) {
BaseAddress = baseAddress,
};
var response = await httpClient.GetAsync(jsonurl);
if(response.IsSuccessStatusCode) {
return await response.Content.ReadAsStringAsync();
}
return string.Empty;
}
private static async Task<string> GetFromAsync(string jsonurl, string sessionID) {
//var url = new Uri(baseAddress + jsonurl);
var cookieContainer = new CookieContainer();
cookieContainer.Add(baseAddress, new Cookie("session", sessionID));
HttpClient httpClient = new HttpClient(
new HttpClientHandler {
CookieContainer = cookieContainer,
AutomaticDecompression = DecompressionMethods.Deflate|DecompressionMethods.GZip,
}) {
BaseAddress = baseAddress,
};
var response = await httpClient.GetAsync(jsonurl);
if(response.IsSuccessStatusCode) {
return await response.Content.ReadAsStringAsync();
}
return string.Empty;
}
private static string GetTableRow(List<AoCUser> users, int d) {
string tablerowtable = "<tr> <td>{4}</td><td> <table> <tbody> <tr> <td class=\"typeheader\" colspan=\"3\">ø[{2}] <span class=\"fixedextenser\">4</span></td></tr><tr> <th title=\"System.String\">name</th> <th title=\"System.DateTime\">get_star_ts</th> <th title=\"System.Int32\">value</th> </tr>{0}</tbody> </table> </td><td> <table> <tbody> <tr> <td class=\"typeheader\" colspan=\"3\">ø[{3}] <span class=\"fixedextenser\">4</span></td></tr><tr> <th title=\"System.String\">name</th> <th title=\"System.DateTime\">get_star_ts</th> <th title=\"System.Int32\">value</th> </tr>{1}</tbody> </table> </td></tr>";
string day = d.ToString();
string[] parts = new string[2];
parts[0] = "";
parts[1] = "";
DateTime start = new DateTime(2022, (d>1?12:11), (d>1?d-1:30));
start = start.AddHours(23);
double avg = users.Where(x => x.completion_day_level.ContainsKey(day) && x.completion_day_level[day].ContainsKey("1")).Where(
x =>
{
TimeSpan dur = x.completion_day_level[day]["1"].dateTime - start;
return dur.TotalHours <= MAX_EXPECTED;
}).Average(x => (x.completion_day_level[day]["1"].dateTime - start).TotalSeconds);
TimeSpan averageTime = new TimeSpan(0, 0, (int)avg);
for (int p = 1; p <= 2; p++) {
string part = p.ToString();
SortUsers(ref users, day, part);
foreach(AoCUser user in users) {
int pts = GetPointsForUser(ref users, user.id, day, part);
if(d > 0)
user.locPoints += pts;
parts[p - 1] += GetUserLineScore(user, day, part, pts, averageTime);
}
}
return string.Format(tablerowtable, parts[0], parts[1], Count(users, day, "1"), Count(users, day, "2"), day);
}
private static string GetTableRowScores(List<AoCUser> users) {
users.Sort((x, y) => y.locPoints.CompareTo(x.locPoints));
string tablerowtable = "<tr> <td>{2}</td><td> <table> <tbody> <tr> <td class=\"typeheader\" colspan=\"3\">ø[{1}] <span class=\"fixedextenser\">4</span></td></tr><tr> <th title=\"System.String\">name</th> <th title=\"System.Int32\">total</th> </tr>{0}</tbody> </table> </td> </table> </td></tr>";
string row = "";
foreach(AoCUser user in users) {
int pts = user.locPoints;
//user.locPoints += pts;
row += GetUserTotalScore(user, pts);
}
return string.Format(tablerowtable, row, users.Count, "Total");
}
private static int Count(List<AoCUser> users, string day, string part) {
return users.Count(x => {
return x.completion_day_level.ContainsKey(day) && x.completion_day_level[day].ContainsKey(part);
});
}
private static void SortUsers(ref List<AoCUser> users, string day, string part) {
int d = int.Parse(day);
DateTime start = new DateTime(2022, (d > 1 ? 12 : 11), (d > 1 ? d - 1 : 30));
start = start.AddHours(23);
double avg = users.Where(x => x.completion_day_level.ContainsKey(day) && x.completion_day_level[day].ContainsKey("1")).Where(
x =>
{
TimeSpan dur = x.completion_day_level[day]["1"].dateTime - start;
return dur.TotalHours <= MAX_EXPECTED;
}).Average(x => (x.completion_day_level[day]["1"].dateTime - start).TotalSeconds);
TimeSpan averageTime = new TimeSpan(0, 0, (int)avg);
users.Sort((x, y) => {
bool xhas = true;
bool yhas = true;
if(!y.completion_day_level.ContainsKey(day) || !y.completion_day_level[day].ContainsKey(part)) {
yhas = false;
}
if(!x.completion_day_level.ContainsKey(day) || !x.completion_day_level[day].ContainsKey(part)) {
xhas = false;
}
if (xhas && yhas)
{
if(!CUSTOM_LEADERBOARD)
return x.completion_day_level[day][part].dateTime.CompareTo(y.completion_day_level[day][part].dateTime);
if (part == "1")
{
TimeSpan xDur, yDur;
if((x.completion_day_level[day][part].dateTime - start).TotalHours > MAX_EXPECTED)
{
DateTime s = (x.completion_day_level[day][part].dateTime - averageTime);
int extra = s.Minute % 15;
s = s.AddMinutes(-extra);
xDur = x.completion_day_level[day][part].dateTime - s;
}
else
{
xDur = (x.completion_day_level[day][part].dateTime - start);
}
if ((y.completion_day_level[day][part].dateTime - start).TotalHours > MAX_EXPECTED)
{
DateTime s = (y.completion_day_level[day][part].dateTime - averageTime);
int extra = s.Minute % 15;
s = s.AddMinutes(-extra);
yDur = y.completion_day_level[day][part].dateTime - s;
}
else
{
yDur = (y.completion_day_level[day][part].dateTime - start);
}
return xDur.CompareTo(yDur);
//return x.completion_day_level[day][part].dateTime.CompareTo(y.completion_day_level[day][part].dateTime);
}
var d1 = (x.completion_day_level[day]["2"].dateTime - x.completion_day_level[day]["1"].dateTime);
var d2 = (y.completion_day_level[day]["2"].dateTime - y.completion_day_level[day]["1"].dateTime);
return d1.CompareTo(d2);
}
else
return yhas.CompareTo(xhas);
});
}
private static int GetPointsForUser(ref List<AoCUser> users, string user, string day, string part) {
//if (part == "1") return 0;
int i = users.FindIndex(x => x.id == user);
if(users[i].completion_day_level.ContainsKey(day) && users[i].completion_day_level[day].ContainsKey(part))
return users.Count - i;
return 0;
}
private static string GetUserLineScore(AoCUser user, string day, string part, int pts, TimeSpan averageTime)
{
int d = int.Parse(day);
DateTime start = new DateTime(2022, (d > 1 ? 12 : 11), (d > 1 ? d - 1 : 30));
start = start.AddHours(23);
string p = "<tr><td>{0}</td><td>{1}</td><td class=\"n\">{2}</td></tr>";
if (user.completion_day_level.ContainsKey(day) && user.completion_day_level[day].ContainsKey(part))
{
if(!CUSTOM_LEADERBOARD)
return string.Format(p, user.name, user.completion_day_level[day][part].dateTime.ToString("M/d/yyyy h:mm:ss tt"), pts);
if (part == "1")
{
TimeSpan yDur;
if ((user.completion_day_level[day][part].dateTime - start).TotalHours > MAX_EXPECTED)
{
DateTime s = (user.completion_day_level[day][part].dateTime - averageTime);
int extra = s.Minute % 15;
s = s.AddMinutes(-extra);
yDur = user.completion_day_level[day][part].dateTime - s;
}
else
{
yDur = (user.completion_day_level[day][part].dateTime - start);
}
return string.Format(p, user.name, yDur.ToString(), pts);
}
TimeSpan dur = (user.completion_day_level[day]["2"].dateTime - user.completion_day_level[day]["1"].dateTime);
return string.Format(p, user.name, dur.ToString(), pts);
}
long.TryParse(user.last_star_ts.ToString(), out long last);
if(last == 0)
return string.Empty;
return string.Format(p, user.name, "----", "0");
}
private static string GetUserTotalScore(AoCUser user, int pts) {
if(pts == 0) return string.Empty;
string p = "<tr><td>{0}</td><td class=\"n\">{1}</td></tr>";
return string.Format(p, user.name, pts.ToString());
}
}
}