【发布时间】:2017-03-30 07:28:58
【问题描述】:
使用预定义的数字数组,我如何使用 PHP 生成一个多维数组,将所有因子对按其产品分组?
输入数组:
$array = array(1,2,3,4,5,6,7,8);
我想显示每个产品组具有多个因子对的所有因子对。
如果没有产品组具有多个因子对,则应显示
No pairs Found。
鉴于上述输入,这是我的预期结果:
1 6 and 2 3 // product group = 6
1 8 and 2 4 // product group = 8
2 6 and 3 4 // product group = 12
3 8 and 4 6 // product group = 24
*注意随着输入数组大小的增加,输出将显示每组超过两个因子对。
这是我的 C++ 代码:
void findPairs(int arr[], int n)
{
bool found = false;
unordered_map<int, pair < int, int > > H;
for (int i=0; i<n; i++)
{
for (int j=i+1; j<n; j++)
{
// If product of pair is not in hash table,
// then store it
int prod = arr[i]*arr[j];
if (H.find(prod) == H.end())
H[prod] = make_pair(i,j);
// If product of pair is also available in
// then print current and previous pair
else
{
pair<int,int> pp = H[prod];
cout << arr[pp.first] << " " << arr[pp.second]
<< " and " << arr[i]<<" "<<arr[j]<<endl;
found = true;
}
}
}
// If no pair find then print not found
if (found == false)
cout << "No pairs Found" << endl;
}
【问题讨论】:
-
它背后的逻辑是什么?
-
我可以在 c++ 中做同样的事情,但在 php 中不行
-
我同意,但是输出背后的逻辑意味着你如何获得输出?或者更确切地说,您可以在这里发布您的 c++ 代码
-
像 1*6 = 2*3 = 6 as ab= cd
-
发布一些代码。甚至 C++ 代码也能提供帮助。
标签: php grouping elements multiplication factors