Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

main.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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)
  14. vms[i].Output = make(chan int, 2)
  15. }
  16. // Link all the inputs and outputs
  17. for i, vm := range vms {
  18. if i > 0 {
  19. vm.Input = vms[i-1].Output
  20. } else if feedback {
  21. vm.Input = vms[len(vms)-1].Output
  22. } else {
  23. vm.Input = make(chan int, 2)
  24. }
  25. }
  26. // Seed the phase settings
  27. for i, vm := range vms {
  28. vm.Input <- ps[i]
  29. }
  30. // Background run all but the last VM
  31. for _, vm := range vms[:len(vms)-1] {
  32. go vm.Run()
  33. }
  34. // Kick off the first VM and then wait for the last VM to finish
  35. vms[0].Input <- 0
  36. vms[len(vms)-1].Run()
  37. // Snag the left over value from the last VM's output
  38. return <-vms[len(vms)-1].Output
  39. }
  40. func maxOutput(memoryBanks []int, input []int, ps []int, feedback bool) int {
  41. max := 0
  42. for _, p := range common.Permutations(ps) {
  43. val := runPipeline(memoryBanks, input, p, feedback)
  44. if val > max {
  45. max = val
  46. }
  47. }
  48. return max
  49. }
  50. func main() {
  51. input := common.ReadCsvAsInts("07/input.txt")
  52. memoryBanks := make([]int, len(input)*5)
  53. fmt.Println(maxOutput(memoryBanks, input, []int{0, 1, 2, 3, 4}, false))
  54. fmt.Println(maxOutput(memoryBanks, input, []int{5, 6, 7, 8, 9}, true))
  55. }