r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/toasterinBflat Dec 05 '18

Here is my solution in Go. I am very very new to Go, so please bear with me.

I know I can go faster than 4.5 seconds -- I think it's to do with all of the awful typecasting I'm doing to string to make things work. I don't know how to make a string from two runes, is mostly the problem. Anyway, here it is:

package main
import (
  "fmt"
  s "strings"
  u "unicode"
  "bufio"
  "os"
  "time"
)

var alphabet = "abcdefghijklmnopqrstuvwxyz"

func load_compound() string {
  file, _ := os.Open("./input.txt")
  defer file.Close()

  scanner := bufio.NewScanner(file)
  output := ""

  for scanner.Scan() {
    output += scanner.Text()
  }

  return output
}

func strip(str string) string {
  oldlen := len(str)
  newlen := oldlen + 999
  for newlen != oldlen {
    oldlen = newlen
    for _, a := range alphabet {
      str = s.Replace(str, string(a) + string(u.ToUpper(a)), "", -1)
      str = s.Replace(str, string(u.ToUpper(a)) + string(a), "", -1)
    }
    newlen = len(str)
  }
  return str
}

func main() {
  start := time.Now()
  data := s.TrimSpace(load_compound())
  fmt.Println("P1:", len(strip(data)))
  result := map[string]int{}
  for _, a := range alphabet {
    data_set := s.Replace(data, string(a), "", -1)
    data_set = s.Replace(data_set, string(u.ToUpper(a)), "", -1)
    fmt.Printf("Data set compiled for %s : processing...\n", string(a))
    result[string(a)] = len(strip(data_set))
  }
  short_l := ""
  short_c := len(data)
  for k, v := range result {
    if v < short_c {
      short_l = k
      short_c = v
    }
  }
  fmt.Printf("P2: %s@%d\n", string(short_l), short_c)
  fmt.Printf("Runtime: %s\n", time.Since(start))
}

1

u/CHAOSFISCH Dec 05 '18

The typecasts should cost nothing! The problem you have is in the strip function. You're iterating through the string very often. This is an algorithmic problem that you have. Part 1 can be solved in O(n) time.