📜  给定数组中具有相同比率的对数

📅  最后修改于: 2022-05-13 01:57:35.942000             🧑  作者: Mango

给定数组中具有相同比率的对数

给定一个由{A, B}形式的N对组成的数组arr[] ,任务是计算索引对(i, j) ,使得arr[i]arr[j]对的比率为相同。

例子:

朴素方法:解决给定问题的最简单方法是生成给定数组的所有可能对并计算比率相同的那些对。检查所有对后,打印获得的对总数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the count of pairs
// having same ratio
long long pairsWithSameRatio(
    vector >& arr)
{
    // Stores the total count of pairs
    int count = 0;
 
    // Traverse the array arr[]
    for (int i = 0; i < arr.size(); i++) {
 
        // Find the first ratio
        double ratio1
            = (double)arr[i].first
              / (double)arr[i].second;
 
        for (int j = i + 1; j < arr.size(); j++) {
 
            // Find the second ratio
            double ratio2 = (double)arr[j].first
                            / (double)arr[j].second;
 
            // Increment the count if
            // the ratio are the same
            if (ratio1 == ratio2) {
                count++;
            }
        }
    }
 
    // Return the total count obtained
    return count;
}
 
// Driver Code
int main()
{
    vector > arr = {
        { 2, 6 }, { 1, 3 }, { 8, 24 }, { 4, 12 }, { 16, 48 }
    };
    cout << pairsWithSameRatio(arr);
 
    return 0;
}


Java
// Java program for the above approach
class GFG {
    static class pair {
        int first, second;
 
        public pair(int first, int second) {
            this.first = first;
            this.second = second;
        }
    }
 
    // Function to find the count of pairs
    // having same ratio
    static long pairsWithSameRatio(pair[] arr)
    {
       
        // Stores the total count of pairs
        int count = 0;
 
        // Traverse the array arr[]
        for (int i = 0; i < arr.length; i++) {
 
            // Find the first ratio
            double ratio1 = (double) arr[i].first / (double) arr[i].second;
 
            for (int j = i + 1; j < arr.length; j++) {
 
                // Find the second ratio
                double ratio2 = (double) arr[j].first / (double) arr[j].second;
 
                // Increment the count if
                // the ratio are the same
                if (ratio1 == ratio2) {
                    count++;
                }
            }
        }
 
        // Return the total count obtained
        return count;
    }
 
    // Driver Code
    public static void main(String[] args) {
        pair[] arr = { new pair(2, 6), new pair(1, 3), new pair(8, 24), new pair(4, 12), new pair(16, 48) };
        System.out.print(pairsWithSameRatio(arr));
 
    }
}
 
// This code is contributed by shikhasingrajput


Python3
# Python 3 program for the above approach
 
# Function to find the count of pairs
# having same ratio
def pairsWithSameRatio(arr):
   
    # Stores the total count of pairs
    count = 0
 
    # Traverse the array arr[]
    for i in range(len(arr)):
       
        # Find the first ratio
        ratio1 = arr[i][0]//arr[i][1]
 
        for j in range(i + 1, len(arr), 1):
           
            # Find the second ratio
            ratio2 = arr[j][0]//arr[j][1]
 
            # Increment the count if
            # the ratio are the same
            if (ratio1 == ratio2):
                count += 1
 
    # Return the total count obtained
    return count
 
# Driver Code
if __name__ == '__main__':
    arr = [[2, 6],[1, 3],[8, 24],[4, 12],[16, 48]]
    print(pairsWithSameRatio(arr))
     
    # This code is contributed by SURENDRA_GANGWAR.


C#
// C# program for the above approach
using System;
 
public class GFG {
    class pair {
        public int first, second;
 
        public pair(int first, int second) {
            this.first = first;
            this.second = second;
        }
    }
 
    // Function to find the count of pairs
    // having same ratio
    static long pairsWithSameRatio(pair[] arr)
    {
       
        // Stores the total count of pairs
        int count = 0;
 
        // Traverse the array []arr
        for (int i = 0; i < arr.Length; i++) {
 
            // Find the first ratio
            double ratio1 = (double) arr[i].first / (double) arr[i].second;
 
            for (int j = i + 1; j < arr.Length; j++) {
 
                // Find the second ratio
                double ratio2 = (double) arr[j].first / (double) arr[j].second;
 
                // Increment the count if
                // the ratio are the same
                if (ratio1 == ratio2) {
                    count++;
                }
            }
        }
 
        // Return the total count obtained
        return count;
    }
 
    // Driver Code
    public static void Main(String[] args) {
        pair[] arr = { new pair(2, 6), new pair(1, 3), new pair(8, 24), new pair(4, 12), new pair(16, 48) };
        Console.Write(pairsWithSameRatio(arr));
 
    }
}
 
  
 
// This code is contributed by 29AjayKumar


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Returns factorial of N
int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
int pairsWithSameRatio(
    vector >& arr)
{
    // Stores the frequency of the ratios
    unordered_map mp;
    int ans = 0;
 
    // Filling the map
    for (auto x : arr) {
        mp[x.first / x.second] += 1;
    }
 
    for (auto x : mp) {
        int val = x.second;
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
int main()
{
    vector > arr = {
        { 2, 6 }, { 1, 3 }, { 8, 24 }, { 4, 12 }, { 16, 48 }
    };
    cout << pairsWithSameRatio(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
   
// Returns factorial of N
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
static int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
static int pairsWithSameRatio(
    pair []arr)
{
   
    // Stores the frequency of the ratios
    Map mp = new HashMap();
    int ans = 0;
 
    // Filling the map
    for (pair x : arr) {
        if(mp.containsKey((double) (x.first / x.second))){
            mp.put((double) (x.first / x.second), mp.get((double) (x.first / x.second))+1);
        }
        else{
            mp.put((double)(x.first / x.second), 1);
        }
    }
 
    for (Map.Entry x : mp.entrySet()){
        int val = x.getValue();
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    pair []arr = {
            new pair( 2, 6 ), new pair( 1, 3 ), new pair( 8, 24 ), new pair( 4, 12 ), new pair( 16, 48 )
    };
    System.out.print(pairsWithSameRatio(arr));
 
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python 3 program for the above approach
from collections import defaultdict
 
# Returns factorial of N
def fact(n):
 
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res
 
# Return the value of nCr
def nCr(n, r):
 
    return fact(n) // (fact(r) * fact(n - r))
 
# Function to count the number of pairs
# having the same ratio
def pairsWithSameRatio(arr):
 
    # Stores the frequency of the ratios
    mp = defaultdict(int)
    ans = 0
 
    # Filling the map
    for x in arr:
        mp[x[0] // x[1]] += 1
 
    for x in mp:
        val = mp[x]
 
        # Find the count of pairs with
        # current key as the ratio
        if (val > 1):
            ans += nCr(val, 2)
 
    # Return the total count
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    arr = [[2, 6], [1, 3], [8, 24], [4, 12], [16, 48]]
    print(pairsWithSameRatio(arr))
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
class pair
{
    public int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
   
// Returns factorial of N
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
static int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
static int pairsWithSameRatio(
    pair []arr)
{
   
    // Stores the frequency of the ratios
    Dictionary mp = new Dictionary();
    int ans = 0;
 
    // Filling the map
    foreach (pair x in arr) {
        if(mp.ContainsKey((double) (x.first / x.second))){
            mp[(double) (x.first / x.second)]=mp[(double) (x.first / x.second)]+1;
        }
        else{
            mp.Add((double)(x.first / x.second), 1);
        }
    }
 
    foreach (KeyValuePair x in mp){
        int val = x.Value;
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    pair []arr = {
            new pair( 2, 6 ), new pair( 1, 3 ), new pair( 8, 24 ), new pair( 4, 12 ), new pair( 16, 48 )
    };
    Console.Write(pairsWithSameRatio(arr));
 
}
}
 
// This code is contributed by 29AjayKumar


Javascript



输出:
10

时间复杂度: O(N 2 )
辅助空间: O(1)

高效方法:上述方法可以通过使用映射进行优化,方法是存储给定数组arr[]中每对比率的频率,然后计算形成的对总数。请按照以下步骤解决给定问题:

  • 初始化一个变量,比如ans0 ,它存储具有相同比率的对的总数。
  • 创建一个无序映射,例如将键存储为数组元素对的比率和值存储为它们的频率的映射。
  • 遍历给定的数组arr[]并为每一对{A, B}将地图中A/B的频率增加1
  • 如果任何键的频率大于 1,则遍历映射Map和每个键值对,然后将频率值*(频率 - 1)/2的值添加到变量ans存储与当前的对的结果计数作为比例。
  • 完成上述步骤后,打印ans的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Returns factorial of N
int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
int pairsWithSameRatio(
    vector >& arr)
{
    // Stores the frequency of the ratios
    unordered_map mp;
    int ans = 0;
 
    // Filling the map
    for (auto x : arr) {
        mp[x.first / x.second] += 1;
    }
 
    for (auto x : mp) {
        int val = x.second;
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
int main()
{
    vector > arr = {
        { 2, 6 }, { 1, 3 }, { 8, 24 }, { 4, 12 }, { 16, 48 }
    };
    cout << pairsWithSameRatio(arr);
 
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
static class pair
{
    int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
   
// Returns factorial of N
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
static int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
static int pairsWithSameRatio(
    pair []arr)
{
   
    // Stores the frequency of the ratios
    Map mp = new HashMap();
    int ans = 0;
 
    // Filling the map
    for (pair x : arr) {
        if(mp.containsKey((double) (x.first / x.second))){
            mp.put((double) (x.first / x.second), mp.get((double) (x.first / x.second))+1);
        }
        else{
            mp.put((double)(x.first / x.second), 1);
        }
    }
 
    for (Map.Entry x : mp.entrySet()){
        int val = x.getValue();
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    pair []arr = {
            new pair( 2, 6 ), new pair( 1, 3 ), new pair( 8, 24 ), new pair( 4, 12 ), new pair( 16, 48 )
    };
    System.out.print(pairsWithSameRatio(arr));
 
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python 3 program for the above approach
from collections import defaultdict
 
# Returns factorial of N
def fact(n):
 
    res = 1
    for i in range(2, n + 1):
        res = res * i
    return res
 
# Return the value of nCr
def nCr(n, r):
 
    return fact(n) // (fact(r) * fact(n - r))
 
# Function to count the number of pairs
# having the same ratio
def pairsWithSameRatio(arr):
 
    # Stores the frequency of the ratios
    mp = defaultdict(int)
    ans = 0
 
    # Filling the map
    for x in arr:
        mp[x[0] // x[1]] += 1
 
    for x in mp:
        val = mp[x]
 
        # Find the count of pairs with
        # current key as the ratio
        if (val > 1):
            ans += nCr(val, 2)
 
    # Return the total count
    return ans
 
# Driver Code
if __name__ == "__main__":
 
    arr = [[2, 6], [1, 3], [8, 24], [4, 12], [16, 48]]
    print(pairsWithSameRatio(arr))
 
    # This code is contributed by ukasp.

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
class pair
{
    public int first, second;
    public pair(int first, int second) 
    {
        this.first = first;
        this.second = second;
    }   
}
   
// Returns factorial of N
static int fact(int n)
{
    int res = 1;
    for (int i = 2; i <= n; i++)
        res = res * i;
    return res;
}
 
// Return the value of nCr
static int nCr(int n, int r)
{
    return fact(n) / (fact(r) * fact(n - r));
}
 
// Function to count the number of pairs
// having the same ratio
static int pairsWithSameRatio(
    pair []arr)
{
   
    // Stores the frequency of the ratios
    Dictionary mp = new Dictionary();
    int ans = 0;
 
    // Filling the map
    foreach (pair x in arr) {
        if(mp.ContainsKey((double) (x.first / x.second))){
            mp[(double) (x.first / x.second)]=mp[(double) (x.first / x.second)]+1;
        }
        else{
            mp.Add((double)(x.first / x.second), 1);
        }
    }
 
    foreach (KeyValuePair x in mp){
        int val = x.Value;
 
        // Find the count of pairs with
        // current key as the ratio
        if (val > 1) {
            ans += nCr(val, 2);
        }
    }
 
    // Return the total count
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    pair []arr = {
            new pair( 2, 6 ), new pair( 1, 3 ), new pair( 8, 24 ), new pair( 4, 12 ), new pair( 16, 48 )
    };
    Console.Write(pairsWithSameRatio(arr));
 
}
}
 
// This code is contributed by 29AjayKumar

Javascript



输出:
10

时间复杂度: O(N)
辅助空间: O(N)