Home  >  Article  >  Backend Development  >  How to build a product array excluding the current element in php (code attached)

How to build a product array excluding the current element in php (code attached)

不言
不言forward
2018-09-30 16:02:163123browse

The content of this article is about how PHP constructs a product array excluding the current element (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Construct a product array
Given an array A[0,1,...,n-1], please construct an array B[0,1,...,n-1], Among them, the element B[i] in B=A[0]*A[1]*...*A[i-1]*A[i 1]*...*A[n-1]. Division cannot be used.

1. The meaning of this question is that the elements of the B array are the products of all the elements in the A array, but the current element must be excluded
2. The A array is divided into two parts around the i element, and they are multiplied separately
3. The left array is A[0]...A[n-1], the right array is A[1]...A[n]
4. Combine a new array

$A=array(1,2,3,4);
multiply($A);
function multiply($numbers){
        $len=count($numbers);
        $res=array();
        //1. 组合左边数组
        $left=array();
        $left[0]=1;
        for($i=1;$i<$len;$i++){
                $left[$i]=$left[$i-1]*$numbers[$i-1];
        }   

        //2. 组合右边数组
        $right=array();
        $right[$len-1]=1;
        for($j=$len-2;$j>=0;$j--){
                $right[$j]=$right[$j+1]*$numbers[$j+1];
        }   

        //3. 组合新数组,整好可以实现A[0]*A[i-1]*A[i+1]*A[n-1]排除当前i元素
        for($i=0;$i<$len;$i++){
                $res[$i]=$left[$i]*$right[$i];
        }   
        return $res;
}

The above is the detailed content of How to build a product array excluding the current element in php (code attached). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:cnblogs.com. If there is any infringement, please contact admin@php.cn delete