Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.88 KB | None | 0 0
  1. import qualified Data.Sequence as DS
  2.  
  3. type Seq = DS.Seq
  4.  
  5. run :: Int -> (Int -> Int -> Int) -> Seq Int -> Seq Int
  6. run zero f seq = DS.update position result seq
  7. where
  8. index = seq `DS.index` (zero + 1)
  9. index' = seq `DS.index` (zero + 2)
  10. result = (seq `DS.index` index) `f` (seq `DS.index` index')
  11. position = seq `DS.index` (zero + 3)
  12.  
  13. opCode :: Int -> Seq Int -> Seq Int
  14. opCode zero seq =
  15. case code of
  16. 1 -> run' (+)
  17. 2 -> run' (*)
  18. 99 -> seq
  19. x -> undefined
  20. where
  21. run' f = run zero f seq
  22. code = seq `DS.index` zero
  23.  
  24. runIntCode :: Seq Int -> Seq Int
  25. runIntCode seq = iter seq 0 (seq `DS.index` 0)
  26. where
  27. iter seq counter 99 = seq
  28. iter seq counter c =
  29. let zero = 4 * counter
  30. next = opCode zero seq
  31. in iter next (succ counter) (next `DS.index` (zero + 4))
  32.  
  33. load :: (Int, Int) -> Seq Int -> Seq Int
  34. load (noun, verb) seq = DS.update 2 verb $ DS.update 1 noun seq
  35.  
  36. prepare :: Seq Int -> Seq Int
  37. prepare = load (2, 12)
  38.  
  39. split :: Char -> String -> [String]
  40. split _ [] = [""]
  41. split c (x:xs)
  42. | x == c = "" : rest
  43. | otherwise = (x : head rest) : tail rest
  44. where
  45. rest = split c xs
  46.  
  47. bruteforce :: Seq Int -> Int -> (Int, Int)
  48. bruteforce seq value =
  49. head $ [(x, x') | x <- [0 .. 99], x' <- [0 .. 99], verify (x, x')]
  50. where
  51. verify pair = (getOutput $ load pair seq) == value
  52.  
  53. getOutput :: Seq Int -> Int
  54. getOutput seq = seq `DS.index` 0
  55.  
  56. main :: IO ()
  57. main = do
  58. file <- readFile "input"
  59. let list = split ',' file
  60. ints = DS.fromList $ map (read :: String -> Int) list -- puzzle input as a sequence
  61. input = prepare ints -- the input but noun = 2 and verb = 12
  62. new = runIntCode input
  63. output = getOutput new -- part 1
  64. (noun, verb) = bruteforce ints 19690720 -- part 2
  65. print "output: "
  66. print output
  67. print "value:"
  68. print (100 * noun + verb)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement