• + 1 comment

    Solution in Haskell.

    These kinds of problems do not play nice with immutability

    import Data.List
    
    makeRowTuples :: [Char] -> [[Int]]
    makeRowTuples row =
      let intValues =  map (\x -> read x :: Int) (words row)
          seperatedValues = partition (\x -> even (snd x)) (zip intValues [0..])
      in zipWith (\x y -> [fst x, fst y]) (fst seperatedValues) (snd seperatedValues)
    
    valueIsInAllRows :: Int -> [[[Int]]] -> Bool
    valueIsInAllRows value rows =
      all (\r -> any (== value) (map (head) r)) rows
      
    removeRelativePrimes :: [Int] -> [[[Int]]] -> [[[ Int ]]]
    removeRelativePrimes truePrimes rows =
      let isTruePrime = (\x -> (head x) `elem` truePrimes)
      in map (\row -> filter isTruePrime row) rows
    
    main = do
      _ <- getLine
      matrix <- getContents
      let rawNumbers = lines matrix
          dataMatrix = map makeRowTuples rawNumbers
          firstValues = map (head) (head dataMatrix)
          truePrimes = filter (\x -> valueIsInAllRows x dataMatrix) firstValues
          matrixWithTruePrimes = removeRelativePrimes truePrimes dataMatrix
          sortedValues = sort (concat matrixWithTruePrimes)
          groupedValues = groupBy (\x y -> (head x) == head y) sortedValues
          answer = concat $ map head groupedValues
      putStrLn (unwords $ map show answer)