This repository has been archived by the owner on Nov 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle13.fs
75 lines (57 loc) · 2.22 KB
/
puzzle13.fs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// https://adventofcode.com/2020/day/13
//
#if !INTERACTIVE
module Puzzle13
#else
#load "common.fs"
#endif
open System.IO
open common
module Part1 =
let (targetTs, buses) =
let rows = Path.Combine(__SOURCE_DIRECTORY__, "puzzle13.txt")
|> readLines
|> Seq.toArray
let times = rows.[1].Split(",") |> Seq.filter ((<>)"x") |> Seq.map int64
int64 rows.[0]
,
times |> Array.ofSeq
let timeToWait ts busId =
let x = (ts % busId)
abs (x - busId)
let answer =
let (minBus, minTime) = buses |> Array.map (fun bus -> bus, timeToWait targetTs bus) |> Seq.minBy snd
minBus * minTime
module Part2 =
let buses =
let rows = Path.Combine(__SOURCE_DIRECTORY__, "puzzle13.txt")
|> readLines
|> Seq.toArray
let times = rows.[1].Split(",") |> Array.map (fun s -> match s with |"x" -> 1, -1L | _ -> 1, int64 s) |> List.ofArray
let rec readTimes l count =
match l with
| (_,-1L)::tail -> readTimes tail (count + 1)
| (_,head)::tail -> (count, head) :: readTimes tail 1
| [] -> []
let head::tail = readTimes times 1
(0, snd head)::tail
let findClosest offset busId =
offset + (busId - offset % busId)
let rec findClosestWithNewBus buses offset bus diff =
if (buses = []) then offset + (bus - offset % bus)
else
let newOffset = offset + int64 diff
if (newOffset % bus = 0L) then newOffset
else
findClosestWithNewBus buses (offset + (buses |> List.fold (*) 1L)) bus diff
let rec findResult buses offset =
let lastoffset =
buses
|> List.fold (fun (offset, busesAcc) (diff, bus) ->
let newOffset = findClosestWithNewBus busesAcc offset bus diff
newOffset, busesAcc @ [bus])
(offset, [])
|> fst
lastoffset - (List.sumBy fst buses |> int64)
let result = findResult buses 0L