DEV Community

Cover image for Java Daily Coding Problem #008

Java Daily Coding Problem #008

Andrew (he/him) on October 02, 2019

Daily Coding Problem is a website which will send you a programming challenge to your inbox every day. I want to show beginners how to solve some o...
Collapse
 
emlautarom1 profile image
Martín Emanuel

Thanks for sharing your solution! Quite an interesting challenge.

I tried to solve it using Haskell since I'm currently learning the language, and after a few mistakes I ended up with the following code:

data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Eq)

isUnival :: (Eq a) => Tree a -> Bool
isUnival tree = case tree of
  Empty -> False
  Node v l r -> case (l, r) of
    (Node lv _ _, Node rv _ _) -> v == lv && v == rv && isUnival l && isUnival r
    (Node lv _ _, Empty) -> v == lv && isUnival l
    (Empty, Node rv _ _) -> v == rv && isUnival r
    (Empty, Empty) -> True

univalCount :: (Eq a) => Tree a -> Int
univalCount tree = case tree of
  Empty -> 0
  Node _ l r -> if isUnival tree then 1 + childCount else childCount
    where
      childCount = univalCount l + univalCount r

As you can see, it's pretty short, and for me it looks very readable.
Have a nice day!

Collapse
 
awwsmm profile image
Andrew (he/him)

If there's one thing Java ain't, it's succinct. Great solution!

Collapse
 
hot9cups profile image
Ayush Modi

I have only 1 complaint, why did you stop posting :(

Stumbled across these recently and love them! Would love to see more of these from you!