Saturday, 4 June 2016

Haskell: How many are equal in four numbers

Suppose you had given four numbers, you need to find how many of them are equal.

For example,
10 10 10 10 : 4 are equal
10 10 10 30 : 3 are equal
10 10 20 30 : 2 are equal
10 20 30 40: 0 are equal


Sample.hs
import Prelude hiding(max)

max :: Int -> Int -> Int
max x y = if (x >= y) then x else y

howManyEqualIn3 :: Int -> Int -> Int -> Int
howManyEqualIn3 x y z
    | (x == y) && (x == z) = 3
    | (x == y) || (x == z) || (y == z) = 2
    | otherwise = 0

howManyEqualIn4 :: Int -> Int -> Int -> Int -> Int
howManyEqualIn4 w x y z
    | (w == x) && (w == y) && (w == z) = 4
    | otherwise = ((howManyEqualIn3 w x y) `max` (howManyEqualIn3 x y z)) `max` (howManyEqualIn3 w y z)

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> howManyEqualIn4 10 10 10 10
4
*Main> howManyEqualIn4 10 10 10 30
3
*Main> howManyEqualIn4 10 10 20 30
2
*Main> howManyEqualIn4 10 20 30 40
0
*Main> howManyEqualIn4 10 20 30 10
2
*Main> howManyEqualIn4 10 20 20 10
2
*Main> howManyEqualIn4 10 20 20 20
3
*Main> howManyEqualIn4 20 20 20 20
4
*Main> 


Previous                                                 Next                                                 Home

No comments:

Post a Comment