Tuesday, 16 April 2019

A Product Array Puzzle

Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.

For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].

source: Daily Coding Problem: Problem #2


package sam.numbers;

import java.util.Arrays;

public class ProductArrayPuzzle {
    public static int[] compute(int... array) {
        if(array.length < 2)
            return array;
        
        int multiply = 1;
        for (int i : array) 
            multiply *= i;
        
        for (int i = 0; i < array.length; i++) 
            array[i] = multiply/array[i];
        
        return array;
    }
    
    
    public static int[] computeWithoutDivision(int... array) {
        if(array.length < 2)
            return array;
        
        int[] copy = Arrays.copyOf(array, array.length);
        
        for (int i = 0; i < array.length; i++) {
            int m = 1;
            for (int j = 0; j < copy.length; j++) 
                m *= j == i ? 1 : copy[j];
            
            array[i] = m;
        } 
        
        return array;
    }

}


package sam.numbers;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import org.junit.jupiter.api.Test;

public class MainTest {
    @Test
    public void ProductArrayPuzzleTest() {
        assertArrayEquals(ProductArrayPuzzle.compute(1, 2, 3, 4, 5), new int[]{120, 60, 40, 30, 24});
        assertArrayEquals(ProductArrayPuzzle.compute(3, 2, 1), new int[]{2, 3, 6});
        
        assertArrayEquals(ProductArrayPuzzle.computeWithoutDivision(1, 2, 3, 4, 5), new int[]{120, 60, 40, 30, 24});
        assertArrayEquals(ProductArrayPuzzle.computeWithoutDivision(3, 2, 1), new int[]{2, 3, 6});
    }
}


code highlighted using: hilite.me

No comments:

Post a Comment