# Functions or Not? – HackerRank Solution

In this post, we will solve Functions or Not HackerRank Solution. This problem (Functions or Not) is a part of HackerRank Functional Programming series.

Contents

## Objective

In this problem, we touch upon a basic concept that is fundamental to Functional Programming: identifying a relation which represents a valid function.

You are given a set of uniqueÂ (x, y)Â ordered pairs constituting a relation. TheÂ x-values form the domain, and theÂ y-values form the range to which they map. For each of these relations, identify whether they may possibly represent a validÂ functionÂ or not.

Note:Â You do not have to find theÂ actualÂ function, you just need to determine that the relation may be representative of some valid function.

## Input Format

The first line contains an integer,Â T, denoting the number of test cases. The subsequent lines describeÂ TÂ test cases, and the input for each test case is as follows:

1. The first line contains an integer,Â N, the number ofÂ (x, y)Â pairs in the test case.
2. TheÂ NÂ subsequent lines each contain two space-separated integers describing the respectiveÂ xÂ andÂ yÂ values for each ordered pair.

## Constraints

• 1 <= T <= 5
• 2 <= N <= 100
• 0 <= x, y <= 500
• x and y are both integers.

## Output Format

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.

Sample Input

``````2
3
1 1
2 2
3 3
4
1 2
2 4
3 6
4 8  ``````

Sample Output

``````YES
YES``````

Explanation

Test Case 0:
N = 3, Ordered Pairs:Â (1, 1), (2, 2), (3, 3)Â The set of ordered pairs represents a relation, which could represent a function such asÂ f : N -> N, f(x) = x. Thus, we printÂ YESÂ on a new line.

Test Case 1:
N = 4, Ordered Pairs:Â (1, 2), (2, 4), (3, 6), (4, 8)
The set of ordered pairs represents a relation, which could represent a function such asÂ f : N -> N,Â f(x) = 2x. Thus, we printÂ YESÂ on a new line.

## Solution – Functions or Not? – HackerRank Solution

Scala

```import java.util.Scanner

object Solution {
def main(args: Array[String]): Unit = {
val sc = new Scanner(System.in)
val t = sc.nextInt

(0 until t).foreach(_ => {
val n = sc.nextInt

println(if ((0 until n).map(_ => (sc.nextInt, sc.nextInt)).groupBy(_._1)
.exists { case (_, list) => list.map(_._2).toSet.size > 1 }) "NO" else "YES")
})
}
}
```

Note: This problem (Functions or Not?) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.