aboutsummaryrefslogtreecommitdiff
path: root/challenge-083/jeongoon/haskell/ch-2.hs
diff options
context:
space:
mode:
authorSteve Rogerson <steve.git@yewtc.demon.co.uk>2020-10-23 12:27:13 +0100
committerSteve Rogerson <steve.git@yewtc.demon.co.uk>2020-10-23 12:27:13 +0100
commit44c2bbf87ac613a2a442cc4e54d810c20a042ff2 (patch)
tree3af39af1f773a9e6b44e91a3852a7553dae7c986 /challenge-083/jeongoon/haskell/ch-2.hs
parentff3c07c3e4409c8d507b3e69496c690b58de524d (diff)
parent89421f14095148aefcd254da3d728b6150b22cc3 (diff)
downloadperlweeklychallenge-club-44c2bbf87ac613a2a442cc4e54d810c20a042ff2.tar.gz
perlweeklychallenge-club-44c2bbf87ac613a2a442cc4e54d810c20a042ff2.tar.bz2
perlweeklychallenge-club-44c2bbf87ac613a2a442cc4e54d810c20a042ff2.zip
Merge branch 'master' of https://github.com/manwar/perlweeklychallenge-club
Diffstat (limited to 'challenge-083/jeongoon/haskell/ch-2.hs')
-rw-r--r--challenge-083/jeongoon/haskell/ch-2.hs53
1 files changed, 53 insertions, 0 deletions
diff --git a/challenge-083/jeongoon/haskell/ch-2.hs b/challenge-083/jeongoon/haskell/ch-2.hs
new file mode 100644
index 0000000000..c64170400a
--- /dev/null
+++ b/challenge-083/jeongoon/haskell/ch-2.hs
@@ -0,0 +1,53 @@
+import System.Environment
+import System.Exit
+import Data.Char (isNumber)
+import Data.Maybe (isJust, catMaybes)
+import Data.List (sum)
+import Combinations (combinations)
+
+
+{- test with:
+ runhaskell ch-2.hs 12 7 4 # answer: 12
+ runhaskell ch-2.hs 12 7 4 5 6 9 20 12 7 4 5 6 9 20 9 4 2 1 13 8 # answer: 6
+ # or in order to get faster result, you can compile and execute:
+ ghc ch-2.hs
+ ./ch-2 12 7 4 5 6 9 20 12 7 4 5 6 9 20 9 4 2 1 13 8 # answer: 6
+-}
+
+answerFlipArray :: (Integral a) => [a] -> Int
+answerFlipArray nums
+ | totalSum == 1 = 0
+ | otherwise = answerWith totalSum totalLen numCombis
+ where
+ totalSum = sum nums
+ totalLen = length nums
+ halfLen = totalLen `div` 2
+ numCombis = (foldr1 (++) .
+ map (combinations nums))
+ [ 1 .. halfLen ]
+
+ answerWith _ minElems [] = minElems
+ answerWith minSum minElems (aCombi:otherCombis) =
+ case (positiveSum `compare` minSum) of
+ LT -> answerWith positiveSum newElems otherCombis
+ EQ -> answerWith minSum (min newElems minElems) otherCombis
+ GT -> answerWith minSum minElems otherCombis
+ where
+ len = length aCombi
+ sm = sum aCombi
+ sm' = totalSum - sm
+ (positiveSum, newElems) =
+ case (sm `compare` sm') of
+ LT -> ( sm' - sm, len )
+ EQ -> ( 0, (min len (totalLen - len)) )
+ GT -> ( sm - sm', (totalLen - len) )
+
+main = do
+ (catMaybes.map (\nStr ->
+ if (all isNumber nStr) then Just(read nStr :: Int)
+ else Nothing )) `fmap` getArgs
+ >>= (\nums ->
+ if length nums < 1 then
+ die "Usage: runhaskell ch-2.hs <natural num> ..."
+ else
+ putStrLn $ show ( answerFlipArray nums ) )