[英]Find if an element is the product of all the other elements in array
我想創建一個函數,如果元素之一是所有其他元素的乘積(本身不包括在內),則該函數返回 true。
舉個例子:
const isThereAProduct([2, 8, 4, 1]) // output : true
// (Because 8 = 2 x 4 x 1)
到目前為止我有解決方案
function canPartition(array) { let productArray = array.reduce((acc, val) => acc * val) let isThereOne = false for (let i = 0; i < array.length; i++) { if (array[i] == productArray / array[i]) { isThereOne = true return isThereOne } } } console.log(canPartition([1, 2, 3, 4, 24]))
但是如果 array[i] = 0,我的函數不起作用,因為它會將乘積除以自身 (0),當然它會變成 NaN。
所以也許我想補充
if (array[i] == 0 && productArray == 0) {
isThereOne = true
return isThereOne
}
但是如果 array[i] == 0 && productArray !== 0 但我也必須這樣做,但這是不可能的,哈哈。
會感謝那個人的一些幫助:)
您必須為零添加一個特殊情況:
function canPartition(array) {
let productArray = array.reduce((acc, val) => acc * val);
if (productArray === 0) return array.filter(x => x === 0).length > 1;
for (let i = 0; i < array.length; i++) {
if (array[i] == productArray / array[i]) {
return true;
}
}
return false;
}
console.log(canPartition([0, 0, 1, 2, 3, 4, 24]))
這是我的解決方案
console.log(canPartition([1,2,4,8,1]))
function canPartition(arr) {
product = 1
maxPos = Math.max(...arr)
maxNeg = Math.min(...arr)
if ((maxNeg *= -1) > maxPos) {
max = maxNeg
} else {
max = maxPos
}
arr.splice(arr.indexOf(max),1)
for (let i = 0;i<arr.length;i++) {
product *= arr[i]
}
if (product == max) {
ans = true
} else {
ans = false
}
count = 0;
for (let i =0;i<arr.length;i++) {
if (arr[i] === 0) count++
}
if (count == 1) {
ans = false
} else if (count >= 2) {
ans = true
}
return ans
}
只有一種情況您會得到true
,並且是array
包含兩個元素為0
。 所以只需檢查這個用例。
我正在使用箭頭函數https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
使用原生javascript數組的.some方法
some()
方法測試數組中是否至少有一個元素通過了由提供的函數實現的測試。 它返回一個布爾值。
過濾函數創建一個按條件過濾的新數組
filter()
方法創建一個新數組,其中包含通過所提供函數實現的測試的所有元素。
而reduce, reduce的返回值被分配給累加器,其值在整個數組的每次迭代中都會被記住,並最終成為最終的、單一的結果值。
reduce()
方法在數組的每個元素上執行一個 reducer 函數(您提供的),從而產生單個輸出值。
const canPartition = (array) => { // return true if one of return is true return array.some((val, it, self) => { // is current value equal the product of numbers except the current return val == self.filter((f,id) => id!=it ).reduce((a,b) => a*b); }); } console.log(canPartition([1, 2, 3, 4, 24])); console.log(canPartition([0, 1, 0, 3, 4, 24]));
const isThereAProduct = (array) =>
array.some((e,idx,arr) => e === arr.concat().fill(1,idx,idx+1)
.reduce((acc,e) =>
Math.imul(acc,e)) )
我認為這會起作用,但它涉及制作中間數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.