Updated readme
[advent-of-code-16.git] / advent11.hs
index af048de2f7090c05d09ebd1a68b9a058eb386396..fd96636830de0ea89fe69ff06fc187d0edbb83a1 100644 (file)
@@ -44,29 +44,41 @@ buildingTest = Building 0 [
 main :: IO ()
 main = do 
     part1 
-    part2 
+    -- part2 
 
 
 part1 :: IO ()
--- part1 = print $ length $ init $ extractJust $ aStar [[buildingTest]] []
+-- part1 = print $ length $ init $ extractJust $ hillClimb [[buildingTest]] []
+-- part1 = print $ length $ init $ extractJust $ hillClimb [[building1]] []
 part1 = print $ length $ init $ extractJust $ aStar [[building1]] []
 
 part2 :: IO ()
-part2 = print $ length $ init $ extractJust $ aStar [[building2]] []
+part2 = print $ length $ init $ extractJust $ hillClimb [[building2]] []
 
 
 extractJust :: Maybe [a] -> [a]
 extractJust Nothing = []
 extractJust (Just x) = x
 
+hillClimb :: [[Building]] -> [Building] -> Maybe [Building]
+hillClimb [] _ = Nothing
+hillClimb (currentTrail:trails) closed = 
+    if isGoal (head currentTrail) then Just currentTrail
+    else hillClimb newAgenda ((head currentTrail): closed) 
+    where newAgenda = 
+            sortBy (\t1 t2 -> (head t1) `compare` (head t2)) $ 
+            trails ++ (candidates currentTrail closed)
+
 aStar :: [[Building]] -> [Building] -> Maybe [Building]
 aStar [] _ = Nothing
 aStar (currentTrail:trails) closed = 
     if isGoal (head currentTrail) then Just currentTrail
     else aStar newAgenda ((head currentTrail): closed) 
     where newAgenda = 
-            sortBy (\t1 t2 -> (head t1) `compare` (head t2)) $ 
+            sortBy (\t1 t2 -> (trailCost t1) `compare` (trailCost t2)) $ 
             trails ++ (candidates currentTrail closed)
+          trailCost t = estimateCost (head t) + length t - 1
+
 
 candidates :: [Building] -> [Building] -> [[Building]]
 candidates currentTrail closed = newCandidates
@@ -110,10 +122,8 @@ legalSuccessors :: [Building] -> [Building]
 legalSuccessors = filter (isLegal)
 
 updateBuilding :: Int -> [Floor] -> Int -> [Item] -> Building
--- updateBuilding f floors _ _ = Building f floors
 updateBuilding oldF oldFloors newF items = Building newF newFloors
-    where numberedFloors = zip [0..] oldFloors
-          newFloors = map (updateFloor) numberedFloors
+    where newFloors = map (updateFloor) $ zip [0..] oldFloors
           updateFloor (f, fl) 
             | f == oldF = sort $ fl \\ items
             | f == newF = sort $ items ++ fl