Compare commits

...

4 Commits

Author SHA1 Message Date
3396a87262 2025: day6: JS 2025-12-06 17:51:37 +00:00
12a56a01f3 2025: day 5: ocaml again! 2025-12-06 17:51:30 +00:00
3ed91e2424 2025: day4: ts 2025-12-06 15:28:40 +00:00
91d18eea0a 2025: day3: ocaml 2025-12-06 15:28:35 +00:00
23 changed files with 779 additions and 0 deletions

View File

@ -0,0 +1,3 @@
(executable
(public_name day3)
(name main))

View File

@ -0,0 +1,86 @@
let get_highest_number_and_index l =
let (t, _) = List.fold_left (
fun ((highest, highest_index), index) i ->
if i > highest then
((i, index), index + 1)
else
((highest, highest_index), index + 1)
) ((0, 0), 0) (List.rev l) in
t
let rec first_n k xs = match xs with
| [] -> failwith "firstk"
| x::xs -> if k=1 then [x] else x::first_n (k-1) xs
let slice_at_index l index =
let rec loop (i, acc) =
match acc with
| [] -> failwith "too far"
| _ :: tail -> if i == index then tail else loop (i + 1, tail)
in
loop (0, List.rev l)
let highest_n n l =
let rec loop acc n l =
match n with
| 0 -> acc
| n ->
let list_first_n_items = first_n (List.length l - n + 1) (List.rev l) |> List.rev in
let (highest, highest_index) = get_highest_number_and_index list_first_n_items in
let remaining_list = slice_at_index l highest_index in
loop (highest :: acc) (n - 1) (List.rev remaining_list)
in
loop [] n l
let string_to_int_list l =
l
|> String.to_seq
|> List.of_seq
|> List.fold_left (fun acc i -> ((int_of_char i) - (int_of_char '0')) :: acc) []
let num_from_int_list l =
let rec loop acc index l =
match l with
| [] -> acc
| head :: tail -> loop (acc + index * head) (index * 10) tail
in
loop 0 1 l
let solve lines =
let nums_part1 = List.fold_left (
fun acc line -> (line |> string_to_int_list |> (highest_n 2)) :: acc
) [] lines in
let part1 = List.fold_left (+) 0 (List.map num_from_int_list nums_part1) in
let nums_part2 = List.fold_left (
fun acc line -> (line |> string_to_int_list |> (highest_n 12)) :: acc
) [] lines in
let part2 = List.fold_left (+) 0 (List.map num_from_int_list nums_part2) in
(part1, part2)
let read_lines name =
let ic = open_in name in
let try_read () = try Some (input_line ic) with End_of_file -> None in
let rec loop acc =
match try_read () with
| Some s -> loop (s :: acc)
| None ->
close_in ic;
List.rev acc
in
loop []
let () =
print_endline "Day 3";
let part1, part2 =
read_lines "./input.txt" |> solve
in
Printf.printf "Part 1: %s\nPart 2: %s\n" (string_of_int part1)
(string_of_int part2)

View File

@ -0,0 +1,32 @@
# This file is generated by dune, edit dune-project instead
opam-version: "2.0"
synopsis: "A short synopsis"
description: "A longer description"
maintainer: ["Maintainer Name <maintainer@example.com>"]
authors: ["Author Name <author@example.com>"]
license: "LICENSE"
tags: ["add topics" "to describe" "your" "project"]
homepage: "https://github.com/username/reponame"
doc: "https://url/to/documentation"
bug-reports: "https://github.com/username/reponame/issues"
depends: [
"dune" {>= "3.20"}
"ocaml"
"odoc" {with-doc}
]
build: [
["dune" "subst"] {dev}
[
"dune"
"build"
"-p"
name
"-j"
jobs
"@install"
"@runtest" {with-test}
"@doc" {with-doc}
]
]
dev-repo: "git+https://github.com/username/reponame.git"
x-maintenance-intent: ["(latest)"]

View File

@ -0,0 +1,26 @@
(lang dune 3.20)
(name day3)
(generate_opam_files true)
(source
(github username/reponame))
(authors "Author Name <author@example.com>")
(maintainers "Maintainer Name <maintainer@example.com>")
(license LICENSE)
(documentation https://url/to/documentation)
(package
(name day3)
(synopsis "A short synopsis")
(description "A longer description")
(depends ocaml)
(tags
("add topics" "to describe" your project)))
; See the complete stanza docs at https://dune.readthedocs.io/en/stable/reference/dune-project/index.html

34
AdventOfCode2025/day4/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# dependencies (bun install)
node_modules
# output
out
dist
*.tgz
# code coverage
coverage
*.lcov
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# caches
.eslintcache
.cache
*.tsbuildinfo
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store

View File

@ -0,0 +1,15 @@
# day4
To install dependencies:
```bash
bun install
```
To run:
```bash
bun run index.ts
```
This project was created using `bun init` in bun v1.2.8. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

View File

@ -0,0 +1,25 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "day4",
"devDependencies": {
"@types/bun": "latest",
},
"peerDependencies": {
"typescript": "^5",
},
},
},
"packages": {
"@types/bun": ["@types/bun@1.3.3", "", { "dependencies": { "bun-types": "1.3.3" } }, "sha512-ogrKbJ2X5N0kWLLFKeytG0eHDleBYtngtlbu9cyBKFtNL3cnpDZkNdQj8flVf6WTZUX5ulI9AY1oa7ljhSrp+g=="],
"@types/node": ["@types/node@24.10.1", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ=="],
"bun-types": ["bun-types@1.3.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-z3Xwlg7j2l9JY27x5Qn3Wlyos8YAp0kKRlrePAOjgjMGS5IG6E7Jnlx736vH9UVI4wUICwwhC9anYL++XeOgTQ=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
}
}

View File

@ -0,0 +1,78 @@
const file = Bun.file("./input.txt");
const content = await file.text();
const EMPTY = ".";
const PAPER = "@";
const splitContent = [...content.trim().split("\n")]
const lineSize = splitContent[0]!.length
const grid = [
'.'.repeat(lineSize),
...splitContent,
'.'.repeat(lineSize),
].map(l => `.${l}.`.split(""))
const solve = (grid: string[][]): [number, string[][]] => {
let paperRemoved = 0;
const newGrid = structuredClone(grid)
for (let y = 1; y < grid.length - 1; y++) {
for (let x = 1; x < grid[0]!.length - 1; x++) {
let adjacentPapers = 0;
const currentSquare = grid?.[y]?.[x]
if (!currentSquare) {
throw new Error("current square must be defined")
}
if (currentSquare === EMPTY) {
continue
}
for (let yOffset = -1; yOffset <= 1; yOffset++) {
for (let xOffset = -1; xOffset <= 1; xOffset++) {
if (yOffset === 0 && xOffset === 0) {
continue
}
const square = grid![y + yOffset]![x + xOffset]!
if (square === PAPER) {
adjacentPapers++
}
}
}
if (adjacentPapers < 4) {
newGrid![y]![x] = EMPTY
paperRemoved++
}
}
}
return [paperRemoved, newGrid]
}
const removePaper = (grid: string[][]): number => {
let totalPaperRemoved = 0;
let currentGrid = grid
while (true) {
const [paperRemoved, newGrid] = solve(currentGrid)
currentGrid = newGrid
if (paperRemoved === 0) {
break
}
totalPaperRemoved += paperRemoved
}
return totalPaperRemoved
}
const [part1] = solve(grid)
const part2 = removePaper(grid)
console.log("Part 1: ", part1)
console.log("Part 2: ", part2)

View File

@ -0,0 +1,12 @@
{
"name": "day4",
"module": "index.ts",
"type": "module",
"private": true,
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5"
}
}

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}

View File

@ -0,0 +1,4 @@
(executable
(public_name day5)
(name main)
(libraries day5))

View File

@ -0,0 +1,144 @@
let get_range str =
let list = (String.split_on_char '-' str)
|> List.map int_of_string in
assert (List.length list == 2);
let lower = List.nth list 0 in
let upper = List.nth list 1 in
(lower, upper)
let is_item_in_range i (lower, upper) =
lower <= i && i <= upper
let rec list_some l fn =
match l with
| [] -> false
| head :: tail -> if fn head then true else list_some tail fn
let is_item_in_ranges ranges i =
list_some ranges (is_item_in_range i)
let is_overlapping (lower1, upper1) (lower2, upper2) =
lower1 <= lower2 && lower2 <= upper1 ||
lower2 <= lower1 && lower1 <= upper2
let get_combined_ranges (lower1, upper1) (lower2, upper2) =
let lower = min lower1 lower2 in
let upper = max upper1 upper2 in
(lower, upper)
let non_overlapping_ranges_work ranges =
let rec loop acc changes ranges =
match ranges with
| [] -> (acc, changes)
| head :: tail ->
let overlap_fn = is_overlapping head in
let overlapping_index = List.find_index overlap_fn tail in
match overlapping_index with
| Some r ->
let (l, u) = List.nth tail r in
let tail_without_index = List.filter
(fun (lower, upper) -> not (lower == l && upper == u)) tail in
let combined_range = get_combined_ranges head (l, u) in
loop (combined_range :: acc) true (tail_without_index)
| None -> loop (head :: acc) changes tail
in
loop [] false ranges
(* let rec print_ranges l = *)
(* match l with *)
(* | [] -> print_endline ""; *)
(* | (lower, upper) :: tail -> *)
(* Printf.printf "lower=%d,upper=%d\n" lower upper; *)
(* print_ranges tail *)
let rec non_overlapping_ranges ranges =
let (ranges, changes) = non_overlapping_ranges_work ranges in
if changes then non_overlapping_ranges ranges
else ranges
let solve lines =
let no_empty_lines = List.filter (fun i -> String.length i > 0) lines in
let (ranges, items) = List.partition (fun i -> String.contains i '-') no_empty_lines in
let ranges = List.map get_range ranges in
let items = List.map int_of_string items in
let part1 = List.fold_left (
fun acc i -> if is_item_in_ranges ranges i then acc + 1 else acc
) 0 items in
let ranges = non_overlapping_ranges ranges in
let part2 = List.fold_left (
fun acc (lower, upper) -> acc + (upper - lower + 1)
) 0 ranges in
(part1, part2)
let read_lines name =
let ic = open_in name in
let try_read () = try Some (input_line ic) with End_of_file -> None in
let rec loop acc =
match try_read () with
| Some s -> loop (s :: acc)
| None ->
close_in ic;
List.rev acc
in
loop []
let () =
print_endline "Day 5";
let part1, part2 =
read_lines "./input.txt" |> solve
in
Printf.printf "Part 1: %s\nPart 2: %s\n" (string_of_int part1)
(string_of_int part2)

View File

@ -0,0 +1,32 @@
# This file is generated by dune, edit dune-project instead
opam-version: "2.0"
synopsis: "A short synopsis"
description: "A longer description"
maintainer: ["Maintainer Name <maintainer@example.com>"]
authors: ["Author Name <author@example.com>"]
license: "LICENSE"
tags: ["add topics" "to describe" "your" "project"]
homepage: "https://github.com/username/reponame"
doc: "https://url/to/documentation"
bug-reports: "https://github.com/username/reponame/issues"
depends: [
"dune" {>= "3.20"}
"ocaml"
"odoc" {with-doc}
]
build: [
["dune" "subst"] {dev}
[
"dune"
"build"
"-p"
name
"-j"
jobs
"@install"
"@runtest" {with-test}
"@doc" {with-doc}
]
]
dev-repo: "git+https://github.com/username/reponame.git"
x-maintenance-intent: ["(latest)"]

View File

@ -0,0 +1,26 @@
(lang dune 3.20)
(name day5)
(generate_opam_files true)
(source
(github username/reponame))
(authors "Author Name <author@example.com>")
(maintainers "Maintainer Name <maintainer@example.com>")
(license LICENSE)
(documentation https://url/to/documentation)
(package
(name day5)
(synopsis "A short synopsis")
(description "A longer description")
(depends ocaml)
(tags
("add topics" "to describe" your project)))
; See the complete stanza docs at https://dune.readthedocs.io/en/stable/reference/dune-project/index.html

View File

@ -0,0 +1,2 @@
(library
(name day5))

View File

@ -0,0 +1,2 @@
(test
(name test_day5))

View File

34
AdventOfCode2025/day6/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# dependencies (bun install)
node_modules
# output
out
dist
*.tgz
# code coverage
coverage
*.lcov
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# caches
.eslintcache
.cache
*.tsbuildinfo
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store

View File

@ -0,0 +1,15 @@
# day6
To install dependencies:
```bash
bun install
```
To run:
```bash
bun run index.ts
```
This project was created using `bun init` in bun v1.2.8. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

View File

@ -0,0 +1,25 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "day6",
"devDependencies": {
"@types/bun": "latest",
},
"peerDependencies": {
"typescript": "^5",
},
},
},
"packages": {
"@types/bun": ["@types/bun@1.3.3", "", { "dependencies": { "bun-types": "1.3.3" } }, "sha512-ogrKbJ2X5N0kWLLFKeytG0eHDleBYtngtlbu9cyBKFtNL3cnpDZkNdQj8flVf6WTZUX5ulI9AY1oa7ljhSrp+g=="],
"@types/node": ["@types/node@24.10.1", "", { "dependencies": { "undici-types": "~7.16.0" } }, "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ=="],
"bun-types": ["bun-types@1.3.3", "", { "dependencies": { "@types/node": "*" } }, "sha512-z3Xwlg7j2l9JY27x5Qn3Wlyos8YAp0kKRlrePAOjgjMGS5IG6E7Jnlx736vH9UVI4wUICwwhC9anYL++XeOgTQ=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@7.16.0", "", {}, "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw=="],
}
}

View File

@ -0,0 +1,116 @@
const file = Bun.file("./input.txt");
const content = await file.text().then((c) => c.trim());
const filterNonEmpty = (i: string) => i.length > 0
type Problem = {
operation: string
numbers: number[]
}
const problems: Problem[] = [];
const splitContent = content.split("\n")
const operationsRow = splitContent.pop()!.split(" ").filter(filterNonEmpty)
for (const line of splitContent) {
const numbers = line.split(" ").filter(filterNonEmpty);
if (problems.length === 0) {
for (let i = 0; i < numbers.length; i++) {
problems.push({
operation: '',
numbers: [],
})
}
}
for (let i = 0; i < numbers.length; i++) {
problems[i]!.numbers.push(parseInt(numbers[i]!))
}
}
for (const [index, problem] of problems.entries()) {
problem.operation = operationsRow[index]!
}
const getReducer = (op: string): (nums: number[]) => number => {
switch (op) {
case '*':
return (nums) => nums.reduce((n, acc) => acc * n, 1)
case '+':
return (nums) => nums.reduce((n, acc) => acc + n, 0)
default:
throw new Error("operation not supported")
}
}
const solve = (problems: Problem[]): number => {
let part1 = 0;
for (const problem of problems) {
const reducer = getReducer(problem.operation)
part1 += reducer(problem.numbers)
}
return part1
}
const transposeProblems = (str: string): Problem[] => {
const charArr = str.split("\n").map(c => c.split(""))
const newCharArr: string[][] = [];
for (let i = 0; i < charArr.length; i++) {
for (let j = 0; j < charArr[0]!.length; j++) {
if (!newCharArr[j]) {
newCharArr[j] = []
}
newCharArr[j]![i]! = charArr[i]![j]! ?? ' '
}
}
const problems: Problem[] = [];
let workingProblem: Problem = {
numbers: [],
operation: ""
}
let index = 0;
for (const line of newCharArr) {
if (line.every(c => c === " ")) {
problems.push(workingProblem)
workingProblem = {
numbers: [],
operation: ''
}
index = 0
continue
}
if (index === 0) {
const op = line.pop()
if (op !== " ") {
workingProblem.operation = op!
}
}
const numbers = line.filter(c => c !== " ")
if (numbers.length === 0) {
continue
}
const number = parseInt(numbers.join(""))
workingProblem.numbers.push(number)
}
problems.push(workingProblem)
return problems
}
const part1 = solve(problems)
console.log("Part 1: ", part1)
const part2Problems = transposeProblems(content)
const part2 = solve(part2Problems)
console.log("Part 2: ", part2)

View File

@ -0,0 +1,12 @@
{
"name": "day6",
"module": "index.ts",
"type": "module",
"private": true,
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5"
}
}

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
// Environment setup & latest features
"lib": ["ESNext"],
"target": "ESNext",
"module": "ESNext",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
// Bundler mode
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// Best practices
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
// Some stricter flags (disabled by default)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false
}
}