0

This is the question

Given an array A of N numbers, find the number of distinct pairs (i, j) such that j >=i and A[i] = A[j].

First line of the input contains number of test cases T. Each test case has two lines, first line is the number N, followed by a line consisting of N integers which are the elements of array A.

For each test case print the number of distinct pairs.

Constraints

1 <= T <= 10

1 <= N <= 10^6

-10^6 <= A[i] <= 10^6 for 0 <= i < N

SAMPLE INPUT 
2
4
1 2 3 4
3
1 2 1
SAMPLE OUTPUT 
4
4

Want a simple java code solution with explanation of all the functions and code used

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

Here is something that I threw together using a bit of code from here:

how to take user input in Array using java?

This code asks the user to input an array by hand, you will have to implement reading in an array from some file if that is needed.

import java.util.*;

public class UserInput
{
    public static void main(String[] args)
    {
        List<String> list = new ArrayList<String>();
        Scanner stdin = new Scanner(System.in);

        do
        {
            System.out.println("Current list is " + list);
            System.out.println("Add more? (y/n)");
            if (stdin.next().startsWith("y"))
            {
                System.out.println("Enter : ");
                list.add(stdin.next());
            }
            else
            {
                break;
            }
        } while (true);
        stdin.close();
        System.out.println("List is " + list);
        String[] arr = list.toArray(new String[0]);
        
        for(int i = 0; i < arr.length; i++)
        {
            for(int j = i + 1; j < arr.length; j++)
            {
                if(arr[i].equals(arr[j]))
                {
                    System.out.println("Pair Found! --> i: " + i + " j: " + j);
                }
            }
        }
    }
}
MFerguson
  • 1,739
  • 9
  • 17
  • 30