this post was submitted on 04 Dec 2024
18 points (95.0% liked)

Advent Of Code

996 readers
4 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
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

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 4: Ceres Search

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] [email protected] 2 points 1 month ago

Nim

import ../aoc, strutils

type
  Cell* = tuple[x,y:int]

#the 8 grid direction
const directions : array[8, Cell] = [
  (1, 0), (-1, 0),
  (0, 1), ( 0,-1),
  (1, 1), (-1,-1),
  (1,-1), (-1, 1)
]

const xmas = "XMAS"

#part 1
proc searchXMAS*(grid:seq[string], x,y:int):int =
  #search in all 8 directions (provided we can find a full match in that direction)
  let w = grid[0].len
  let h = grid.len
  
  for dir in directions:
    # check if XMAS can even fit
    let xEnd = x + dir.x * 3
    let yEnd = y + dir.y * 3
    if xEnd < 0 or xEnd >= w or
       yEnd < 0 or yEnd >= h:
      continue;
    
    #step along direction
    var matches = 0
    for s in 0..3:
      if grid[y + dir.y * s][x + dir.x * s] == xmas[s]:
        inc matches
        
    if matches == xmas.len:
      inc result

#part 2
proc isMAS(grid:seq[string], c, o:Cell):bool=
  let ca : Cell = (c.x+o.x, c.y+o.y)
  let cb : Cell = (c.x-o.x, c.y-o.y)
  let a = grid[ca.y][ca.x]
  let b = grid[cb.y][cb.x]
  (a == 'M' and b == 'S') or (a == 'S' and b == 'M')

proc searchCrossMAS*(grid:seq[string], x,y:int):bool =
  grid[y][x] == 'A' and
  grid.isMAS((x,y), (1,1)) and
  grid.isMAS((x,y), (1,-1))

proc solve*(input:string): array[2,int] =
  let grid = input.splitLines
  let w = grid[0].len
  let h = grid.len
  
  #part 1
  for y in 0..<h:
    for x in 0..<w:
      result[0] += grid.searchXMAS(x, y)
  
  #part 2, skipping borders
  for y in 1..<h-1:
    for x in 1..<w-1:
      result[1] += (int)grid.searchCrossMAS(x, y)

Part 1 was done really quickly. Part 2 as well, but the result was not accepted...

Turns out +MAS isn't actually a thing :P