$arr = [ 'a'=>[0,1,2,3], 'b'=>[0,1,2,3,6,7], 'c'=>[1,2,3,4,7,8,9], 'd'=>[6,8,1,3,5]];//上面组成的新数组:$new = [ count($arr[a]) * count($arr[b]), count($arr[a]) * count($arr[c]), count($arr[a]) * count($arr[d]), count($arr[b) * count($arr[c]), count($arr[b) * count($arr[d]), count($arr[c) * count($arr[d])];//最后把new数组里面的值全部相加
Now there is an array that takes 2 (this could be 3 or more) from the ARR array, and the length of the two array to be multiplied into the new array will eventually add all the values inside the new array and get the result. What I'm doing now is using loops. Is there any formula that can be directly implemented?
Reply content:
$arr = [ 'a'=>[0,1,2,3], 'b'=>[0,1,2,3,6,7], 'c'=>[1,2,3,4,7,8,9], 'd'=>[6,8,1,3,5]];//上面组成的新数组:$new = [ count($arr[a]) * count($arr[b]), count($arr[a]) * count($arr[c]), count($arr[a]) * count($arr[d]), count($arr[b) * count($arr[c]), count($arr[b) * count($arr[d]), count($arr[c) * count($arr[d])];//最后把new数组里面的值全部相加
Now there is an array that takes 2 (this could be 3 or more) from the ARR array, and the length of the two array to be multiplied into the new array will eventually add all the values inside the new array and get the result. What I'm doing now is using loops. Is there any formula that can be directly implemented?
No formula can be implemented, the formula is actually the algorithm, the algorithm may have a loop
[0,1,2,3], 'b'=>[0,1,2,3,6,7], 'c'=>[1,2,3,4,7,8,9], 'd'=>[6,8,1,3,5]];$arr_len = array();foreach($arr as $item) { $arr_len[] = count($item);}// 以上循环可以统计字数组的长度$res = 0; // 要输出的结果$c_arr_len = $arr_len;foreach($arr_len as $k1=>$v1) { unset($c_arr_len[$k1]); // 处理了一个数之后删除 if(count($c_arr_len)>0) { foreach($c_arr_len as $k2=>$v2) { $res += ($v1*$v2); } }}var_dump($res);//得到结果,其实不需要产生你那个$new数组
Yes
2*(a1*a2 + a1*a3 + ... + a2*a3 ...) === ( a1 + a2 + a3 + ... )**2 - (a1**2 + a2**2 + ...)
Then you can use map and reduce to avoid writing loops.
But the complexity is not changing, it's n^2.