Advertisement
Guest User

Calc.java

a guest
Aug 2nd, 2015
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3. import java.util.Random;
  4.  
  5. public class Calc
  6. {
  7.     public static void main(String[] args)
  8.     {
  9.     // whether each element in rpn string is a number or operator
  10.     // five possibilities
  11.     final boolean[][] isOp = {{false,false,true,false,true,false,true},
  12.                   {false,false,true,false,false,true,true},
  13.                   {false,false,false,false,true,true,true},
  14.                   {false,false,false,true,false,true,true},
  15.                   {false,false,false,true,true,false,true}};
  16.     // possible ops and nums
  17.     final char[] ops = {'+', '-', '*', '/'};
  18.     char[] nums = {'1', '5', '6', '7'};
  19.    
  20.     Random rand = new Random();
  21.     Stack<Double> stk = new Stack<Double>();
  22.     char[] str = new char[8];
  23.     double result = 0;
  24.     while (result < 20.9 || 21.1 < result) { // allow floating point errors
  25.  
  26.         // fisher-yates shuffle on nums
  27.         for (int i = 3; i > 0; i--) {
  28.         int j = rand.nextInt(i + 1);
  29.         char tmp = nums[j];
  30.         nums[j] = nums[i];
  31.         nums[i] = tmp;
  32.         }
  33.  
  34.         int ord = rand.nextInt(5); // select order of ops and nums
  35.         for (int i = 0, nnum = 0; i < 7; i++)
  36.         // can select any operator
  37.         // nums can only be used once (hence shuffling)
  38.         str[i] = isOp[ord][i] ? ops[rand.nextInt(4)] : nums[nnum++];
  39.  
  40.         // run rpn through stack calculator
  41.         for (int i = 0; i < 7; i++) {
  42.         switch (str[i]) {
  43.         case '+':
  44.             stk.push(stk.pop() + stk.pop());
  45.             break;
  46.         case '-':
  47.             stk.push(- stk.pop() + stk.pop());
  48.             break;
  49.         case '*':
  50.             stk.push(stk.pop() * stk.pop());
  51.             break;
  52.         case '/':
  53.             stk.push(1 / stk.pop() * stk.pop());
  54.             break;
  55.         default:
  56.             stk.push((double)(str[i] - 0x30));
  57.         }
  58.         }
  59.         result = stk.pop();
  60.     }
  61.     System.out.println(result);
  62.     System.out.println(str);
  63.     }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement