Need a little help with a java code challenge

Hey!

So I am trying to complete the java code challenge “Product of everything else”. The goal is to multiply all values of a given array with all the other values in the array except for itself. It says I have 4/5 test cases complete and I have no idea why it won’t completely work and what the last test case could be that it makes the code fail. Please help me out.

[language=java]
import java.util.Arrays;

public class ProductOfTheOthers {

public static void main(String[] args) {

  // Calling your function on an example

  int[] testArray = new int[]{1, 2, 3, 4, 5};

  int[] outputArray = productOfTheOthers(testArray);

  for (int i = 0; i < testArray.length; i++) {

    System.out.println(outputArray[i]);

  }

}



public static int[] productOfTheOthers(int[] array) {

  // Write your code here

  System.out.println(Arrays.toString(array));

     int[] products = new int[array.length];

     for (int c = 0; c < array.length; c++) {

      int sum = 1;

      for (int i = 0; i < array.length; i++) {

       

        if (array[c] != array[i]) {

          sum *= array[i];}

       

      }

           

 products[c] = sum;

     }

  return products;

}

}
[/codebyte]

If you pass almost all the cases then either there’s a slight error in your algorithm/implementation, or you missed considering an edge case.

Try writing out all the edge cases you can think of and test whether they work.

Hello there.
After having a play with your code there’s one edge case which looks like it’s causing it to fail

An array with multiple 0’s in it. e.g. [10, 0, 0, 5]

You’re actually very close to a solution already;

this line needs tweaking
if (array[c] != array[i])

change to :

if (c != i)

I had the same problem. I gave up on it a while ago. There is likely an edge case that your code does not address. The way I look at it though, without specifications for how it should work given various inputs, you are essentially shooting in the dark trying to guess what the test writer was hoping you would do. Some may consider that a good time, but not so much for me. A unit test that doesn’t tell what is failing isn’t much of a unit test.

That’s my cynicism for the week. :innocent:

Ahh of course, I should compare the index and not the elements themselves. Thank you so much!!

1 Like