Array Formation HackerEarth

 

  1. import java.util.*;
  2. import java.util.LinkedList;
  3. import java.util.Queue;
  4.  
  5. class PrimeChecker{
  6. Queue<Integer> q;
  7. Stack<Integer> stack;
  8. Stack<Integer> stack1;
  9. public PrimeChecker(){
  10. q=new LinkedList<Integer>();
  11. stack=new Stack<Integer>();
  12. }
  13. public void isPrime(int num){
  14. boolean b=true;
  15. for(int i=2;i<=num/2;i++)
  16. {
  17. int temp=num%i;
  18. if(temp==0)
  19. {
  20. b=false;
  21. break;
  22. }
  23. }
  24. if(b){
  25. //System.out.println(num + " is a Prime Number");
  26. q.add(num);
  27. }
  28. else{
  29. //System.out.println(num + " is not a Prime Number");
  30. stack.push(num);
  31. }
  32. }
  33. // This is checked so that we can skip
  34. // middle five numbers in below loop
  35. public void toPrint(){
  36. //System.out.println(/*"Queue is: "+*/ q);
  37. //System.out.println(/*"Intermediate Stack is: "+*/stack);
  38. stack1=new Stack<Integer>();
  39. while(!stack.isEmpty()){
  40. stack1.push(stack.pop());
  41. }
  42. //System.out.print(" Final Stack is: "+stack1);*/
  43. int arr1[]=new int[q.size()];
  44. int index=0;
  45. while(!q.isEmpty()){
  46. arr1[index++]=q.remove();
  47. }
  48.  
  49. Object[] arr = stack1.toArray();
  50. //System.out.println("The array is:");
  51.  
  52. for(int i=0;i<index;i++){
  53. System.out.print(arr1[i]+" ");
  54. }
  55. System.out.println();
  56.  
  57. for (int j = 0; j < arr.length; j++){
  58. System.out.print(arr[j]+" ");
  59. }
  60. }
  61. }
  62.  
  63. class HackerEarth3{
  64. public static void main(String arg[]){
  65. Scanner sc=new Scanner(System.in);
  66. int n=sc.nextInt();
  67. int arr[]=new int[n];
  68. for(int i=0;i<n;i++){
  69. arr[i]=sc.nextInt();
  70. }
  71. /*for(int i=0;i<n;i++){
  72. System.out.print(arr[i]+" ");
  73. }*/
  74. PrimeChecker obj=new PrimeChecker();
  75. for(int i=0;i<n;i++){
  76. obj.isPrime(arr[i]);
  77. }
  78. obj.toPrint();
  79. }
  80.  
  81.  
  82. }
Language: Java

Approach:

We will check all the elements of entered array whether they are prime or not.
If they are prime push in a queue or else in the stack.
Take one more stack (stack 1)so as you will get the reverse of elements present in the stack.
Then add all the elements using remove operation in queue and pop operation in the stack into two different arrays.
Later print the arrays.



Thanks for Reading.😇

Comments

Post a Comment

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks