Declaratieve Talen/oplossingBallen

Uit Wina Examenwiki
Naar navigatie springen Naar zoeken springen

Een oplossing voor het eerste deel:

import Data.List

-- Bereken alle mogelijke mappings tussen twee foto's, gegeven de tijdspanne
-- tussen deze foto's.
berekenMappings :: [Int] -> [Int] -> Int -> [[(Int,Int)]]
berekenMappings f1 f2 t = filterMappings ( combinations f1 (allMappings f1 f2 t))

-- Zoek alle mogelijke combinaties van een positie uit Foto1 met een positie uit Foto2.
-- Een combinatie is mogelijk als: abs(oude_positie - nieuwe_positie) = Tijd
-- Main> allMappings [10,12] [9,11,14] 1
-- [(10,9), (10,11), (12,11)]
allMappings :: [Int] -> [Int] -> Int -> [(Int,Int)]
allMappings f1 f2 t = 
    [(old_pos, new_pos) | old_pos <- f1,
                          new_pos <- f2, 
                          abs (old_pos - new_pos) == t]

-- Groepeer allMappings.
-- Main> combinations [10,12] [(10,9), (10,11), (12,11)]
-- [ [(10,9), (12,11)] , [(10,11), (12,11)] ]
combinations :: [Int] -> [(Int,Int)] -> [[(Int,Int)]]
combinations [] _  = [ [] ]
combinations (oldPosition:oldPositions) mappings = 
    [ (o,n):ys | (o,n):mappings' <- tails mappings,
                 o == oldPosition,
                 ys <- combinations oldPositions mappings'] 

-- Filter ongeldige mappings.
-- Mappings genre [(10,11), (12,11)] moeten nog weggefilterd worden.
-- Main> filterMappings [ [(10,9), (12,11)] , [(10,11), (12,11)] ]
-- [ [(10,9), (12,11)] ]
filterMappings :: [[(Int,Int)]] -> [[(Int,Int)]]
filterMappings [] = []
filterMappings (m:ms) 
    | ok        = m:filterMappings ms
    | otherwise = filterMappings ms
    where ok = noDoubles newPos
          noDoubles xs = (length xs == length (nub xs))
          newPos = map snd m

--Pieter 14 jan 2014 23:18 (UTC)