Skip to content

Commit ad27ec7

Browse files
committed
day1 many languages
1 parent db3d44e commit ad27ec7

File tree

11 files changed

+470
-3
lines changed

11 files changed

+470
-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.cs

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
// [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
2+
3+
using System;
4+
using System.Collections.Generic;
5+
using System.IO;
6+
7+
class day1
8+
{
9+
static void Main(string[] args)
10+
{
11+
// Default to "input.txt" if no argument is provided
12+
string inputFile = args.Length == 0 ? "input.txt" : args[0];
13+
14+
// Lists to store the values
15+
List<int> left = new List<int>();
16+
List<int> right = new List<int>();
17+
18+
// Read the file and populate the left and right lists
19+
foreach (var line in File.ReadLines(inputFile))
20+
{
21+
// Split the line by any whitespace (spaces or tabs)
22+
var parts = line.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
23+
24+
// Add the two integers to left and right lists
25+
left.Add(int.Parse(parts[0]));
26+
right.Add(int.Parse(parts[1]));
27+
}
28+
29+
// Sort both lists
30+
left.Sort();
31+
right.Sort();
32+
33+
// Part 1: Calculate the sum of absolute differences
34+
int part1Result = 0;
35+
for (int i = 0; i < left.Count; i++)
36+
{
37+
part1Result += Math.Abs(left[i] - right[i]);
38+
}
39+
Console.WriteLine(part1Result);
40+
41+
// Part 2: Count occurrences of each element in the right list
42+
Dictionary<int, int> rightCounts = new Dictionary<int, int>();
43+
foreach (var num in right)
44+
{
45+
if (rightCounts.ContainsKey(num))
46+
{
47+
rightCounts[num]++;
48+
}
49+
else
50+
{
51+
rightCounts[num] = 1;
52+
}
53+
}
54+
55+
// Calculate the weighted sum for part 2
56+
int part2Result = 0;
57+
foreach (var num in left)
58+
{
59+
if (rightCounts.ContainsKey(num))
60+
{
61+
part2Result += num * rightCounts[num];
62+
}
63+
}
64+
Console.WriteLine(part2Result);
65+
}
66+
}

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.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
2+
3+
// javac day1.java
4+
// java day1 [input.txt]
5+
6+
import java.io.*;
7+
import java.nio.file.*;
8+
import java.util.*;
9+
10+
class day1 {
11+
public static void main(String[] args) throws IOException {
12+
// Default to "input.txt" if no arguments are passed
13+
String inputFile = args.length == 0 ? "input.txt" : args[0];
14+
15+
// Read the file into two lists: left and right
16+
List<Integer> left = new ArrayList<>();
17+
List<Integer> right = new ArrayList<>();
18+
19+
// Read the file and split the numbers
20+
Files.lines(Paths.get(inputFile)).forEach(line -> {
21+
String[] parts = line.split("\\s+");
22+
left.add(Integer.parseInt(parts[0]));
23+
right.add(Integer.parseInt(parts[1]));
24+
});
25+
26+
// Sort both lists
27+
Collections.sort(left);
28+
Collections.sort(right);
29+
30+
// Part 1: Calculate the sum of absolute differences
31+
int part1 = 0;
32+
for (int i = 0; i < left.size(); i++) {
33+
part1 += Math.abs(left.get(i) - right.get(i));
34+
}
35+
System.out.println(part1);
36+
37+
// Part 2: Count the occurrences of each number in the right list
38+
Map<Integer, Integer> rightCounts = new HashMap<>();
39+
for (int num : right) {
40+
rightCounts.put(num, rightCounts.getOrDefault(num, 0) + 1);
41+
}
42+
43+
// Calculate the weighted sum of left elements based on right counts
44+
int part2 = 0;
45+
for (int num : left) {
46+
part2 += num * rightCounts.getOrDefault(num, 0);
47+
}
48+
System.out.println(part2);
49+
}
50+
}

2024/day1/day1.js

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

2024/day1/day1.lua

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
-- [Day 1: Historian Hysteria](https://adventofcode.com/2024/day/1)
2+
3+
input_file = arg[1] or "input.txt"
4+
5+
local left = {}
6+
local right = {}
7+
8+
for line in io.lines(input_file) do
9+
local a, b = line:match("(%d+)%s*(%d+)")
10+
table.insert(left, tonumber(a))
11+
table.insert(right, tonumber(b))
12+
end
13+
14+
-- Sort both lists
15+
table.sort(left)
16+
table.sort(right)
17+
18+
-- Part 1: Calculate the sum of absolute differences
19+
local part1 = 0
20+
for i = 1, #left do
21+
part1 = part1 + math.abs(left[i] - right[i])
22+
end
23+
print(part1)
24+
25+
-- Part 2: Count occurrences of each element in the right list
26+
local right_counts = {}
27+
for _, num in ipairs(right) do
28+
right_counts[num] = (right_counts[num] or 0) + 1
29+
end
30+
31+
-- Calculate the weighted sum for part 2
32+
local part2 = 0
33+
for _, num in ipairs(left) do
34+
part2 = part2 + num * (right_counts[num] or 0)
35+
end
36+
print(part2)

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
}

0 commit comments

Comments
 (0)