陣列中一個元素和其餘部分的相等劃分 - JavaScript
我們需要編寫一個函式,如果我們可以將陣列劃分為一個元素和其餘部分,使得此元素等於排除它自身的其他所有元素的乘積,則返回 true,否則返回 false。
例如:如果陣列為 −
const arr = [1, 56, 2, 4, 7];
則輸出應為 true
因為,56 等於 −
2 * 4 * 7 * 1
示例
程式碼如下 −
const arr = [1, 56, 2, 4, 7]; const isEqualPartition = arr => { const creds = arr.reduce((acc, val) => { let { prod, max } = acc; if(val > max || !max){ prod *= (max || 1); max = val; }else{ prod *= val; } return { prod, max }; }, { prod: 1, max: null }); return creds.max === creds.prod; }; console.log(isEqualPartition(arr));
輸出
控制檯中的輸出如下 −
true
廣告