First commit

This commit is contained in:
2024-12-05 00:17:39 +01:00
parent 60634c1b25
commit 42e86ecf5d
11 changed files with 2742 additions and 3 deletions
+1000
View File
File diff suppressed because it is too large Load Diff
+21
View File
@@ -0,0 +1,21 @@
from time import now
from collections import List
from collections.string import atol
from Sort import sort
fn main() raises:
start = now()
with open("day1/input", "r") as f:
content = f.read()
left = List[Int]()
right = List[Int]()
for line in content.split('\n')[0:-1]:
left.append(atol(line[][0:5]))
right.append(atol(line[][8:13]))
print("Took ", (now() - start) / 1_000_000, "ms")
fn sort()
+69
View File
@@ -0,0 +1,69 @@
const std = @import("std");
const print = std.debug.print;
var file_buf: [1024 * 1024]u8 = undefined; // The file do 20kB, I give it 1MB
pub fn main() !void {
const time_start = std.time.microTimestamp();
var left: [1000]i32 = undefined;
var right: [1000]i32 = undefined;
const file = try std.fs.cwd().openFile("day1/input", .{});
defer file.close();
const len = try file.readAll(&file_buf);
var i: u32 = 0;
var iter = std.mem.split(u8, file_buf[0..len], "\n");
while (iter.next()) |line| {
if (i == 1000) continue;
left[i] = try std.fmt.parseInt(i32, line[0..5], 10);
right[i] = try std.fmt.parseInt(i32, line[8..13], 10);
i += 1;
}
std.mem.sort(i32, &left, {}, comptime std.sort.asc(i32));
std.mem.sort(i32, &right, {}, comptime std.sort.asc(i32));
const time_parsing = std.time.microTimestamp();
print("Parsing time: {d}μs\n", .{time_parsing - time_start});
const total_distance = distance(left, right);
const total_similarity = try similarity(left, right);
const time_end = std.time.microTimestamp();
print("Compute time: {d}μs\n", .{time_end - time_parsing});
print("\tDistance: {d}\n", .{total_distance});
print("\tSimilarity: {d}\n", .{total_similarity});
}
fn distance(left: [1000]i32, right: [1000]i32) u32 {
var total_distance: u32 = 0;
for (left, right) |l, r| {
total_distance += @abs(r - l);
}
return total_distance;
}
fn similarity(left: [1000]i32, right: [1000]i32) !i32 {
// Make a map with value -> occurence
var buff: [1024 * 100]u8 = undefined;
var fbuf = std.heap.FixedBufferAllocator.init(&buff);
const allocator = fbuf.allocator();
var map = std.AutoHashMap(i32, u8).init(allocator);
defer map.deinit();
for (right) |r| {
if (map.get(r)) |r_count| {
try map.put(r, r_count + 1);
} else {
try map.put(r, 1);
}
}
var total_similarity: i32 = 0;
for (left) |l| {
if (map.get(l)) |r_count| total_similarity += l * r_count;
}
return total_similarity;
}