aboutsummaryrefslogtreecommitdiff
path: root/Puzzle6.hs
blob: 1f9ac7f439f5c93772b703ad8833929ea24a8f80 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
{-
Copyright (C) 2017 Yuchen Pei.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU Affero General Public
License along with this program.  If not, see
<https://www.gnu.org/licenses/>.
-}
import Data.List (elemIndex)
import Data.List.Split (splitOn)
import Data.Maybe (fromJust)
--import Control.Monad (liftM2)

incList :: Int -> Int -> Int -> [Int]
incList n q r = replicate r (q + 1) ++ replicate (n - r - 1) q

f :: [Int] -> [Int]
f xs = (drop (n - m) zs) ++ (take (n - m) zs)
  where p = maximum xs
        n = length xs
        q = p `div` n
        r = p `mod` n
        m = (fromJust $ elemIndex p xs) + 1
        ys = drop m (cycle xs)
        zs = (take (n - 1) $ zipWith (+) ys (incList n q r)) ++ [q]

g :: [[Int]] -> [[Int]]
g xs = (f $ head xs):xs

looped :: [Int] -> [[Int]]
looped xs = until (\ys -> (head ys) `elem` (tail ys)) g [xs]

solve1' :: [Int] -> Int
solve1' xs = (length $ looped xs) - 1

solve2' :: [Int] -> Int
solve2' xs = let (y:ys) = looped xs in (fromJust $ elemIndex y ys) + 1

parseInput :: [Char] -> [Int]
parseInput xs = map read $ splitOn " " xs

solve1 :: [Char] -> Int
solve1 = solve1' . parseInput

solve2 :: [Char] -> Int
solve2 = solve2' . parseInput

input :: [Char]
input = "4 10 4 1 8 4 9 14 5 1 14 15 0 15 3 5"