Skip to content

Commit 6987b98

Browse files
committed
day1 many languages
1 parent db3d44e commit 6987b98

File tree

7 files changed

+279
-3
lines changed

7 files changed

+279
-3
lines changed

2024/day1/day1.c

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
// cc -o day1 -Wall -O2 day1.c
2+
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
#include <string.h>
6+
#include <inttypes.h>
7+
#include <stdbool.h>
8+
#include <time.h>
9+
#include <stdarg.h>
10+
#include <unistd.h>
11+
#include <signal.h>
12+
#include <sys/time.h>
13+
#include <sys/types.h>
14+
#include <sys/stat.h>
15+
16+
static int int_cmp(const void *a, const void *b)
17+
{
18+
return *(int *)a - *(int *)b;
19+
}
20+
21+
int main(int argc, char *argv[])
22+
{
23+
FILE *f;
24+
int a, b;
25+
int *left = NULL, *right = NULL;
26+
size_t size = 0;
27+
size_t n = 0;
28+
29+
if (argc >= 2)
30+
f = fopen(argv[1], "r");
31+
else
32+
f = fopen("input.txt", "r");
33+
34+
while (fscanf(f, "%d %d", &a, &b) == 2)
35+
{
36+
if (n >= size)
37+
{
38+
size += 16;
39+
left = (int *)realloc(left, size * sizeof(int));
40+
right = (int *)realloc(right, size * sizeof(int));
41+
}
42+
left[n] = a;
43+
right[n] = b;
44+
n += 1;
45+
}
46+
47+
qsort(left, n, sizeof(int), int_cmp);
48+
qsort(right, n, sizeof(int), int_cmp);
49+
50+
// part 1
51+
int part1 = 0;
52+
for (size_t i = 0; i < n; ++i)
53+
{
54+
part1 += abs(left[i] - right[i]);
55+
}
56+
printf("%d\n", part1);
57+
58+
// part 2
59+
int part2 = 0;
60+
for (size_t i = 0; i < n; ++i)
61+
{
62+
int a = left[i];
63+
for (size_t j = 0; j < n; ++j)
64+
{
65+
if (right[j] == a)
66+
{
67+
part2 += a;
68+
}
69+
}
70+
}
71+
printf("%d\n", part2);
72+
73+
free(left);
74+
free(right);
75+
76+
return 0;
77+
}

2024/day1/day1.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
2+
3+
package main
4+
5+
import (
6+
"bufio"
7+
"fmt"
8+
"os"
9+
"sort"
10+
"strconv"
11+
"strings"
12+
)
13+
14+
func main() {
15+
16+
inputFile := "input.txt"
17+
if len(os.Args) >= 2 {
18+
inputFile = os.Args[1]
19+
}
20+
21+
file, err := os.Open(inputFile)
22+
if err != nil {
23+
fmt.Println("error:", err)
24+
return
25+
}
26+
defer file.Close()
27+
28+
var left, right []int
29+
30+
scanner := bufio.NewScanner(file)
31+
for scanner.Scan() {
32+
line := scanner.Text()
33+
parts := strings.Fields(line)
34+
a, _ := strconv.Atoi(parts[0])
35+
b, _ := strconv.Atoi(parts[1])
36+
left = append(left, a)
37+
right = append(right, b)
38+
}
39+
40+
if err := scanner.Err(); err != nil {
41+
fmt.Println("error:", err)
42+
return
43+
}
44+
45+
// sort the lists
46+
sort.Ints(left)
47+
sort.Ints(right)
48+
49+
// part 1
50+
part1 := 0
51+
for i := 0; i < len(left); i++ {
52+
part1 += abs(left[i] - right[i])
53+
}
54+
fmt.Println(part1)
55+
56+
// part 2
57+
rightCount := make(map[int]int)
58+
for _, v := range right {
59+
rightCount[v]++
60+
}
61+
62+
part2 := 0
63+
for _, a := range left {
64+
part2 += a * rightCount[a]
65+
}
66+
fmt.Println(part2)
67+
}
68+
69+
// abs returns the absolute value of x.
70+
func abs(x int) int {
71+
if x < 0 {
72+
return -x
73+
}
74+
return x
75+
}

2024/day1/day1.js

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
const fs = require('fs');
2+
3+
// Main function to handle file reading and calculations
4+
async function main() {
5+
// Default input file or the one provided as a command line argument
6+
const inputFile = process.argv.length === 3 ? process.argv[2] : 'input.txt';
7+
8+
let left = [];
9+
let right = [];
10+
11+
try {
12+
const data = await fs.promises.readFile(inputFile, 'utf-8');
13+
const lines = data.split('\n');
14+
15+
// Reading lines and populating left and right arrays
16+
for (const line of lines) {
17+
// Split by one or more spaces (whitespace characters)
18+
const [a, b] = line.trim().split(/\s+/).map(Number);
19+
if (!isNaN(a) && !isNaN(b)) {
20+
left.push(a);
21+
right.push(b);
22+
}
23+
}
24+
25+
// Sorting both arrays
26+
left.sort();
27+
right.sort();
28+
29+
// Part 1: Calculate the sum of absolute differences
30+
const part1 = left.reduce((sum, a, index) => sum + Math.abs(a - right[index]), 0);
31+
console.log(part1);
32+
33+
// Part 2: Count occurrences of each number in the right array
34+
const rightCounts = {};
35+
for (const b of right) {
36+
rightCounts[b] = (rightCounts[b] || 0) + 1;
37+
}
38+
39+
// Calculate the weighted sum based on left array and counts in right array
40+
const part2 = left.reduce((sum, a) => sum + a * (rightCounts[a] || 0), 0);
41+
console.log(part2);
42+
43+
} catch (err) {
44+
console.error('Error reading file:', err);
45+
}
46+
}
47+
48+
main();

2024/day1/day1.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
2+
3+
input_file = ARGV.length == 0 ? "input.txt" : ARGV[0]
4+
5+
left = []
6+
right = []
7+
8+
File.open(input_file, "r") do |file|
9+
file.each_line do |line|
10+
a, b = line.split.map(&:to_i)
11+
left << a
12+
right << b
13+
end
14+
end
15+
16+
left.sort!
17+
right.sort!
18+
19+
# part 1
20+
puts left.zip(right).map { |a, b| (a - b).abs }.sum
21+
22+
# part 2
23+
right_counts = right.tally
24+
puts left.sum { |a| a * right_counts[a].to_i }

2024/day1/day1.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ impl Puzzle {
3131
}
3232
}
3333

34-
// sort the both vectors
34+
// Sort both arrays
3535
self.left.sort();
3636
self.right.sort();
3737
}

2024/day1/day1.swift

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import Foundation
2+
3+
// Main function to handle file reading and calculations
4+
func main() {
5+
// Default input file or the one provided as a command line argument
6+
let inputFile = CommandLine.arguments.count == 2 ? CommandLine.arguments[1] : "input.txt"
7+
8+
var left: [Int] = []
9+
var right: [Int] = []
10+
11+
do {
12+
// Read the file content
13+
let data = try String(contentsOfFile: inputFile, encoding: .utf8)
14+
let lines = data.split(separator: "\n")
15+
16+
// Read lines and populate the left and right arrays
17+
for line in lines {
18+
let components = line.split(whereSeparator: { $0.isWhitespace }).map { Int($0.trimmingCharacters(in: .whitespaces)) }
19+
if components.count == 2, let a = components[0], let b = components[1] {
20+
left.append(a)
21+
right.append(b)
22+
}
23+
}
24+
25+
// Sorting both arrays
26+
left.sort()
27+
right.sort()
28+
29+
// Part 1: Calculate the sum of absolute differences
30+
let part1 = zip(left, right).reduce(0) { sum, pair in
31+
sum + abs(pair.0 - pair.1)
32+
}
33+
print(part1)
34+
35+
// Part 2: Count occurrences of each number in the right array
36+
var rightCounts: [Int: Int] = [:]
37+
for b in right {
38+
rightCounts[b, default: 0] += 1
39+
}
40+
41+
// Calculate the weighted sum based on left array and counts in right array
42+
let part2 = left.reduce(0) { sum, a in
43+
sum + a * (rightCounts[a] ?? 0)
44+
}
45+
print(part2)
46+
47+
} catch {
48+
print("Error reading file: \(error)")
49+
}
50+
}
51+
52+
main()

scripts/runall.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ def make(year: Path, source: Path, dest: Path, cmd: str):
207207

208208

209209
def build_all(filter_year: int, filter_lang: t.Iterable[str]):
210-
for year in range(2015, 2024):
210+
for year in range(2015, 2025):
211211
if filter_year != 0 and year != filter_year:
212212
continue
213213
year = Path(str(year))
@@ -683,7 +683,7 @@ def main():
683683
script.unlink()
684684

685685
# here we go!
686-
for year in range(2015, 2024):
686+
for year in range(2015, 2025):
687687
if filter_year != 0 and year != filter_year:
688688
continue
689689

0 commit comments

Comments
 (0)