You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/csmith/aoc-2019/common"
  5. "github.com/csmith/aoc-2019/intcode"
  6. )
  7. func runPipeline(memoryBanks []int, program []int, ps []int, feedback bool) int {
  8. // Create a series of VMs for our amplifiers
  9. vms := make([]*intcode.VirtualMachine, len(ps))
  10. for i := 0; i < len(ps); i++ {
  11. memory := memoryBanks[i*len(program) : (i+1)*len(program)]
  12. copy(memory, program)
  13. vms[i] = intcode.NewVirtualMachine(memory, true)
  14. }
  15. // Link all the inputs and outputs
  16. for i, vm := range vms {
  17. if i > 0 {
  18. vm.Input = vms[i-1].Output
  19. } else if feedback {
  20. vm.Input = vms[len(vms)-1].Output
  21. }
  22. }
  23. // Seed the phase settings
  24. for i, vm := range vms {
  25. vm.Input <- ps[i]
  26. }
  27. // Background run all but the last VM
  28. for _, vm := range vms[:len(vms)-1] {
  29. go vm.Run()
  30. }
  31. // Kick off the first VM and then wait for the last VM to finish
  32. vms[0].Input <- 0
  33. vms[len(vms)-1].Run()
  34. // Snag the left over value from the last VM's output
  35. return <-vms[len(vms)-1].Output
  36. }
  37. func maxOutput(memoryBanks []int, input []int, ps []int, feedback bool) int {
  38. max := 0
  39. for _, p := range common.Permutations(ps) {
  40. val := runPipeline(memoryBanks, input, p, feedback)
  41. if val > max {
  42. max = val
  43. }
  44. }
  45. return max
  46. }
  47. func main() {
  48. input := common.ReadCsvAsInts("07/input.txt")
  49. memoryBanks := make([]int, len(input)*5)
  50. fmt.Println(maxOutput(memoryBanks, input, []int{0, 1, 2, 3, 4}, false))
  51. fmt.Println(maxOutput(memoryBanks, input, []int{5, 6, 7, 8, 9}, true))
  52. }