给定两个不同的数组,任务是找到随机对被选为最大加权对的概率。
一对将包含一个来自数组1的元素,另一个包含另一个数组,例如array2的元素。因此,程序必须找到包含第一个元素作为数组1的最大元素和包含第二个元素作为数组2的最大元素的对的概率,从而形成最大的加权对。
输入项
arr1[] = { 2, 23 } arr2[] = { 10, 3, 8 }
输出结果
probability of maximum pair : 0.166667
说明
set of pairs from both the arrays are -: {(2, 10), (2, 3), (2, 8), (23, 10), (23, 3), (23, 8)} Maximum weighted pair from the given set is: (23, 8) Probability is : 1 / 6 = 0.166667
输入-
arr1[] = { 4, 5, 6 } arr2[] = { 6, 2, 6 }
输出-
probability of maximum pair : 0.222222
说明
set of pairs from both the arrays are -: {(4, 6), (4, 2), (4, 6), (5, 6), (5, 2), (5, 6), (6, 6), (6, 2), (6, 6)} Maximum weighted pair from the given set is (6, 6) which is occurring twice. Probability is : 2 / 9 = 0.2222
输入数组元素
从两个数组中找到最大元素,并计算由此形成的最大加权对的总数
通过将最大加权对的总数除以集合中对的总数来计算概率
打印计算出的概率
Start Step1→ declare function to calculate maximum weighted pair double max_pair(int arr1[], int arr2[], int size_1, int size_2) declare int max_pair1 = INT_MIN, count_1 = 0 Loop For int i = 0 and i < size_1 and i++ IF arr1[i] > max_pair1 Set max_pair1 = arr1[i] Set count_1 = 1 End Else IF arr1[i] = max_pair1 Set count_1++ End End Declare int max_pair2 = INT_MIN, count_2 = 0 Loop For int i = 0 and i < size_2 and i++ IF arr2[i] > max_pair2 Set max_pair2 = arr2[i] Set count_2 = 1 End Else IFarr2[i] = max_pair2 Set count_2++ End End return (double)(count_1 * count_2) / (size_1 * size_2) Step 2→ In main() Declare int arr1[] = { 2, 23 } Declare int arr2[] = { 10, 3, 8 } Calculate int size_1 = sizeof(arr1) / sizeof(arr1[0]) Calculate int size_2 = sizeof(arr2) / sizeof(arr2[0]) Call max_pair(arr1, arr2, size_1, size_2) Stop
#include <bits/stdc++.h> using namespace std; //函数返回概率 double max_pair(int arr1[], int arr2[], int size_1, int size_2){ //数组1中的一对 int max_pair1 = INT_MIN, count_1 = 0; for (int i = 0; i < size_1; i++){ if (arr1[i] > max_pair1){ max_pair1 = arr1[i]; count_1 = 1; } else if (arr1[i] == max_pair1){ count_1++; } } //数组2中的一对 int max_pair2 = INT_MIN, count_2 = 0; for (int i = 0; i < size_2; i++){ if (arr2[i] > max_pair2){ max_pair2 = arr2[i]; count_2 = 1; } else if (arr2[i] == max_pair2){ count_2++; } } return (double)(count_1 * count_2) / (size_1 * size_2); } int main(){ int arr1[] = { 2, 23 }; int arr2[] = { 10, 3, 8 }; int size_1 = sizeof(arr1) / sizeof(arr1[0]); int size_2 = sizeof(arr2) / sizeof(arr2[0]); cout <<"probability of maximum pair in both the arrays are "<<max_pair(arr1, arr2, size_1, size_2); return 0; }
输出结果
如果运行上面的代码,它将生成以下输出-
probability of maximum pair in both the arrays are 0.166667