Write a program for “Number of Pairs” ?

Number of Pairs Requirement:

Given two arrays X and Y of positive integers, find the number of pairs that satisfies this condition xy > yx where x is an element from X or array 1 and y is an element from Y or array 2.

Input: 
X[] = [2 4] 
Y[] = [1 3]
Output: 3
Explanation: 
All the possible pairs are for xy > yx are:
21 > 12 [2 > 1 => true],  
23 > 32 [8 > 9 => false],
41 > 14 [4 > 1 => true],
43 > 34 [64 > 81 => false]
So the output shoule be => 2 [only true condition values]

Number of Pairs Logic:

The logic is to keep the counter variable to count/increment on the condition which satisfies the xy > yx

Programmatic steps:

  • Have nested for loops to complete the iteration for every possible values in both the arrays.
  • Calculate the Math.pow(x, y) and Math.pow(y,x)
  • Increment the counter variable which satisifies only this condition [Math.pow(x, y) > Math.pow(y,x)] and return the same.

Optimised or Improved solution would be:

To store the already evaluated results to apply the true/false directly instead of executing the complete Math.pow logics.

For Example, if you have x array as {1,2,1,3} and y array as {2,7,9}, here since you have number 1 as two times in the x array, now if we have the results stored in collections like map then duplicate numbers can be skipped for the whole logic execution and can directly be applied with the true / false solutions.

That is something, you can try and post in the comments section, otherwise later sometime I will post that as well.

Number of PairsProgram [Java] Source code:

package com.ngdeveloper;

public class NumberOfParis {
    public static void main(String[] args) {
        int[] x = {2, 4};
        int[] y = {1, 3};
        System.out.println(numberOfPairs(x,y));
    }

    static int numberOfPairs(int[] x, int[] y){
        int counter =0;
        for(int outer=0;outer<x.length;outer++){
            for(int inner=0;inner<y.length;inner++){
                if(Math.pow(x[outer], y[inner]) > Math.pow(y[inner], x[outer])){
                    counter++;
                }
            }
        }
        return counter;
    }
}

Output:

2

Leave a Reply