HappyButter

Software Mansion task

Mar 19th, 2021 (edited)
516
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Arrays;
  3. import java.util.HashMap;
  4.  
  5. public class Main {
  6.  
  7.     public static void main(String[] args) {
  8.         Integer[] A = {2,3,9,2,5,1,3,7,10};
  9.         Integer[] B = {2,1,3,4,3,10,6,6,1,7,10,10,10};
  10.  
  11.         System.out.println(useTheAlgorithm(A, B));
  12.     }
  13.  
  14.     private static ArrayList<Integer> useTheAlgorithm(Integer[] listA, Integer[] listB){
  15.         HashMap<Integer, Integer> listBWithCounters = new HashMap<>();
  16.  
  17.         for(Integer elementB : listB){
  18.             listBWithCounters.compute(elementB, (key, val) -> (val == null) ? 1 : val + 1);
  19.         }
  20.  
  21.         ArrayList<Integer> resultList = new ArrayList<>(Arrays.asList(listA));
  22.  
  23.         for(Integer elementA : listA){
  24.             Integer counter = listBWithCounters.get(elementA);
  25.  
  26.             if(counter != null && isPrime(counter)){
  27.                 resultList.remove(elementA);
  28.             }
  29.         }
  30.  
  31.         return resultList;
  32.     }
  33.  
  34.     private static boolean isPrime(int num){
  35.         if(num <= 3) return num > 1;
  36.         if(num % 2 == 0) return false;
  37.  
  38.         int i = 5;
  39.         while(Math.pow(i, 2) <= num){
  40.             if(num % i == 0) return false;
  41.             i += 2;
  42.         }
  43.         return true;
  44.     }
  45. }
  46.  
Add Comment
Please, Sign In to add comment