Problem
Balanced number is the number that the sum of all digits to the left of the middle digit(s) and the sum of all digits to the right of the middle digit(s) are equal. The middle digit(s) should not be considered when determining whether a number is balanced or not.
If the number has an odd number of digits then there is only one middle digit, e.g. 92645 has middle digit 6; otherwise, there are two middle digits , e.g. 1301 has middle digits 3 and 0.
Given a number, find if it is balanced or not. Number passed is always Positive. Return the result as String.
My solution
I solved it. But I am not sure, how to fold the similarly looking code for odd and even lengths.
data ListLength a = ListLength {list :: [a], len :: Int} deriving Show
digs :: Integral x => x -> ListLength x
digs 0 = ListLength [0] 1
digs x = let
helper :: Integral x => x -> [x] -> Int -> ListLength x
helper 0 acc len = ListLength acc len
helper n acc len = helper (n `div` 10) ((n `mod` 10) : acc) $ len + 1
in
helper x [] 0
balancedNum :: Int -> String
balancedNum n | n > 0 = let digits = digs n
middle = (len digits) `div` 2
in
if even (len digits) then
let (left, right) = splitAt (middle - 1) (list digits) in
if (sum left) == (sum $ drop 2 right) then
"Balanced"
else
"Not Balanced"
else
let (left, right) = splitAt middle (list digits) in
if (sum left) == (sum $ tail right) then
"Balanced"
else
"Not Balanced"
| otherwise = error "Number must be positive"