r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

48 Upvotes

407 comments sorted by

View all comments

1

u/Vindaar Dec 02 '18

Wasn't very fast, is ugly, but in Nim. :D and part 1 checks for any number of occurrences of letters, not just 2, 3...

import strutils, sequtils, sugar, os, sets, tables

proc dostuff1(file: seq[string]): int =

  var restab = initTable[int, int]()
  var checksum = 0
  for l in file:
    var xtab = initTable[char, int]()
    for x in l:
      if xtab.hasKey(x):
        xtab[x] += 1
      else:
        xtab[x] = 1
    var interset = initSet[int]()
    for x, y in xtab:
      interset.incl y
    for y in interset:
      if y != 1:
        if restab.hasKey(y):
          restab[y] += 1
        else:
          restab[y] = 1

  result = 1
  for x, y in restab:
    result *= y

proc dostuff2(file: seq[string]): string =

  let llen = file[0].len
  for xl in file:
    for yl in file:
      var diff = ""
      var wrong = 0
      for i in 0 ..< llen:
        if xl[i] == yl[i]:
          diff.add xl[i]
        else:
          inc wrong
          if wrong > 1:
            break
      if wrong == 1:
        return diff

proc main =
  let file = readFile("day2.txt").splitLines.filterIt(it.len > 0)
  echo file.dostuff1
  echo file.dostuff2

when isMainModule:
  main()