Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.util.Stack;
- import java.util.Random;
- public class Calc
- {
- public static void main(String[] args)
- {
- // whether each element in rpn string is a number or operator
- // five possibilities
- final boolean[][] isOp = {{false,false,true,false,true,false,true},
- {false,false,true,false,false,true,true},
- {false,false,false,false,true,true,true},
- {false,false,false,true,false,true,true},
- {false,false,false,true,true,false,true}};
- // possible ops and nums
- final char[] ops = {'+', '-', '*', '/'};
- char[] nums = {'1', '5', '6', '7'};
- Random rand = new Random();
- Stack<Double> stk = new Stack<Double>();
- char[] str = new char[8];
- double result = 0;
- while (result < 20.9 || 21.1 < result) { // allow floating point errors
- // fisher-yates shuffle on nums
- for (int i = 3; i > 0; i--) {
- int j = rand.nextInt(i + 1);
- char tmp = nums[j];
- nums[j] = nums[i];
- nums[i] = tmp;
- }
- int ord = rand.nextInt(5); // select order of ops and nums
- for (int i = 0, nnum = 0; i < 7; i++)
- // can select any operator
- // nums can only be used once (hence shuffling)
- str[i] = isOp[ord][i] ? ops[rand.nextInt(4)] : nums[nnum++];
- // run rpn through stack calculator
- for (int i = 0; i < 7; i++) {
- switch (str[i]) {
- case '+':
- stk.push(stk.pop() + stk.pop());
- break;
- case '-':
- stk.push(- stk.pop() + stk.pop());
- break;
- case '*':
- stk.push(stk.pop() * stk.pop());
- break;
- case '/':
- stk.push(1 / stk.pop() * stk.pop());
- break;
- default:
- stk.push((double)(str[i] - 0x30));
- }
- }
- result = stk.pop();
- }
- System.out.println(result);
- System.out.println(str);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement