DEV Community

Discussion on: Daily Challenge #99 - Balance the Scales

Collapse
 
aminnairi profile image
Amin • Edited

Haskell

Note: I'm really unsure about what I have done since I'm pretty new to Haskell and that there are no expected result for the test cases (or I'm both blinded & tired).

Note 2: it seems like in the example given, 1 & 6 can be used to balance the result. Since 1 & 6 are lower than 2 & 7, it makes them the least amounts to use for balance. Or I didn't understand the problem well enough.

Note 3: this implementation assumes that there will always be an input of format which is described above. Of course this will fail if the strings are differents.

import Data.List (find)

readIntegersFrom :: String -> [Int]
readIntegersFrom string =
    read string :: [Int]

combinationPairs :: [Int] -> [(Int, Int)]
combinationPairs integers =
    (,) <$> integers <*> integers

equalizer :: [Int] -> (Int, Int) -> Bool
equalizer balance (left, right) =
    left + head balance == right + last balance

scale :: [String] -> Maybe (Int, Int)
scale strings =
    find (equalizer balance) combinations
    where
        balance :: [Int]
        balance = readIntegersFrom $ head strings

        weights :: [Int]
        weights = readIntegersFrom $ last strings

        combinations :: [(Int, Int)]
        combinations = combinationPairs weights

main :: IO ()
main = do
    print $ scale ["[9,4]", "[1,2,6,7]"]    -- Just (1, 6)
    print $ scale ["[1,2]","[10,3,6,6]"]    -- Nothing
    print $ scale ["[20,5]","[1,6,10,4]"]   -- Nothing
    print $ scale ["[0,13]","[4,6,3,7]"]    -- Nothing

Playground

Try it online here.

Collapse
 
craigmc08 profile image
Craig McIlwrath

Just spent a few moments reading through your code. Here is some feedback I have, but I'm also kinda new so don't take it too seriously.

  1. You should consider converting the first input array to a 2-tuple. You use it as a tuple in equalizer so having the type be a tuple will make the code clearer. It also forces you to do a little bit of input validation, which is always nice :D

  2. Some functions don't have a great name. Specifically, equalizer and combinationPairs. Personally, they should probably be verbs. combinations = combinePairs weights sounds a bit nicer, in my opinion.

Also, I like the use of applicative functors for the combinePairs function :)

Collapse
 
aminnairi profile image
Amin

Thanks for taking some time to help me on my journey.