Advertisement
Guest User

RPN.java

a guest
Nov 9th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.76 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. /*
  4. *   ф
  5. *   Внимание: повторное применение преобразования для польской нотации испортит порядок выполнения.
  6. *   В классе нет проверки на то, является ли функция записанной в обычной нотации.
  7. * */
  8. public class Rpn {
  9.     static Map<String,Double> dictionary;
  10.     static Map<String,Integer> priority;
  11.     String notation;
  12.     String function;
  13.  
  14.  
  15.     public void putInDictonary(double t, String tname){
  16.         dictionary.put(tname,t);
  17.     }
  18.     //Ініціує словник
  19.     static void init_vars(){
  20.         if(dictionary==null && priority==null){
  21.             dictionary=new HashMap<>(15);
  22.             priority=new HashMap<>(15);
  23.             dictionary.put("E",Math.E);
  24.             dictionary.put("Pi",Math.PI);
  25.             for(String s:new String[]{"(",")"})
  26.                 priority.put(s,0);
  27.             for(String s:new String[]{"+","-"})
  28.                 priority.put(s,1);
  29.             for(String s:new String[]{":","*","/","cos","sin","tan","abs","sqrt","log"})
  30.                 priority.put(s,2);
  31.             for(String s:new String[]{"**","^"})
  32.                 priority.put(s,3);
  33.         }
  34.     }
  35.     public Rpn(){
  36.         init_vars();
  37.     }
  38.     public String setNotation(String notation){
  39.         this.notation=notation;
  40.         return notation;
  41.     }
  42.     public double calculate(){
  43.         return calculate(notation);
  44.     }
  45.     static public double calculate(String expr){
  46.         return calculate(expr.split(" "));
  47.     }
  48.     //Рахує значеня формули
  49.     static public double calculate(String[] stack){
  50.  //       for(String s:stack)System.out.println(s);
  51.         double[] numbers=new double[stack.length];
  52.         int point=0;
  53.         for(int i=0;i<stack.length;i++){
  54.             if(stack[i].matches("[0-9]+\\.?[0-9]*"))
  55.                 //stack[i].matches("[0-9]*")){//Double.NaN != Double.parseDouble(stack[i])){//
  56.                 numbers[point++]=Double.parseDouble(stack[i]);
  57.                 //Якщо у стеці є хоча б одна буква, перевірити чи є така константа, або оператор
  58.             else  if(stack[i].matches("[a-zA-Z]+"))
  59.                 if(dictionary.get(stack[i])!=null)
  60.                     numbers[point++]=dictionary.get(stack[i]);
  61.                 else if(stack[i].equalsIgnoreCase("cos"))
  62.                     numbers[point-1]=Math.cos(numbers[point-1]);
  63.                 else if(stack[i].equalsIgnoreCase("sin"))
  64.                     numbers[point-1]=Math.sin(numbers[point-1]);
  65.                 else if(stack[i].equalsIgnoreCase("abs"))
  66.                     numbers[point-1]=Math.abs(numbers[point-1]);
  67.                 else if(stack[i].equalsIgnoreCase("tan"))
  68.                     numbers[point-1]=Math.tan(numbers[point-1]);
  69.                 else if(stack[i].equalsIgnoreCase("sqrt"))
  70.                     numbers[point-1]=Math.sqrt(numbers[point-1]);
  71.                 else if(stack[i].equalsIgnoreCase("log"))
  72.                     numbers[point-1]=Math.log(numbers[point-1]);
  73.                 else ;
  74.                 //Звичайний оператор
  75.             else if(priority.get(stack[i])!=null){
  76.                 if(stack[i].equals("*"))
  77.                     numbers[point-2]=numbers[point-2]*numbers[point-1];
  78.                 else  if(stack[i].equals(":")||stack[i].equals("/") )
  79.                     numbers[point-2]=numbers[point-2]/numbers[point-1];
  80.                 else  if(stack[i].equals("**") || stack[i].equals("^") )
  81.                     numbers[point-2]=Math.pow(numbers[point-2],numbers[point-1]);
  82.                 else  if(stack[i].equals("+"))
  83.                     numbers[point-2]=numbers[point-2]+numbers[point-1];
  84.                 else  if(stack[i].equals("-"))
  85.                     numbers[point-2]=numbers[point-2]-numbers[point-1];
  86.                 else continue;
  87.                 point--;
  88.             }
  89.         }
  90.         return numbers[0]+0;
  91.     }
  92.  
  93.     // Припустимо що вираз розділен пробілами
  94.     public String buildNotation(String expr){
  95.         String new_expr =expr.replace(",",".");
  96.         notation = buildNotation( new_expr.split(" "));
  97.         return notation;
  98.     }
  99.     //Будує з звичайної нотації польску
  100.     public String buildNotation(String[] expr){
  101.         // j-out[] index; k-stack[]index
  102.         int j=0,k=0;
  103.         String out[]=new String[expr.length],stack[]=new String[expr.length];
  104.         for(int i=0;i<expr.length;i++)
  105.             //Число
  106.             if(expr[i].matches("[0-9]+\\.?[0-9]*") && !expr[i].matches("[a-zA-Z]"))
  107.                 out[j++]=expr[i];
  108.                 //Змінна чи константа
  109.             else if(!dictionary.isEmpty()&& dictionary.get(expr[i])!=null)
  110.                 out[j++]=expr[i];
  111.                 //Функція
  112.             else if(expr[i].matches("[a-zA-Z]*"))
  113.                 if(priority.get(expr[i])!=null) stack[k++]=expr[i];
  114.                 else out[j++]=expr[i];
  115.                 //Дужка
  116.             else if(expr[i].contains("("))
  117.                 stack[k++]="(";
  118.                 //Друга дужка
  119.             else if(expr[i].contains(")"))
  120.                 while(k>0)
  121.                     if(stack[k-1].contains("(")){
  122.                         stack[--k]=" ";
  123.                         break;
  124.                     }
  125.                     else out[j++] = stack[--k];
  126.                 //Звичайні оператори
  127.             else if(expr[i].matches("[*:/^+-]")){
  128.                 while(k>0)
  129.                     if(priority.get(stack[k-1]) >= priority.get(expr[i]) )
  130.                         out[j++]=stack[--k];
  131.                     else break;
  132.                 stack[k++]=expr[i];
  133.             }
  134.         //Кінець циклу
  135.         //Перевірка балансу дужок та розгруз стеку
  136.         for(int i=k-1; i>=0;i--)
  137.             if(stack[i].contains("(") || stack[i].contains(")"))return "3rr0r";
  138.             else out[j++]=stack[i];
  139.  
  140.         StringJoiner result=new StringJoiner(" ");
  141.         for(String i:out)if(i!=null)result.add(i);
  142.         return result.toString();
  143.     }
  144.  
  145.     //Будуе графік по заданих параметрах
  146.     public TreeSet<Pair<Double, Double>> function(double a, double b, double h, String variable){
  147.         if(a>b)return null;
  148.         TreeSet<Pair<Double,Double>> f=new TreeSet<>();
  149.         dictionary.put(variable, a);
  150.         int n=(int)((b-a)/h)+1;
  151.         for(double t=a;t<b;t+=h) {
  152.             dictionary.replace(variable, t);
  153.             f.add(new Pair(t,calculate()));
  154.         }
  155.         dictionary.remove(variable,a+h*n);
  156.         return f;
  157.     }
  158. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement