protohackers/main.ts

75 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-09-26 23:53:34 -05:00
import { BufReader } from "https://deno.land/std@0.157.0/io/buffer.ts";
2022-09-23 14:39:50 -05:00
import { ByteSet } from "https://deno.land/x/bytes@1.0.3/mod.ts";
2022-09-23 13:33:17 -05:00
2022-09-26 20:57:53 -05:00
const QUERY_SIZE = 9;
const PORT = 5588;
2022-09-23 13:33:17 -05:00
2022-09-26 20:57:53 -05:00
const listener = Deno.listen({ port: 5588 });
console.log(`Listening on 0.0.0.0:${PORT}`);
2022-09-23 13:33:17 -05:00
for await (const conn of listener) {
2022-09-26 20:57:53 -05:00
console.log("Connection established:", conn.remoteAddr);
2022-09-23 14:37:43 -05:00
try {
2022-09-26 20:57:53 -05:00
meansToAnEnd(conn);
2022-09-23 14:37:43 -05:00
} catch (e) {
2022-09-26 20:57:53 -05:00
console.error(conn.remoteAddr, e);
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
console.log("Connection closed:", conn.remoteAddr);
2022-09-23 13:33:17 -05:00
}
2022-09-23 14:37:43 -05:00
// problem 2
2022-09-26 20:57:53 -05:00
async function meansToAnEnd(conn: Deno.Conn) {
2022-09-23 14:37:43 -05:00
try {
2022-09-26 23:53:34 -05:00
const prices = [];
2022-09-26 20:57:53 -05:00
for await (const query of queries(conn)) {
2022-09-26 23:53:34 -05:00
if (query == null) break;
const bs = ByteSet.from(query, "big");
const queryChar = String.fromCharCode(bs.read.uint8());
const a1 = bs.read.int32();
const a2 = bs.read.int32();
if (queryChar == "I") {
console.log(conn.remoteAddr, "Pushing I:", [a1, a2]);
prices.push([a1, a2]);
} else if (queryChar == "Q") {
console.log(conn.remoteAddr, "Querying:", a1, a2);
let numMatches = 0;
let sum = 0;
for (const [ts, price] of prices) {
if (ts < a1 || ts > a2) continue;
numMatches++;
sum += price;
}
let result = Math.floor(sum / numMatches);
if (isNaN(result)) result = 0;
console.log(
conn.remoteAddr,
`Result for ${prices.length} prices: ${sum} / ${numMatches} = ${result}`,
);
const response = new ByteSet(4, "big");
response.write.int32(result);
conn.write(response.buffer);
}
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
console.log("Done!");
} catch (err) {
2022-09-26 23:53:34 -05:00
console.error("Error processing query:", err);
2022-09-23 14:37:43 -05:00
}
}
2022-09-26 20:57:53 -05:00
function queries(conn: Deno.Conn) {
2022-09-23 14:37:43 -05:00
return {
async *[Symbol.asyncIterator]() {
2022-09-26 23:53:34 -05:00
const b = new Uint8Array(9);
const reader = new BufReader(conn, QUERY_SIZE);
try {
while (await reader.readFull(b) != null) {
yield b;
}
} catch (err) {
console.error("Error receiving query:", err);
2022-09-23 14:37:43 -05:00
}
2022-09-26 20:57:53 -05:00
},
};
2022-09-23 14:37:43 -05:00
}