Skip to content
Advertisement

The function returns invalid values

Implement the getarrayproduct function, which gets an array of numbers and returns an array of the same size, where numbers[I] is equal to the product of all elements of the array to the right and left of that element.

Notes:

The initial array contains at least 2 elements The array contains only positive numbers The numbers can be repeated Examples:

getArrayProduct([1,5,2]) === [10,2,5]

The first element 10 is the product of all array’s elements except the first element 1 The second element 2 is the product of all array’s elements except the second element 5 The third element 5 is the product of all array’s elements except the third element 2

and

 getArrayProduct([12,20]) === [20,12]

The first element in array 20 is the product of all array’s elements except the first element The second element 12 is the product of all array’s elements except the second element

My code

function getArrayProduct(numbers) {

  let arr = []
  let a = 0;
  let l = numbers.length;

  if (numbers.length == 2) {
    arr = numbers.reverse()
    return arr
  }

  while(true) {
    if (a + 1 !== NaN) {
      if ((a + 1) == numbers.length) {
        arr[a] = numbers[a] * numbers[0]
      } else {
        arr[a] = numbers[a] * numbers[a+1]
      }
    }

    if (a > numbers.length - 2) {
      break;
    }

    a++;
    l--;
  }

  return arr
}

Function ‘getArrayProduct’ should return correct array for:

[4, 5, 2, 19, 8, 80]

Expected:

"[121600,97280,243200,25600,60800,6080]"

Received:

"[20,10,38,152,640,320]"

and getArrayProduct([1,5,2]) === [10,2,5] – (expected) and my result [5,10,2]

Advertisement

Answer

Alternate approach: Eg: [1,5,2] Multiply all the numbers in array at once. you will get ans 1x5x2 = 10

now your output array will be [product/1, product/5, product/2] == [10/1,10/5,10/2] == [10,2,5]

This method will remove the effort of multiplying same numbers again and again, for each index in array.

function getArrayProduct(numbers) {

  let arr = []
  let product = 1, i=0;

for (i=0;i<numbers.length;i++){
    product=product*numbers[i];
}

for(i=0;i<numbers.length;i++)
{ 
    arr[i] = product/numbers[i];
}

return arr;
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement