/ HackerRank Functional Challenges

HR F#: Functions or Not?

The Functions or Not? problem is defined as follows:

You are given a set of unique (x, y) ordered pairs constituting a relation. For each of these relations, identify whether they may possibly represent a valid function or not. On a new line for each test case, print YES if the set of ordered pairs represent a valid function, or NO if they do not.

The definition of the function helps to get the idea on how to solve this problem (from Wikipedia):

In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output.

This property holds for the both sample inputs so they result in YES. There is no sample negative input. It should be crafted in order to test the code:

1 2
2 3
1 1
1 2

There is a function for the first set of pairs and there is no function for the second set.

F# solution:

open System

let main argv = 
  let t = Console.ReadLine () |> int
  seq { for _ in 1..t do
          let n = Console.ReadLine () |> int
          yield seq { for _ in 1..n do
                        yield (Console.ReadLine ()).Split(' ') }
                |> Seq.groupBy (fun v -> v.[0])
                |> Seq.forall (fun v -> 1 = ((snd v)
                                             |> Seq.map (fun q -> q.[1])
                                             |> Seq.distinct
                                             |> Seq.length))
                |> function | true -> "YES" | _ -> "NO" }
  |> Seq.iter (printfn "%s")
  0 // return an integer exit code
Alex Netkachov

Alex Netkachov

Alex works at Central London on the next generation of energy trading solutions to traders, brokers and exchanges worldwide.

Read More

Why not to stay updated if the subject is interesting? Join Telegram channel Alex@Net or follow alex_at_net on Twitter. Or just, use the comments form below.