Write a java program for Array-Pair Problem

Java program to solve the Array Pair problem that makes pairs of the same data in two arrays. Let’s understand the problem statement and write java code to solve the array pair problem

Problem Statement:

Suppose we are given n white and n black water jugs, all of different shapes and sizes. All black jugs hold different amounts of water, as do the white ones. Moreover, there is a white jug for every black jug that holds the same amount of water and vice-versa. The task is to efficiently group the jugs into pairs of black and white jugs that the same amount of water.

Example:

Input:

Enter the no. of jugs:
3
Enter the quantity in white jugs
1 7 2
Enter the quantity in black jugs
2 1 7

Output:

The pairs are:

( 1, 1 )
( 7, 7 )
( 2, 2 )

Algorithm for Array-Pair Problem:

  1. First, we will take no. of jugs and the quantities of water in two separate arrays.
  2. Next, we will create a for loop which runs from i=0 to i=n-1. It is for the quantity of water in white jugs.
  3. Inside for loop, we will create another nested for loop which runs from j=0 to j=n-1. It is for the quantity of water in black jugs.
  4. The nested for loop will check if the black jug quantity matches with the white jug quantity and returns the index of the black jug.
  5. Next, we will swap the black jug having an index equal to the index found with the index of the white jug using a temporary variable.
  6. The black jug array is now such that it has similar quantities and indices as that of white jugs.

Write a program for the Array-Pair Problem:

import java.util.Scanner;
public class PairProblem 
{
    public static void main(String[] args) 
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the no. of jugs:");
        int n=sc.nextInt();
        int white[]=new int[n];
        int black[]=new int[n];
        System.out.println("Enter the quantity in white jugs");
        for(int i=0;i<n;i++) white[i]=sc.nextInt();
        System.out.println("Enter the quantity in black jugs");
        for(int i=0;i<n;i++) black[i]=sc.nextInt();
        boolean flag=false;
        for(int i=0;i<n;i++)
        {
            flag=false;
            int index=-1;
            for(int j=0;j<n;j++)
            {
                if(white[i]==black[j])
                {
                    index=j;
                    flag=true;
                    break;
                }
            }
            if(flag)
            {
                int temp=black[i];
                black[i]=black[index];
                black[index]=temp;
            }
            else break;
        }
        if(flag)
        {
            System.out.prinltn("The pairs are:");
            for(int i=0;i<n;i++) System.out.println("( "+white[i]+" , "+black[i]+" )");
        }
        else System.out.println("You have entered unequal quanitites of water in jugs");
    }
}

Output for the Array-Pair Problem: