Advent of Code 2023

Julian Fondren julian.fondren at gmail.com
Sun Dec 3 23:44:43 UTC 2023


On Saturday, 2 December 2023 at 13:33:33 UTC, Johannes 
Miesenhardt wrote:
> I am a bloody beginner so if there are any things that are very 
> wrong with this please point them out.
> The fact that I need a template for accepting both a string and 
> a char[] is very weird but I went with it. I am also curious if 
> there is a better way for the reversible for-loop to happen. I 
> saw foreach and foreach_reverse but I don't think that helps me 
> here, since I swap them out based on a runtime argument.

Rather than putting `version = Part2;` in the source, you can 
specify that on the commandline. This doesn't work with rdmd, but 
these work:

```
$ dmd -run day1.d
$ dmd -version=Part2 day1.d
$ ldc2 --d-version=Part2 --run day1.d
$ gdc -fversion=Part2 day1.d && ./a.out
```

Rather than the template you could only accept 
`immutable(char)[]` and use `str.representation.assumeUTF` to get 
that from a string, without any extra allocation. There's a table 
at 
https://d.minimaltype.com/index.cgi/wiki?name=string+type+conversions that might be helpful (although I notice the unicode tests have some bitrot due to increased safety in the language.)

You may still want a template though, to specialize on the 
`reverse` variable. That only changes these lines:

```d
int findNum(bool reverse)(immutable(char)[] str) {
...
     auto firstNum = findNum!false(str.representation.assumeUTF);
     auto secNum = findNum!true(str.representation.assumeUTF);
```

Bonus from using a dynamic array: it would be much more annoying 
to have `reverse` as a template argument if you were still 
relying on an implicit `T` parameter at the callsite.

And, `unittest {}` is a great feature of d. Instead of editing 
your code to run tests, changing things while working with the 
real input, not realizing that you broke your tests, then getting 
timed out when you submit your answer to AoC, you can doublecheck 
just before submission that `dmd -unittest -run day1.d` still 
passes.

In your loop over numberMap, you could use

```d
if (str[i..$].startsWith(key) == key) return value;
```

Otherwise, I think it's fine good. People might differ on style, 
but it doesn't look bad at all compared to some other 
implementations I've seen. The several ternary operators are the 
only awkward bit. Since you're a beginner you might find it 
interesting to implement a range that yields chars in reverse 
order, and have `findNum` take a range.


More information about the Digitalmars-d-learn mailing list