We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Java 8
The hardest part of the problem is generating the prime numbers. I used Sieve of Atkin algorithm to generate the list of prime numbers and used the max value in the number list. He is my solution.
publicstaticList<Integer>waiter(List<Integer>number,intq){List<Integer>results=newArrayList<>();// Find max value in the numbers listintmax=number.stream().max(Integer::compareTo).orElse(2);List<Integer>primes=sieveOfAtkin(max);Stack<Integer>ai=newStack<>();Stack<Integer>bi=newStack<>();for(intk=0;k<q;++k){if(k<primes.size()){Integerprime=primes.get(k);System.out.println("prime: "+prime);while(!number.isEmpty()){Integervalue=number.remove(number.size()-1);if(value%prime==0)bi.push(value);elseai.push(value);}stackToList(bi,results);number.addAll(ai);ai.clear();}else{// All of the rest of the primes numbers are larger // then any value in the number list. Just need to calculate // the number of value reversals.if((q-k)/2==0)Collections.reverse(number);break;}}Collections.reverse(number);results.addAll(number);returnresults;}privatestaticvoidstackToList(Stack<Integer>stack,List<Integer>list){while(!stack.isEmpty()){list.add(stack.pop());}}/** * Creates a list of Prime numbers. * Based off of Sieve Of Atkin algorithm * * @param limit - top possible prime number * @return List of prime numbers from 2 too limit inclusive. */privatestaticList<Integer>sieveOfAtkin(finalintlimit){List<Integer>primes=newArrayList<>();boolean[]sieve=newboolean[limit+1];// Special case calculationsif(sieve.length>2)sieve[2]=true;if(sieve.length>3)sieve[3]=true;// Caching each case for(intx=1;x*x<=limit;++x){for(inty=1;y*y<=limit;++y){intxx=x*x;intyy=y*y;intn=(4*xx)+yy;if(n<=limit&&(n%12==1||n%12==5))sieve[n]^=true;n=(3*xx)+yy;if(n<=limit&&(n%12==7))sieve[n]^=true;n=(3*xx)-yy;if(x>y&&n<=limit&&n%12==11)sieve[n]^=true;}}// Marking multiples out for(intr=5;r*r<=limit;++r){if(sieve[r]){for(inti=r*r;i<=limit;i+=r*r){sieve[i]=false;}}}for(inti=2;i<=limit;++i){if(sieve[i])primes.add(i);}returnprimes;}
Java 8 The hardest part of the problem is generating the prime numbers. I used Sieve of Atkin algorithm to generate the list of prime numbers and used the max value in the number list. He is my solution.
Here is hackerrank waiter problem solution in Python, java, C++, C and javascript
can anyone help with the understanding of the problem?
I think the largest challenge could be the prime numbers generating.