Waiter


Problem Statement :


You are a waiter at a party. There is a pile of numbered plates. Create an empty answers array. At each iteration, i, remove each plate from the top of the stack in order. Determine if the number on the plate is evenly divisible ith the  prime number. If it is, stack it in pile Bi. Otherwise, stack it in stack Ai. Store the values Bi in  from top to bottom in answers. In the next iteration, do the same with the values in stack . Once the required number of iterations is complete, store the remaining values in Ai  in answers , again from top to bottom. Return the answers  array.


Function Description

Complete the waiter function in the editor below.

waiter has the following parameters:

int number[n]: the numbers on the plates
int q: the number of iterations
Returns

int[n]: the numbers on the plates after processing
Input Format

The first line contains two space separated integers, n and q.
The next line contains n space separated integers representing the initial pile of plates, i.e., A.



Solution :



title-img


                            Solution in C :

In C ++ :




#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <climits>
#include <set>
#include <map>
using namespace std;

int m, n;

const int mycount = 10000;
vector<int> prime_results;
vector<int> sieve(int n)
{
    set<int> primes;
    vector<int> vec;

    primes.insert(2);

    for(int i=3; i<=n ; i+=2)
    {
        primes.insert(i);
    }       

    int p=*primes.begin();
    vec.push_back(p);
    primes.erase(p);

    int maxRoot = sqrt(*(primes.rbegin()));

    while(primes.size() > 0)
    {
        if(p > maxRoot)
        {
            while(primes.size() > 0)
            {
                p=*primes.begin();
                vec.push_back(p);
                primes.erase(p);        
            }
            break;
        }

        int i = p*p;  
        int temp = (*(primes.rbegin()));

        while(i<=temp)
        {
            primes.erase(i);
            i += p;
            i += p;
        }

        p=*primes.begin();
        vec.push_back(p);
        primes.erase(p);
    }

    return vec;
}

void prepare() {
	prime_results = sieve(mycount);
}

int a[100005];
vector<int> thearray[mycount];
void process() {
    int i, j, k, q, l;
    
    prepare();
    scanf("%d %d", &n, &q);
    
    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }
    
    for (i = 0; i < n; i++) {
        for (j = 0; j < q; j++) {
            k = prime_results[j];
            if (a[i] % k == 0) {
                thearray[j].push_back(a[i]);
                break;
            }
        }
        
        if (j == q) {
            thearray[j].push_back(a[i]);
        }
    }
    
    for (i = 0; i < q; i++) {
        if ((i & 1) == 0) {
            for (j = 0; j < thearray[i].size(); j++) {
                printf("%d\n", thearray[i][j]);
            }
        } else {
            for (j = thearray[i].size() - 1; j >= 0;j--) {
                printf("%d\n", thearray[i][j]);
            }
        }
    }
    
    if (q & 1) {
        for (j = 0; j < thearray[i].size(); j++) {
            printf("%d\n", thearray[i][j]);
        }
    } else {
        for (j = thearray[i].size() - 1; j >= 0;j--) {
            printf("%d\n", thearray[i][j]);
        }
    }
    
}

int main() {
    process();
    
    return 0;
}









In Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    
    public static void main(String[] args) {
      
        
        Scanner sc = new Scanner(System.in);
        String nq[] = sc.nextLine().split(" ");
        int n = Integer.parseInt(nq[0]);
        int q = Integer.parseInt(nq[1]);
        String nums[] = sc.nextLine().split(" ");
        int pnum = 2;
        int primes[] = new int[q];
        MyStack first = new MyStack();
        MyStack rest = new MyStack();
        MyStack dpst = new MyStack();
        for(int i = 0; i < nums.length; ++i){
            first.push(Integer.parseInt(nums[i]));
        }
        for(int i = 0; i < q; ++i){
            if(first.head == null) break;
            primes[i] = pnum;
            while(first.head != null){
                int number = first.pop();
                if(number%pnum == 0)
                    dpst.push(number);
                else
                    rest.push(number);
            }
            while(dpst.head != null){
                System.out.println(dpst.pop());
            }
            pnum = nextPrimeNumber(pnum, i, primes);
            MyStack temp = rest;
            rest = first;
            first = temp;
        }
        while(first.head != null){
            System.out.println(first.pop());
        }
    }
    static int nextPrimeNumber(int num,int idx,int[] primes){
        if(num == 2) return 3;
        while(true){
            num = num + 2;
            boolean isPrime = true;
            for(int i = 0; i <= idx; ++i){
                if(num%primes[i] == 0){
                    isPrime = false;
                    break;
                }
            }
            if(isPrime) break;
        }
        return num;
    }
}

class MyStack{
    Node head;
    MyStack(){
        head = null;
    }
    void push(int data){
        Node newNode = new Node(data);
        newNode.next = head;
        head = newNode;
    }
    
    int pop(){
        int data = head.data;
        head = head.next;
        return data;
    }
}
class Node{
    int data;
    Node next;
    Node(int d){
        data = d;
        next = null;
    }
}








In C :





#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX 50005
int top=-1;
int pri[MAX],q,b[MAX],stack[MAX];
void push(int sym){
    stack[++top]=sym;
}
int pop(){
    return stack[top--];
}
int isempty(){
    if(top==-1)
        return 1;
    return 0;
}
void prime(){
    
    pri[0]=2;
    int count,c,i=3;
for ( count = 1 ; count < 1250 ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }
      if ( c == i )
      {
         pri[count]=i;
         count++;
      }
      i++;
   }
}
int main() {

     
    prime();
    int n,i,a[MAX];
    scanf("%d %d",&n,&q);
    for(i=0;i<n;i++)
        {
        scanf("%d",&a[i]);
    }
    int k=0;
    for(i=0;i<n;i++)
        {
        if(a[i]%pri[k]==0)
            printf("%d\n",a[i]);
        else
            push(a[i]);
    }
  
    k++;
    int s;
    
    while(k<q)
        {
         int z=0;
         while(!isempty())
             {
              b[z++]=pop();
         }
             for(i=0;i<z;i++)
                 {
                 if(b[i]%pri[k]==0)
                     printf("%d\n",b[i]);
                 else
                     push(b[i]);
             }
        k++;
         }
    int x=0,c[MAX];
    if(k==q)
    {
        while(!isempty())
        {
            c[x++]=pop();
    }
        for(i=x-1;i>=0;i--)
            printf("%d\n",c[i]);
    }
    
    return 0;
}








In Python3 : 





a,b = map(int, input().split(" "))
nums = list(map(int, input().split(" ")))
def prime(x):
    x = x + 1
    primes = []
    for a in range(1, 10000):
        for b in range(2, a):
            if a % b == 0: break
        else:
            primes.append(a)
        if len(primes) == x:
            return primes[1:]

primes = prime(b)
L = []
for i in primes:
    temp_nums = []
    L2 = []
    for j in range(len(nums)):
        num = nums[j]
        if num % i == 0:
            L2 += [num]
        else:
            temp_nums += [num]
    L += L2
    nums = list(reversed(temp_nums))

for i in L:
	print(i)
for i in list(reversed(nums)):
	print(i)
                        








View More Similar Problems

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution →