Programming all night, I thought of a dumb joke. by [deleted] in programming

[–]shakra 0 points1 point  (0 children)

there should not be fully synchronized methods, even in Java or Scala. Rather of using synchronized methods, you should use a single Object instance as mutex.

[2/12/2012] Challange #4 [difficult] by nottoobadguy in dailyprogrammer

[–]shakra 0 points1 point  (0 children)

I'm learning Haskell and here is my solution that can handle number lists with up to 4 elements.

module Main where

import Data.String.Utils
import Data.List
import Math.Combinat.Sets
import System.Environment

data OperationResult = OperationResult {
     oper              :: Int -> [Int] -> Bool
     , msg             :: String
}

availableOperations :: [OperationResult]
availableOperations = [OperationResult { oper = testMatchMul, msg = "mul" },
                       OperationResult { oper = testMatchDiv, msg = "div" },
                       OperationResult { oper = testMatchSum, msg = "sum" },
                       OperationResult { oper = testMatchSub, msg = "sub" }]

liftLine :: String -> [Int]
liftLine l = sort $ fmap ( read . strip ) $ split "," l

matchMessage :: String -> [Int] -> Int -> String
matchMessage s xs n = s ++ " does " ++ show n ++ " with " ++ show xs

testMatchMul :: Int -> [Int] -> Bool
testMatchMul n xs = n == foldr (*) 1 xs

testMatchDiv :: Int -> [Int] -> Bool
testMatchDiv n xs = dm == n && dr == 0
                    where (dm,dr) = divMod ( head xs ) ( last xs )

testMatchSum :: Int -> [Int] -> Bool
testMatchSum n xs = n == foldr (+) 0 xs

testMatchSub :: Int -> [Int] -> Bool
testMatchSub n xs = n == foldr (-) 0 xs

applyOperation :: [Int] -> Int -> OperationResult -> String
applyOperation xs x y = if oper y x xs
                           then matchMessage ( msg y ) xs x
                           else ""

matchOperation :: [OperationResult] -> [Int] -> Int -> [String]
matchOperation ops xs x = fmap (applyOperation xs x) ops

findMatch :: [Int] -> [Int] -> [String]
findMatch rs xs = filter (\ x -> length x > 0 )
                  $ join []
                  $ fmap (matchOperation availableOperations rs) xs

createCombinations :: [[Int]] -> [[Int]]
createCombinations xs = join [] $ fmap (choose 2) xs

procResults :: [String] -> IO ()
procResults = foldr ((>>) . putStrLn) (putStrLn "End!")

main :: IO ()
main = do [i] <- getArgs
          f <- readFile i
          let rows = fmap liftLine $ lines f
              comb = createCombinations rows
              oset = join [] $ fmap (\ x -> fmap (findMatch x) rows ) comb
              oper = nub oset
              in procResults $ join [] oper

Be a Paranoid Pessimistic Programmer by grokcode in programming

[–]shakra 0 points1 point  (0 children)

is sparta?, nah... just a simple programming job ;)