zoukankan      html  css  js  c++  java
  • java算法:基于应用ADT例子

    java算法:基于应用ADT例子

    例1:多项式ADT接口

    Java代码 复制代码
    1. class Poly{   
    2.     Poly(int,int)   
    3.     double eval(double)   
    4.     void add(Poly)   
    5.     void mult(Poly)   
    6.     public String toString()   
    7. }  

    例2:多项式客户程序

    Java代码 复制代码
    1. public class Binomial{   
    2.     public static void main(String args[]){   
    3.         int N = 100;   
    4.         double p = 1.1;   
    5.         Poly y = new Poly(1,0);   
    6.         Poly t = new Poly(1,0);   
    7.         t.add(new Poly(1,1));   
    8.         for(int i = 0; i < N; i++){   
    9.             y.mult(t);   
    10.             System.out.println(y + " ");   
    11.         }   
    12.         System.out.println("value: " + y.eval(p));   
    13.     }   
    14. }  

    例3:多项式ADT的数组实现

    Java代码 复制代码
    1. class Poly{   
    2.     private int n;   
    3.     private int[] a;   
    4.     Poly(int c,int N){   
    5.         a = new int[N+1];    
    6.         n = N + 1;    
    7.         a[N] = c;   
    8.         for(int i = 0; i < N; i++){   
    9.             a[i] = 0;   
    10.         }   
    11.     }   
    12.     double eval(double d){   
    13.         double t = 0.0;   
    14.         for(int i = n - 1; i >= 0; i--){   
    15.             t = t * d + (double)a[i];   
    16.         }   
    17.         return t;   
    18.     }   
    19.     void add(Poly p){   
    20.         int[] t = new int[(p.n > n) ? p.n : n];   
    21.         for(int i = 0; i < p.n; i++){   
    22.             t[i] = p.a[i];   
    23.         }   
    24.         for(int j = 0; j < n; j++){   
    25.             t[j] += a[j];   
    26.         }   
    27.         a = t;   
    28.         n = t.length;   
    29.     }   
    30.     void mult(Poly p){   
    31.         int[] t = new int[p.n + n -1];   
    32.         for(int i = 0; i < p.n; i++){   
    33.             for(inti j = 0; j < n; j++){   
    34.                 t[i+j] += p.a[i] * a[j];   
    35.             }   
    36.         }   
    37.         a = t;   
    38.         n = t.length;   
    39.     }   
    40.     public String toString(){   
    41.         String s = "";   
    42.         for(int i = 0; i < n; i++){   
    43.             s += a[i] + " ";   
    44.         }   
    45.         return s;   
    46.     }   
    47. }  

    注意:Horner算法:a4x4 + a3x3 + a2x2 + a1x + a0 = (((a4x + a3)x + a2)x + a1)x + a0

  • 相关阅读:
    终于把老板的项目搞完了---最后一步项目部署
    linux rz/sz 拖动文件上传
    layui之table.render使用(含后台详细代码实现)
    layui upload 后台获取不到值
    Layui upload动态传参,后台接收不到,解决方法
    hibernate 多条件查询,查询部分字段等操作
    IDEA自动生成序列化ID
    MySQL范围查询(日期)
    安全随机数!Java 随机数 Random 与 SecureRandom
    java poi 写excel到指定目录
  • 原文地址:https://www.cnblogs.com/wuyida/p/6301148.html
Copyright © 2011-2022 走看看