domingo, 2 de septiembre de 2018

4. Get a new array from another one by multiplying all the elements except the i element and store the result of each i place


 4. Get a new array from another one by multiplying all the elements except the i element and store the result of each i place

 Tools

-java 8
-CoderPad/Sandbox

Solution

import java.io.*;
import java.util.*;

class Solution {
  public static void main(String[] args)
  {
//Init array
    List <Integer> array = new ArrayList<Integer>();
    array.add(1);
    array.add(2);
    array.add(3);
    array.add(4);
    array.add(5);
    List<Integer> result = new ArrayList<Integer>();
//create an auxiliar to store the result of multiplying all elements of initial array
    int aux = 1;
//Get the result by multiplying all elements of initial array
    for(Integer in: array)
      aux = aux*in;
//Divide the auxiliar by the i element of the initial array and store in result array
    for(Integer in: array )
      result.add(aux / in);
//Print result
    System.out.println(result); // out: [120, 60, 40, 30, 24]
  }
}

No hay comentarios:

Publicar un comentario