Faster
This commit is contained in:
@@ -25,7 +25,7 @@ module Day15 =
|
||||
|
||||
answer
|
||||
|
||||
let removeFirst<'a> (toRemove : 'a -> bool) (arr : ResizeArray<'a>) : unit =
|
||||
let inline removeFirst<'a> ([<InlineIfLambda>] toRemove : 'a -> bool) (arr : ResizeArray<'a>) : unit =
|
||||
let mutable i = 0
|
||||
|
||||
while i < arr.Count do
|
||||
@@ -38,7 +38,13 @@ module Day15 =
|
||||
|
||||
i <- i + 1
|
||||
|
||||
let replace (withKey : 'a -> 'key) (key : 'key) (value : 'a) (arr : ResizeArray<'a>) : unit =
|
||||
let inline replace
|
||||
([<InlineIfLambda>] withKey : 'a -> 'key)
|
||||
(key : 'key)
|
||||
(value : 'a)
|
||||
(arr : ResizeArray<'a>)
|
||||
: unit
|
||||
=
|
||||
let mutable i = 0
|
||||
|
||||
while i < arr.Count do
|
||||
@@ -60,23 +66,35 @@ module Day15 =
|
||||
|
||||
answer
|
||||
|
||||
let inline toUint32 (s : ReadOnlySpan<char>) : uint32 =
|
||||
let mutable answer = 0ul
|
||||
|
||||
for c in s do
|
||||
answer <- answer * 26ul + uint32 (byte c - byte 'a')
|
||||
|
||||
answer
|
||||
|
||||
let part2 (s : string) =
|
||||
let s = s.AsSpan().TrimEnd ()
|
||||
use chunks = StringSplitEnumerator.make' ',' s
|
||||
let lenses = Array.init 256 (fun _ -> ResizeArray<string * _> ())
|
||||
// The max length of a label turns out to be 6, which means we need 26^6 < 2^32 entries.
|
||||
// So we'll use a uint32 instead of our string, to save hopping around memory.
|
||||
let lenses = Array.init 256 (fun _ -> ResizeArray<uint32 * _> ())
|
||||
|
||||
for chunk in chunks do
|
||||
if chunk.[chunk.Length - 1] = '-' then
|
||||
let label = chunk.Slice(0, chunk.Length - 1).ToString ()
|
||||
removeFirst (fun (label2, _focalLength) -> label2 = label) lenses.[hash (label.AsSpan ())]
|
||||
let label = chunk.Slice (0, chunk.Length - 1)
|
||||
let labelShrunk = toUint32 label
|
||||
removeFirst (fun (label2 : uint32, _focalLength) -> label2 = labelShrunk) lenses.[hash label]
|
||||
else
|
||||
let equalsPos = chunk.IndexOf '='
|
||||
|
||||
let focalLength =
|
||||
Int32.Parse (chunk.Slice (equalsPos + 1), NumberStyles.None, CultureInfo.InvariantCulture)
|
||||
|
||||
let label = chunk.Slice(0, equalsPos).ToString ()
|
||||
replace fst label (label, focalLength) lenses.[hash (label.AsSpan ())]
|
||||
let label = chunk.Slice (0, equalsPos)
|
||||
let labelShrunk = toUint32 label
|
||||
replace fst labelShrunk (labelShrunk, focalLength) lenses.[hash label]
|
||||
|
||||
let mutable answer = 0
|
||||
|
||||
|
Reference in New Issue
Block a user