this post was submitted on 01 Dec 2023
17 points (100.0% liked)

NotAwfulTech

364 readers
2 users here now

a community for posting cool tech news you don’t want to sneer at

non-awfulness of tech is not required or else we wouldn’t have any posts

founded 1 year ago
MODERATORS
 

Rules: no spoilers.

The other rules are made up as we go along.

Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.

top 50 comments
sorted by: hot top controversial new old
[–] [email protected] 7 points 11 months ago* (last edited 11 months ago) (1 children)

Just when I think I'm out, awful systems pulls me right back in.

C++, Horrifying C++ for day 1b check it out ;)

Day 1: https://www.animeprincess.net/blog/?p=55

One day is enough for me though, writing deliberately off-the-wall code is surprisingly mentally taxing, and normally I make sure to never program outside of work.

[–] [email protected] 4 points 11 months ago (1 children)

// Where we're going we won't need regexes.

fuck yes

[–] [email protected] 4 points 11 months ago (1 children)

honestly I considered writing a parser-based approach

then I was too tired and thought "hmm, doing this with grok would be funny", but I didn't have logstash handy and fuck dealing with containers at midnight

I will, however, do that today

[–] [email protected] 4 points 11 months ago

Status report: grok allows for non-greedy matching but still captures greedily for term assignment. I think I have a workaround that might work (recursively pipe data back to itself, gated on length for action), need to test later

This particular flavour of parsecrime is near guaranteed to be of interest to very few, but I want to see if I can make it work nonetheless. That’s just how my brainworms work.

[–] [email protected] 7 points 11 months ago* (last edited 11 months ago) (2 children)

day 1

part 1

perl

#!/usr/bin/env perl

use strict;
use warnings;
use 5.010;

my $total = 0;

for my $line (<>) {
    my @nums = ($line =~ /\d/g);
    $total += $nums[0] * 10 + $nums[-1];
}

say $total;

part 2

perl

#!/usr/bin/env perl

use strict;
use warnings;
use v5.010;

my %nums = (one => 1, two => 2, three => 3, four => 4, five => 5, six => 6, seven => 7, eight => 8, nine => 9);
$nums{$_} = $_ for 1..9;

my $regex = join "|", keys %nums;

my $total = 0;

for my $line (<>) {
    $line =~ /($regex)/;
    my $first_num = $nums{$1};

    my $window = 1;
    my $sub = substr $line, -1;
    while ($sub !~ /($regex)/) {
        $window ++;
        $sub = substr $line, -$window;
    }

    $sub =~ /($regex)/;
    my $second_num = $nums{$1};

    $total += $first_num * 10 + $second_num;
}

say $total;

Part 2 gave me a surprising amount of trouble. I resolved it by looking at longer and longer substrings from the end of the line in order to find the very last word even if it overlapped, which you can't do with normal regex split. I doubt this is the most efficient possible solution.

Also Lemmy is eating my < characters inside code blocks, which seems wrong. Pretend the "&lt;>" part says "<>", lol

[–] [email protected] 4 points 11 months ago

day 2

perl

#!/usr/bin/env perl

use strict;
use warnings;
use v5.010;
use List::Util qw/ max /;

# Parse the input

my %games = ();

for my $line (&lt;>) {
    $line =~ /Game (\d+): (.+)/;
    my $game_id = $1;
    my $game_str = $2;

    my @segments = split '; ', $game_str;
    my @game = ();
    for my $segment (@segments) {
        my @counts = split ', ', $segment;

        my %colors = (red => 0, blue => 0, green => 0);
        for my $count (@counts) {
            $count =~ /(\d+) (\w+)/;
            $colors{$2} = $1;
        }

        push @game, { %colors };
    }

    $games{$game_id} = [ @game ];
}

# Part 1

my $part1 = 0;

game: for my $game_id (keys %games) {
    for my $segment (@{$games{$game_id}}) {
        next game if $segment->{red} > 12 || $segment->{green} > 13 || $segment->{blue} > 14;
    }

    $part1 += $game_id;
}

say "Part 1: $part1";

# Part 2

my $part2 = 0;

for my $game (values %games) {
    my ($red, $green, $blue) = (0, 0, 0);

    for my $segment (@$game) {
        $red = max $segment->{red}, $red;
        $green = max $segment->{green}, $green;
        $blue = max $segment->{blue}, $blue;
    }

    $part2 += $red * $green * $blue;
}

say "Part 2: $part2";

Found this much easier than day 1 honestly...

[–] [email protected] 4 points 11 months ago

lemme is an incredibly hungry little shit, it eats so much

[–] [email protected] 4 points 11 months ago (1 children)

Day 11: Cosmic Expansion

https://adventofcode.com/2023/day/11

discussion

After yesterday' fiddle-fest we are back with a straight-forward puzzle. Today we get the return of Manhattan distance, an AoC fav, but this time not spelled out to fool the crafty LLMs.

I made the initial decision not to "move" the galaxies in the initial map, but instead to store an offset that was increased whenever an empty row or column preceding the object was detected. This turned out to make part 2 really easy once I figured out the off-by-one error.

load more comments (1 replies)
[–] [email protected] 4 points 11 months ago (1 children)

Day 2: Cube Conundrum

https://adventofcode.com/2023/day/2

Parsing the puzzle (both instructions and input) was the hardest this time for me.

[–] [email protected] 4 points 11 months ago (1 children)

Day 14: Parabolic Reflector Dish

I only managed part 1 today. My enthusiasm for index fiddling is waning rapidly.

[–] [email protected] 4 points 11 months ago

How about not fiddling with indices?

JQ Notfiddlingwithindexificationhttps://github.com/zogwarg/advent-of-code/blob/main/2023/jq/14-a.jq

#!/usr/bin/env jq -n -R -f

# Dish to grid
[ inputs / "" ]

# Tilt UP
| transpose                       # Transpose, for easier RE use
| map(                            #
  ("#" + add) | [                 # For each column,   replace '^' with '#'
    scan("#[O.]*") | [            # From '#' get empty spaces and 'O' rocks
      "#", scan("O"), scan("\\.") # Let gravity do it's work.
    ]                             #
  ] | add[1:]                     # Add groups back together
 )                                #
| transpose                       # Transpose back

# For each row, count  'O'  rocks
| map(add | [scan("O")] | length)

# Add total load on "N" beam
| [0] + reverse | to_entries
| map( .key * .value ) | add

Similarly tired with index fiddling, I was pretty happy with my approach, which led to satisfying transpose cancelling in part 2. Not the fastest code out there, but it works. Day 14 was actually my favorite one so far ^^.

[–] [email protected] 4 points 11 months ago

Day 4: Scratchcards

Late to the party and never done advents before, I liked how this problem reminded me that tree traversal is thing, almost as much as I don't that so much of my career involves powershell now.

I'm putting everything up at https://github.com/SpaceAntelope/advent-of-code-2023 except the input files.

Using command abbreviations like % and ? to keep the horizontal length friendly to lemmy post areas, they are expanded in git.

Part 2 in Powershell

function calculate([string]$data) {
  # code for parsing data and calculating matches from pt1 here, check the github link if you like banal regexps
  # returns objects with the relevant fields being the card index and the match count
}

function calculateAccumulatedCards($data) {
    $cards = calculate $data # do pt1 calculations

    $cards 
    | ? MatchCount -gt 0 # otherwise the losing card becomes its own child and the search cycles to overflow
    | % { 
        $children = ($_.Index + 1) .. ($_.Index + $_.MatchCount)  # range of numbers corresponding to indices of cards won
        | % { $cards[$_ - 1] } # map to the actual cards
        | ? { $null -ne $_ }  # filter out overflow when index exceeds input length

        $_ | Add-Member -NotePropertyName Children -NotePropertyValue $children # add cards gained as children property
    }

    # do depth first search on every card and its branching children while counting every node
    # the recursive function is inlined in the foreach block because it's simpler than referencing it 
    # from outside the parallel scope
    $cards | % -Parallel {
        function traverse($card) {
            $script:count++        
            foreach ($c in $card.Children) { traverse($c) }
        }
        
        $script:count = 0 # script: means it's basically globally scoped
        traverse $_ 
        $script:count # pass node count to pipeline     
    } 
    | measure -sum    
    | % sum
}

[–] [email protected] 4 points 11 months ago (2 children)

Back to a more straightfoward day, do they make them harder on the weekends?

Day 4 Scratchcards

Part 1

#!/usr/bin/env jq -n -R -f
[
  inputs
  # Split winning numbers | card
  | split(" | ")
  # Get numbers, remove game id
  | .[] |= [ match("\\d+"; "g").string | tonumber ] | .[0] |= .[1:]
  # Get score for each line
  | .[1] - (.[1] - .[0]) | length | select(. > 0) | pow(2; . - 1)
]

# Output total score sum
| add

Very suited to JQ, extra trick learned using: [ match("\\d+"; "g").string | tonumber ] as a parse all ints in line.

Part 2

#!/usr/bin/env jq -n -R -f
[
  inputs
  # Split winning numbers | card
  | split(" | ")
  # Get numbers, remove game id
  | .[] |= [ match("\\d+"; "g").string | tonumber ] | .[0] |= .[1:]
  # Set number of cards to 1, and further cards count
  | .[1] - (.[1] - .[0]) | [ 1, length ]
]

| { cards: ., i: 0, l: length } | until (.i == .l;
  # Get number for current card
  .cards[.i][0] as $num
  # Increase range of futher cards, by current number
  | .cards[.i + range(.cards[.i][1]) + 1 ][0] += $num
  | .i += 1
)

# Output total sum of cards
| [ .cards[][0] ] | add

Not too much of an edit compared to part one, being able to easily do operations on range of indices is convenient.

[–] [email protected] 4 points 11 months ago

Historically problems on Sat/Sun have been more challenging than weekdays. However given that the first 7 days are usually “warmup” problems, I’d say this years edition of AoC is more challenging than at least since 2019.

[–] [email protected] 4 points 11 months ago

I liked today's puzzle. It was meaty but not frustrating.

[–] [email protected] 4 points 11 months ago

Have been mostly using jq for fun.

Day 1

Part 1

#!/usr/bin/env jq -n -R -f

# Get and reduce every "pretty" line
reduce inputs as $line (
  0;
  # Add extracted number
  . + ( $line / "" | [ .[] | tonumber? ] | [first * 10 , last] | add )
)

First part was easy, and very suited to jq

Part 2

#!/usr/bin/env jq -n -R -f

# Define string to num value map
{
  "one":   1,  "1": 1,
  "two":   2,  "2": 2,
  "three": 3,  "3": 3,
  "four":  4,  "4": 4,
  "five":  5,  "5": 5,
  "six":   6,  "6": 6,
  "seven": 7,  "7": 7,
  "eight": 8,  "8": 8,
  "nine":  9,  "9": 9
} as $to_num |

# Get and reduce every "pretty" line
reduce inputs as $line (
  0;
  . + (
    $line |
    # Try two capture two numbers
    capture("(^.*?(?(one|two|three|four|five|six|seven|eight|nine|[1-9])).*(?(one|two|three|four|five|six|seven|eight|nine|[1-9])).*?$)?") |
    # If no capture, get one number twice
    if .f == "" then $line | capture("^.*?(?(one|two|three|four|five|six|seven|eight|nine|[1-9]))") | .l = .f else . end |
    # Add extracted number
    $to_num[.f] * 10 + $to_num[.l]
  )
)

Second part was harder than expected, i had to resort to regex.

Day 2

Part 1

#!/usr/bin/env jq -n -R -f

# For each game: Is 12 red cubes, 13 green cubes, and 14 blue cubes possible ?
# Line Format =
# Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
[
  # Splitting input game id and content
  inputs / ": " |
  # Saving id
  (.[0] / " " | .[1] | tonumber ) as $id |
  # Parsing game
  .[1] / "; " | [
    .[] / ", " | [ .[] / " " | {(.[1]): .[0] | tonumber} ] | add |
    # Is given sample possible ?
    .red &lt;= 12 and .green &lt;= 13 and .blue &lt;= 14
  ] |
  # If all samples possible, return id, else 0
  if all then $id else 0 end
] |

# Return sum of all possible game ids
add

Not too much trickery in this example.

Part 2

#!/usr/bin/env jq -n -R -f

# Line Format =
# Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
[
  # Splitting input game id and content
  inputs / ": " |
  # Parsing game
  .[1] / "; " |
    [ .[] / ", " | [ .[] / " " | {(.[1]): .[0] | tonumber} ] | add ] |
    # Getting minimum required mumber for each color,
    # and computing the power
    {
      r: ([.[].red]   | max),
      g: ([.[].green] | max),
      b: ([.[].blue]  | max)
    } | .r * .g * .b
] |

# Return sum of all powers
add

Satisifyingly straightfoward edit form part one.

Day 3

Part 1

#!/usr/bin/env jq -n -R -f

# Getting input with padding, and padded width
[ "." + inputs + "." ] as $inputs | ( $inputs[0] | length ) as $w |

# Working with flattened string, convert all symbols to '#'
[
  ([range($w) | "."]|join("")), # Padding
  $inputs[],
  ([range($w) | "."]|join(""))  # Padding
] | join("") | gsub("[^0-9.]";"#") as $inputs |

reduce (
  # Get all indices for symbols, in box pattern around symbols
  $inputs | indices("#")[] |
  . - $w -1  , . - $w , . - $w + 1 ,
  . - 1      , empty  , . + 1      ,
  . + $w - 1 , . + $w , . + $w + 1
) as $i (
  # Numbers containes bounding indices,
  # of numbers bordering symbols
  {numbers: []};

  # Test if current index isn't included in any found number
  def new_number($i): [ .numbers[] | .[0] &lt;= $i and $i &lt;= .[1] ] | any | not ;
  # Make "number" as bounding indices, by extending left and right
  def make_number($i):
    {a: $i, b: ($i+1 )}
      | until( $inputs[.a:.b] | test("^[^0-9]"); .a -= 1 )
      | until( $inputs[.a:.b] | test("[^0-9]$"); .b += 1 )
      | [ .a +1 , .b -1 ]
  ;

  # Add numbers if bordering symbol and new
  if ($inputs[$i:$i+1] | test("[0-9]")) and new_number($i) then .numbers += [ make_number($i) ] else . end
) |

# Output sum of all found numbers
[ .numbers[] | $inputs[.[0]:.[1]] | tonumber ] | add

Took More time than i expected, glad i had the idea early to search by the indices of the symbols and not the digits. Not super well suited to jq, unless I'm missing a better solution.

Part 2

#!/usr/bin/env jq -n -R -f

# Getting input with padding, and padded width
[ "." + inputs + "." ] as $inputs | ( $inputs[0] | length ) as $w |

# Working with flattened string, only keep gear '*' symbols
[
  ([range($w) | "."]|join("")), # Padding
  $inputs[],
  ([range($w) | "."]|join(""))  # Padding
] | join("") | gsub("[^0-9*]";".") as $inputs |

# Iterate over index positions of all gears
reduce ($inputs | indices("*")[]) as $i (
  0;
  # Re-use part-1 functions
  def new_number($i):
    [ .numbers[] | .[0] &lt;= $i and $i &lt;= .[1] ] | any | not
  ;
  def make_number($i):
    {a: $i, b: ($i+1 )}
      | until( $inputs[.a:.b] | test("^[^0-9]"); .a -= 1 )
      | until( $inputs[.a:.b] | test("[^0-9]$"); .b += 1 )
      | [ .a +1 , .b -1 ]
  ;
  # Reset and add numbers for each "box" ids
  def add_numbers($box_idx):
    reduce $box_idx[] as $i ({numbers:[]};
      if ($inputs[$i:$i+1] | test("[0-9]")) and new_number($i) then
        .numbers += [ make_number($i) ]
      else
        .
      end
    )
  ;
  add_numbers([
    $i - $w -1 , $i - $w , $i -$w + 1 ,
    $i - 1     , empty   , $i + 1     ,
    $i + $w - 1, $i + $w , $i + $w + 1
  ]).numbers as $numbers |

  if $numbers | length == 2 then
    # Add product if exactly two bordering numbers
    . += ( $numbers | map($inputs[.[0]:.[1]]|tonumber) | .[0] * .[1] )
  else
    .
  end
)

Not too far of an edit from part one.

[–] [email protected] 4 points 11 months ago (1 children)
[–] [email protected] 4 points 11 months ago (2 children)

Perl: https://github.com/gustafe/aoc2023/blob/main/d01-Trebuchet.pl

thoughts

I found this really tough for a day 1 problem. Because I don't really know regex, I did not know the secret to finding overlapping patterns. I quickly figured out that "twone" was a possibility, because it was in the example, but then I had to find other examples and hardcode them into my split pattern.

This isn't general, my input doesn't have 'sevenine' for example.

load more comments (1 replies)
[–] [email protected] 4 points 11 months ago* (last edited 11 months ago) (10 children)

I am using dart to develop my dart chops. All code for all days here:

https://github.com/Fluxward/aoc2023

[–] [email protected] 4 points 11 months ago

1 a,b:as a professional software engineer, I know that googling regex syntax and getting it right will take longer than manually writing string comparisons, so... here's all you need to see of my final solution.

  int? check3(String line, int index) {
    if (line.length &lt; index + 3) {
      return null;
    }

    String sub = line.substring(index, index + 3);
    return sub == "one"
        ? 1
        : sub == "two"
            ? 2
            : sub == "six"
                ? 6
                : null;
  }

[–] [email protected] 4 points 11 months ago (1 children)

Nice, I’ll be reading :D

(Possibly have some dart coming up on a thing soon)

[–] [email protected] 4 points 11 months ago

I'll be honest: so far, Dart is pretty rubbish for this kind of exercise for the simple reason that their Strings aren't just arrays of chars. There's no native isDigit, for example. Otherwise, I've been using it with Flutter and have been happy with my experience.

I'm only posting code when I think I've done something interesting or if there's a notable language feature to show off, but so far, no dice.

[–] [email protected] 3 points 11 months ago (1 children)

3 aI read this wrong initially and thought that you only needed to check adjacency on the same line. Whoops! Then I wrote a bad algorithm that finds numbers THEN searches for symbols. That alg isn't inherently bad, except...

3 bIf I had chosen a symbol first approach, I would not have had as much pain as I did here. Also, I probably under and overthought this one. I went with my first idea, which was guaranteed to work.

The approach this time was:

  1. iterate through the characters to find a * symbol
  2. Search the characters around it for a digit.
  3. Get the value of the number associated with that digit by searching backwards until you find the start of a number
  4. Use union-find to track whether or not you've seen this number before (because you can't assume that the same value is the same number)

A simpler approach would consider that you only have two numbers on the same line for the same gear if the character in the gear column is a non-digit; otherwise, if a number is adjacent to a gear, there is only one on that row. Union-find is completely overkill, but I like using it even when I don't need to.

Anyway, upon reflecting on this, while the general approach is fine, I didn't think too hard about the implementation and just ended up with globs of overly memoized spaghetti. I probably should check if Dart has a python-like tuple object or similar. Whatever. Behold!

void day3s() {
  List lines = [
    for (String? line = stdin.readLineSync();
        line != null;
        line = stdin.readLineSync())
      line
  ];

  List> digs = [for (int i = 0; i &lt; lines.length; i++) Map()];
  int? isDigitMem(int r, int c) {
    return digs[r].putIfAbsent(c, () => isDigit(lines[r][c]));
  }

  // first entry is parentc, second is size
  List>> uf = List.generate(
      lines.length, (i) => List.generate(lines[0].length, (j) => [j, 1, -1]));

  int find(int r, int c) {
    if (uf[r][c][0] != c) {
      uf[r][c][0] = find(r, uf[r][c][0]);
      return uf[r][c][0];
    }
    return uf[r][c][0];
  }

  void union(int r, int cp, int c) {
    cp = find(r, cp);
    c = find(r, c);

    if (c == cp) {
      return;
    }

    if (uf[r][cp][1] >= uf[r][c][1]) {
      uf[r][c][0] = cp;
      uf[r][cp][1] += uf[r][c][1];
    } else {
      uf[r][cp][0] = c;
      uf[r][c][1] += uf[r][cp][1];
    }
  }

  int stoi(int row, int col) {
    int acc = 0;
    for (int i = col; i &lt; lines[0].length; i++) {
      int? d = isDigitMem(row, i);
      if (d != null) {
        acc = (acc * 10) + d;
        union(row, col, i);
      } else {
        break;
      }
    }
    return acc;
  }

  int? stoiSearch(int row, int col) {
    assert(row >= 0 &amp;&amp; col >= 0 &amp;&amp; row &lt; lines.length &amp;&amp; col &lt; lines[0].length);
    if (isDigitMem(row, col) == null) {
      return null;
    }
    int i = col - 1;
    while (i >= 0) {
      if (isDigitMem(row, i) == null) {
        return stoi(row, i + 1);
      }
      i--;
    }
    return stoi(row, 0);
  }

  List> s2i = [for (int i = 0; i &lt; lines.length; i++) Map()];
  int? stoiSearchMem(int row, int col) {
    return s2i[row].putIfAbsent(col, () => stoiSearch(row, col));
  }

  int count = 0;
  for (int i = 0; i &lt; lines.length; i++) {
    for (int j = 0; j &lt; lines[0].length; j++) {
      if (lines[i][j] != "*") {
        continue;
      }

      List gearVals = List.empty(growable: true);
      for (int x = -1; x &lt;= 1; x++) {
        if (i + x &lt; 0 || i + x > lines.length) {
          continue;
        }

        Set parents = {};
        for (int y = -1; y &lt;= 1; y++) {
          if (j + y &lt; 0 || j + y > lines[0].length) {
            continue;
          }

          int? cur = stoiSearchMem(i + x, j + y);

          int parent = find(i + x, j + y);
          if (parents.contains(parent)) {
            continue;
          }

          parents.add(parent);

          if (cur != null) {
            gearVals.add(cur);
          }
        }
      }

      if (gearVals.length == 2) {
        count += gearVals[0] * gearVals[1];
      }
    }
  }

  print(count);
}

load more comments (1 replies)
load more comments (7 replies)
[–] [email protected] 3 points 11 months ago (1 children)

rule 5: one code enters, 7 codes leave

[–] [email protected] 3 points 11 months ago* (last edited 11 months ago) (1 children)

okay yeah so

p1 part 1 submitted, runs fine. part 2 says "wrong answer for you but right for someone else". doing a debug-print-everything run on the intermediate stages of the data after my regex all seems correct, but it's also 23h50 and it's been a looooong week. so I guess I'll take a look a fresh look at that one in the morning over coffee

part1, badly:

spoiler

import re

pattern = '\d'
cmp = re.compile(pattern)

# extremely lazy, of the ungood kind
datapath = 'data'
lines = open(datapath, 'r').read().split('\n')
candidates = []
values = []
for l in lines:
    if l != '':
        r = cmp.findall(l)
        candidates.append(r)
        values.append(int(''.join([r[0], r[-1]])))

print(candidates)
print(values)
print(sum(values))

(I really wasn't kidding about the badly)

part2:

spoilermissed the eightwo case

changes:

mapping = {...} # name/int pairs
pattern = f'(?=(\d|{"|".join(mapping.keys())}))'
lines = open(datapath, 'r').read().split('\n').remove('')
values = []
for l in lines:
    r = cmp.findall(l)
    equivs = [str(mapping.get(x, x)) for x in r]
    head, tail = [equivs[0], equivs[-1]]
    values.append(int(f"{head}{tail}"))
print(sum(values))

load more comments (1 replies)
[–] [email protected] 3 points 11 months ago* (last edited 11 months ago) (1 children)

I have come up with a more horrifying way to solve Day 1 Part 1 involving C++ implementation defined behavior, but it requires launching two subprocesses for every test case so I'm not sure I have the motivation right now.

Proof of concept: https://www.animeprincess.net/blog/?p=60

load more comments (1 replies)
[–] [email protected] 3 points 11 months ago (1 children)

Day 7: Camel Cards

https://adventofcode.com/2023/day/7

So far, my favorite puzzle. Challenging but fair. Also plays to Perl's strengths.

Leaderboard completion time: 16 minutes flat, so not a pushover.

load more comments
view more: next ›