• + 0 comments

    java solution

    class Result {

    /*
     * Complete the 'waiter' function below.
     *
     * The function is expected to return an INTEGER_ARRAY.
     * The function accepts following parameters:
     *  1. INTEGER_ARRAY number
     *  2. INTEGER q
     */
     public static boolean isprime(int n ) {
         for (int i = 2 ; i <= n+2 ; i++) {
             if ( i!=n && n%i==0) {
                 return false;
             }
         }
         return true;
     }
    

    public static List waiter(List number, int q) { // Write your code here

           Stack <Integer> sc = new Stack<>();
           Stack <Integer> scB = new Stack<>();
           List<Integer> ans = new ArrayList<>();
           int prime = 1 ;
    
       //for prime  
       for (int i = 1 ; i <= q ; i++ ) {
          prime++;
          while (!isprime(prime)) {
              prime++;
          } 
          //process 
           if (i == 1 ) { 
               for (int k = number.size()-1; k>=0 ; k--) {
                   if (number.get(k) % prime == 0) {
                       scB.push(number.get(k));
                        //System.out.println(scB.peek() +"  " + i+ "scb");
                   } else {
                       sc.push(number.get(k));
                       // System.out.println(sc.peek() +"  " + i+ "sc");
                   }
               }
    
           } else {
                Stack <Integer> scA1 = new Stack<>();
                  while ( !sc.empty()){ 
                    if (sc.peek()% prime ==0) {
                       scB.add(sc.pop());
                       //System.out.println(scB.peek() +"  " + i+ "scb");
                   } else {
                       scA1.add(sc.pop()); 
                           // System.out.println(scA1.peek() + "   " +i + "sca1");
                   }
                }
                sc = scA1;
           }
    
    
          while (!scB.empty()) {
              ans.add(scB.pop());
             // System.out.println(scB.pop() +"    /"+ i + "  scbpr");
    
          }
      }
    
          while (!sc.empty()) {
              ans.add(sc.pop());
          }
       return ans;
    }
    

    }