binibiningtinamoran

RandomAndStacks

Oct 11th, 2019
217
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Random;
  3. import java.util.Stack;
  4. import java.util.stream.IntStream;
  5.  
  6. public class RandomAndStacks {
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.         Stack <Integer> myStack = new Stack <>();
  11.         Stack<Integer> tempStack = new Stack<>();
  12.  
  13.         int element;
  14.         for (int i = 0; i < 555; i++) {
  15.             element = generateRandomNums(25000, 41000);
  16.             isDivisibleByThreeAndTwo(element, myStack);
  17.         }
  18.  
  19.         // Using traditional for-loop to display contents of myStack
  20.         /*
  21.         for (int i = 0; i < myStack.size(); i++) {
  22.             System.out.println(myStack.pop());
  23.         }
  24.          */
  25.  
  26.         // Using IntStream.range() to display contents of myStack
  27.         /*IntStream.range(0, myStack.size()).forEach(i -> {
  28.             System.out.println(myStack.pop());
  29.         });*/
  30.  
  31.         System.out.println("Sorting the stack of numbers...");
  32.  
  33.  
  34.         while (!myStack.isEmpty()) {
  35.  
  36.             int popped = myStack.pop();
  37.  
  38.             while (!tempStack.isEmpty() && tempStack.peek() > popped) {
  39.                 myStack.push(tempStack.pop());
  40.             }
  41.  
  42.             tempStack.push(popped);
  43.         }
  44.  
  45.         System.out.println(Arrays.toString(tempStack.toArray()));
  46.         System.out.printf("How many random numbers are in the stack? %,d\n", tempStack.size());
  47.  
  48.     }
  49.  
  50.     public static int generateRandomNums(int min, int max) {
  51.         if ((min > max) || (max - min +1) > Integer.MAX_VALUE) {
  52.             throw new IllegalArgumentException();
  53.         }
  54.         return new Random().nextInt(max - min +1) + min;
  55.     }
  56.  
  57.     public static void isDivisibleByThreeAndTwo(int randomNum, Stack<Integer> s) {
  58.         if (randomNum % 3 == 0 && randomNum % 2 == 0) {
  59.             s.push(randomNum);
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment