Advertisement
Guest User

Untitled

a guest
Sep 25th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 23.73 KB | None | 0 0
  1. @Main.java
  2.  
  3. import org.knowm.xchart.*;
  4. import org.knowm.xchart.style.Styler;
  5. import org.knowm.xchart.style.markers.SeriesMarkers;
  6.  
  7. import javax.media.MediaLocator;
  8. import java.awt.*;
  9. import java.io.*;
  10. import java.net.MalformedURLException;
  11. import java.util.ArrayList;
  12. import java.util.Scanner;
  13. import java.util.StringTokenizer;
  14. import java.util.Vector;
  15.  
  16. public class Main {
  17.     FastScanner in;
  18.     PrintWriter out;
  19.  
  20.  
  21.     public void solve() throws IOException {
  22.         short[][] b = new short[16][4];
  23.         double left = -10, right = 10;
  24.         double leftx = -1, rightx = 1, lefty = -1, righty = 1;
  25.         Scanner scanner = new Scanner(System.in);
  26.         System.out.println("Введите номер задачи: ");
  27.         int choice = scanner.nextInt();
  28.         if (choice == 1) {
  29.             Genetic genetic = new Genetic(16, 14, 1357, left, right, -100.223161d); // интервал вкупе с количеством генов задают точность.
  30.             int steps = genetic.solve(1000);
  31.             double[] solutionx = new double[1];
  32.             double[] solutiony = new double[1];
  33.             solutionx[0] = genetic.getSolutionx();
  34.             solutiony[0] = genetic.getSolutiony();
  35.             System.out.println("X = " + solutionx[0]);
  36.             System.out.println("Y = " + solutiony[0]);
  37.             System.out.println("Steps to get solution: " + steps);
  38.             int n = 100;
  39.             double[] x = new double[n];
  40.             double[] y = new double[n];
  41.             for (int i = 0; i < n; i++) {
  42.                 x[i] = left + i * (right - left) / (double) n;
  43.                 y[i] = Function.get(x[i]);
  44.             }
  45.             XYChart chart = QuickChart.getChart("Sample", "X", "Y", "y(x)", x, y);
  46.             new SwingWrapper(chart).displayChart();
  47.             XYSeries solution = chart.addSeries("Solution", solutionx, solutiony);
  48.             solution.setMarker(SeriesMarkers.CIRCLE);
  49.             solution.setMarkerColor(Color.RED);
  50.             ArrayList listY = genetic.getListY();
  51.             ArrayList<Double> m = new ArrayList();
  52.             for (int i = 0; i < genetic.counter; i++) {
  53.                 m.add((double)i + 1);
  54.             }
  55.  
  56.             XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Best chromosomes of each iteration").xAxisTitle("Iteration").yAxisTitle("f(x)").build();
  57.             chart2.getStyler().setChartTitleVisible(true);
  58.             chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
  59.             XYSeries best = chart2.addSeries("Best", m, listY);
  60.             new SwingWrapper(chart2).displayChart();
  61.         } else {
  62.             GeneticXY genetic = new GeneticXY(20, 14, 13337L, leftx, rightx, lefty, righty, -2.598202d);
  63. //            for (int i = 0; i < 1000; i++) {
  64. //                System.out.println(genetic);
  65. //                genetic.iterate();
  66. //            }
  67.             int steps = genetic.solve(10000);
  68.             double solutionx, solutiony, solutionz;
  69.             solutionx = genetic.getSolutionx();
  70.             solutiony = genetic.getSolutiony();
  71.             solutionz = genetic.getSolutionz();
  72.             System.out.println("X = " + solutionx);
  73.             System.out.println("Y = " + solutiony);
  74.             System.out.println("Z = " + solutionz);
  75.             System.out.println("Steps to get solution: " + steps);
  76.             ArrayList listY = genetic.getListY();
  77.             ArrayList<Double> m = new ArrayList();
  78.             for (int i = 0; i < genetic.counter; i++) {
  79.                 m.add((double)i + 1);
  80.             }
  81.  
  82.             XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Best chromosomes of each iteration").xAxisTitle("Iteration").yAxisTitle("f(x)").build();
  83.             chart2.getStyler().setChartTitleVisible(true);
  84.             chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
  85.             XYSeries best = chart2.addSeries("Best", m, listY);
  86.             new SwingWrapper(chart2).displayChart();
  87.         }
  88.  
  89.  
  90.     }
  91.  
  92.     public void run() {
  93.         try {
  94.             in = new FastScanner(new File("Main.in"));
  95.             out = new PrintWriter(new File("Main.out"));
  96.  
  97.             solve();
  98.  
  99.             out.close();
  100.         } catch (IOException e) {
  101.             e.printStackTrace();
  102.         }
  103.     }
  104.  
  105.     class FastScanner {
  106.         BufferedReader br;
  107.         StringTokenizer st;
  108.  
  109.         FastScanner(File f) {
  110.             try {
  111.                 br = new BufferedReader(new FileReader(f));
  112.             } catch (FileNotFoundException e) {
  113.                 e.printStackTrace();
  114.             }
  115.         }
  116.  
  117.         String next() {
  118.             while (st == null || !st.hasMoreTokens()) {
  119.                 try {
  120.                     st = new StringTokenizer(br.readLine());
  121.                 } catch (IOException e) {
  122.                     e.printStackTrace();
  123.                 }
  124.             }
  125.             return st.nextToken();
  126.         }
  127.  
  128.         int nextInt() {
  129.             return Integer.parseInt(next());
  130.         }
  131.     }
  132.  
  133.     public static void main(String[] arg) {
  134.         new Main().run();
  135.     }
  136. }
  137.  
  138. @Analyze.java
  139.  
  140. import org.knowm.xchart.SwingWrapper;
  141. import org.knowm.xchart.XYChart;
  142. import org.knowm.xchart.XYChartBuilder;
  143. import org.knowm.xchart.XYSeries;
  144. import org.knowm.xchart.style.Styler;
  145.  
  146. import java.io.File;
  147. import java.io.IOException;
  148. import java.io.PrintWriter;
  149. import java.util.ArrayList;
  150. import java.util.Random;
  151. import java.util.Scanner;
  152.  
  153. /**
  154.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  155.  * Date: 25.09.2017
  156.  * Time: 13:56
  157.  */
  158. public class Analyze {
  159.     public static void main(String[] args) throws IOException {
  160.         double left = -10, right = 10;
  161.         double leftx = -1, rightx = 1, lefty = -1, righty = 1;
  162.         Scanner scanner = new Scanner(System.in);
  163.         PrintWriter out;
  164.         out = new PrintWriter(new File("Main.out"));
  165.         System.out.println("Введите номер задачи: ");
  166.         int choice = scanner.nextInt();
  167.         if (choice == 1) {
  168.             ArrayList<Integer> iterations = new ArrayList<Integer>();
  169.             Random rnd = new Random(1337);
  170.             for (int i = 0; i < 1000; i++) {
  171.                 Genetic genetic = new Genetic(16, 14, rnd.nextInt(), left, right, -100.223161d); // интервал вкупе с количеством генов задают точность.
  172.                 int steps = genetic.solve(100000);
  173.                 iterations.add(genetic.counter);
  174.             }
  175.             int n = 100;
  176.             double[] x = new double[n];
  177.             double[] y = new double[n];
  178.             for (int i = 0; i < n; i++) {
  179.                 x[i] = left + i * (right - left) / (double) n;
  180.                 y[i] = Function.get(x[i]);
  181.             }
  182.             ArrayList<Integer> m = new ArrayList();
  183.             long sum = 0;
  184.             for (int i = 0; i < iterations.size(); i++) {
  185.                 m.add(i + 1);
  186.                 sum += iterations.get(i);
  187.             }
  188.             double average = sum / 1000.0d;
  189.             for (int i = 0; i < 1000; i++) {
  190.                 out.write(iterations.get(i) + "\n");
  191.             }
  192.             System.out.println("Average: " + average);
  193.             XYChart chart2 = new XYChartBuilder().width(800).height(600).title("Quantity of iterations on each experiment").xAxisTitle("# experiment").yAxisTitle("Iterations").build();
  194.             chart2.getStyler().setChartTitleVisible(true);
  195.             chart2.getStyler().setLegendPosition(Styler.LegendPosition.InsideNW);
  196.             XYSeries best = chart2.addSeries("Best", m, iterations);
  197.             chart2.getStyler().setDefaultSeriesRenderStyle(XYSeries.XYSeriesRenderStyle.Scatter);
  198.             new SwingWrapper(chart2).displayChart();
  199.         } else {
  200.             Random rnd = new Random(1337);
  201.             for (int i = 0; i < 1000; i++) {
  202.                 Genetic genetic = new GeneticXY(20, 14, rnd.nextInt(), leftx, rightx, lefty, righty, -2.598202d); // интервал вкупе с количеством генов задают точность.
  203.                 int steps = genetic.solve(100000);
  204.                 out.write(genetic.counter + "\n");
  205.             }
  206.         }
  207.         out.close();
  208.     }
  209. }
  210.  
  211. @Genetic.java
  212.  
  213. import java.util.*;
  214.  
  215. /**
  216.  * Класс, реализующий генетический алгоритм для нахождения инфимума.
  217.  *
  218.  * @author Dmitri Savelin
  219.  * @version 1.0
  220.  */
  221. public class Genetic {
  222.     int genes, population;
  223.     long seed;
  224.     double leftx, rightx, righty, lefty, offset;
  225.     double v[];
  226.     Random rnd;
  227.     Phenotype[] m;
  228.     int counter = 0;
  229.     double solutionx, solutiony, solutionz;
  230.     double trueSolution, epsilon = 3d;
  231.     ArrayList<Double> listx, listy;
  232.  
  233.     Genetic() {
  234.  
  235.     }
  236.  
  237.     /**
  238.      * Конструктор
  239.      *
  240.      * @param genes      - количество генов в хромосоме
  241.      * @param population - количество популяции (хромосом)
  242.      * @param seed       - сид для создания псевдослучайных наборов генов в хромосомах
  243.      * @param leftx      - левая граница интервала
  244.      * @param rightx     - правая граница интервала
  245.      */
  246.     Genetic(int genes, int population, long seed, double leftx, double rightx) {
  247.         listx = new ArrayList<Double>();
  248.         listy = new ArrayList<Double>();
  249.         this.genes = genes;
  250.         this.population = population;
  251.         this.seed = seed;
  252.         this.leftx = leftx;
  253.         this.rightx = rightx;
  254.         m = new Phenotype[population];
  255.         rnd = new Random(seed);
  256.         for (int i = 0; i < population; i++) {
  257.             short[] ch = new short[genes];
  258.             for (int j = 0; j < genes; j++) {
  259.                 ch[j] = (short) rnd.nextInt(2);
  260.             }
  261.             m[i] = new Phenotype(genes, ch, leftx, rightx);
  262.         }
  263.         trueSolution = Double.NaN;
  264.     }
  265.  
  266.     Genetic(int genes, int population, long seed, double leftx, double rightx, double trueSolution) {
  267.         this(genes, population, seed, leftx, rightx);
  268.         this.trueSolution = trueSolution;
  269.     }
  270.  
  271.     public int solve(int maxSteps) {
  272.         while (trueSolution != Double.NaN && Math.abs(trueSolution - getSolutiony()) > epsilon && counter < maxSteps) {
  273.             iterate();
  274.         }
  275.         if (counter > maxSteps - 1) return -1;
  276.         return counter;
  277.     }
  278.  
  279.     public void makeOffset() {
  280.         for (int i = 0; i < population; i++) {
  281.             m[i].f += 300;
  282.         }
  283.     }
  284.  
  285.     void undoOffset() {
  286.         for (int i = 0; i < population; i++) {
  287.             m[i].f -= offset;
  288.         }
  289.     }
  290.  
  291.     void selection() {
  292.         v = new double[population];
  293.         double sum = 0, tmp = 0;
  294.         for (int i = 0; i < population; i++) {
  295.             sum += m[i].f;
  296.         }
  297.         for (int i = 0; i < population; i++) {
  298.             v[i] = m[i].f * 1000 / sum;
  299.             tmp += v[i];
  300.             v[i] = tmp;
  301.             System.out.println(v[i]);
  302.         }
  303.     }
  304.  
  305.     int roulette() {
  306.         int val = rnd.nextInt(1001);
  307.         int i = 0;
  308.         while (i < population - 1 && val > v[i]) {
  309.             i++;
  310.         }
  311.         System.out.println(val + " " + i);
  312.         return i;
  313.     }
  314.  
  315.     public void crossing() {
  316.         System.out.println();
  317.         System.out.println("Making crossing\n");
  318.         Phenotype[] children = new Phenotype[population];
  319.         selection();
  320.         Stack<Integer> list = new Stack();
  321.         for (int i = 0; i < population; i++) {
  322.             list.push(roulette());
  323.         }
  324.         Collections.shuffle(list, rnd);
  325.         for (int i = 0; i < population / 2; i++) {
  326.             int a = list.pop(), b = list.pop();
  327.             System.out.println("Pairs " + a + " and " + b);
  328.             int delim = rnd.nextInt(genes - 1);  // число разрезов на 1 меньше, чем число элементов
  329.             System.out.println(genes);
  330.             //      System.out.println(m[a].ch.length);
  331.             System.out.println("a = " + a);
  332.             short[] m1 = Arrays.copyOf(m[a].ch, genes);
  333.             short[] m2 = Arrays.copyOf(m[b].ch, genes);
  334.             for (int j = delim + 1; j < genes; j++) {
  335.                 short tmp = m1[j];
  336.                 m1[j] = m2[j];
  337.                 m2[j] = tmp;
  338.             }
  339.             Phenotype first = new Phenotype(genes, m1, leftx, rightx);
  340.             Phenotype second = new Phenotype(genes, m2, leftx, rightx);
  341.             children[i * 2] = first;
  342.             children[i * 2 + 1] = second;
  343.         }
  344.         m = children;
  345.     }
  346.  
  347.     void iterate() {
  348.         counter++;
  349.         System.out.println("\nIteration " + counter + ": \n\n");
  350.         makeOffset();
  351.         crossing();
  352.         mutation();
  353.         System.out.println(this);
  354.         findBestSolution();
  355.     }
  356.  
  357.     void findBestSolution() {
  358.         double maxx = m[0].genotypeX, maxy = m[0].f;
  359.         for (int i = 1; i < population; i++) {
  360.             if (maxy < m[i].f) {
  361.                 maxy = m[i].f;
  362.                 maxx = m[i].genotypeX;
  363.             }
  364.         }
  365.  
  366.         System.out.println("Best solution this step:");
  367.         System.out.println("X = " + maxx + "\nY = " + Function.get(maxx));
  368.         listx.add(maxx);
  369.         listy.add(Function.get(maxx));
  370.  
  371.         if (maxy > solutiony) {
  372.             solutionx = maxx;
  373.             solutiony = maxy;
  374.         }
  375.     }
  376.  
  377.     ArrayList<Double> getListY() {
  378.         return listy;
  379.     }
  380.  
  381.     double getSolutionx() {
  382.         return solutionx;
  383.     }
  384.  
  385.     double getSolutiony() {
  386.         return Function.get(solutionx);
  387.     }
  388.  
  389.     void mutation() {
  390.         if ((counter + 1) % 4 != 0) return;
  391.         for (int i = 0; i < population; i += 10) {
  392.             for (int j = 0; j < 2; j++) {
  393.                 int k = rnd.nextInt(genes);
  394.                 m[i].ch[k] = (short) (1 - m[i].ch[k]);
  395.             }
  396.         }
  397.     }
  398.  
  399.     @Override
  400.     public String toString() {
  401.         StringBuilder sb = new StringBuilder();
  402.         for (int i = 0; i < population; i++) {
  403.             for (int j = 0; j < genes; j++) {
  404.                 sb.append(m[i].ch[j]).append(" ");
  405.             }
  406.             sb.append(m[i].genotypeX).append(" ").append(m[i].f).append(" ").append("\n");
  407.         }
  408.         return sb.toString();
  409.     }
  410.  
  411.     // более строгий оффсет
  412. //    void makeOffset() {
  413. //        System.out.println("Making offset");
  414. //        double min = m[0].f;
  415. //        for (int i = 1; i < population; i++) {
  416. //            if (m[i].f < min) {
  417. //                min = m[i].f;
  418. //            }
  419. //        }
  420. //        if (min < 0) {
  421. //            offset = -min * 1.05d;
  422. //        } else {
  423. //            offset = min * 0.95d;
  424. //        }
  425. //        System.out.println("Offset is " + offset);
  426. //        for (int i = 0; i < population; i++) {
  427. //            m[i].f = m[i].f + offset;
  428. //        }
  429. //    }
  430. }
  431.  
  432. @GenotypeXY.java
  433.  
  434. import java.util.*;
  435.  
  436. /**
  437.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  438.  * Date: 23.09.2017
  439.  * Time: 18:17
  440.  */
  441. public class GeneticXY extends Genetic {
  442.  
  443.     GeneticXY(int genes, int population, long seed, double leftx, double rightx, double lefty, double righty) {
  444.         this.listy = new ArrayList<Double>();
  445.         this.genes = genes;
  446.         this.population = population;
  447.         this.seed = seed;
  448.         this.leftx = leftx;
  449.         this.rightx = rightx;
  450.         this.lefty = lefty;
  451.         this.righty = righty;
  452.         m = new PhenotypeXY[population];
  453.         rnd = new Random(seed);
  454.         for (int i = 0; i < population; i++) {
  455.             short[] ch = new short[genes];
  456.             for (int j = 0; j < genes; j++) {
  457.                 ch[j] = (short) rnd.nextInt(2);
  458.             }
  459.             m[i] = new PhenotypeXY(genes, ch, leftx, rightx, lefty, righty);
  460.         }
  461.         epsilon = 0.02d;
  462.     }
  463.  
  464.     GeneticXY(int genes, int population, long seed, double leftx, double rightx, double lefty, double righty, double trueSolution) {
  465.         this(genes, population, seed, leftx, rightx, lefty, righty);
  466.         this.trueSolution = trueSolution;
  467.     }
  468.  
  469.     @Override
  470.     public int solve(int maxSteps) {
  471.         while (trueSolution != Double.NaN && Math.abs(trueSolution - getSolutionz()) > epsilon && counter < maxSteps) {
  472.             iterate();
  473.         }
  474.         if (counter > maxSteps - 1) return -1;
  475.         return counter;
  476.     }
  477.  
  478.     @Override
  479.     public void makeOffset() {
  480.         for (int i = 0; i < population; i++) {
  481.             m[i].f += 2.62d;
  482.         }
  483.     }
  484.  
  485.     @Override
  486.     double getSolutiony() {
  487.         return solutiony;
  488.     }
  489.  
  490.     double getSolutionz() {
  491.         return FunctionXY.get(solutionx, solutiony);
  492.     }
  493.  
  494.     @Override
  495.     void findBestSolution() {
  496.         double maxx = m[0].genotypeX, maxy = m[0].genotypeY, maxz = m[0].f;
  497.         for (int i = 1; i < population; i++) {
  498.             if (maxz < m[i].f) {
  499.                 maxz = m[i].f;
  500.                 maxx = m[i].genotypeX;
  501.                 maxy = m[i].genotypeY;
  502.             }
  503.         }
  504.  
  505.         System.out.println("Best solution this step:");
  506.         System.out.println("X = " + maxx + "\nZ = " + FunctionXY.get(maxx, maxy));
  507.         listy.add(FunctionXY.get(maxx, maxy));
  508.  
  509.         if (maxz > solutionz) {
  510.             solutionx = maxx;
  511.             solutiony = maxy;
  512.             solutionz = maxz;
  513.         }
  514.     }
  515.  
  516.     @Override
  517.     public void crossing() {
  518.         System.out.println();
  519.         System.out.println("Making crossing\n");
  520.         Phenotype[] children = new Phenotype[population];
  521.         selection();
  522.         Stack<Integer> list = new Stack();
  523.         for (int i = 0; i < population; i++) {
  524.             list.push(roulette());
  525.         }
  526.         Collections.shuffle(list, rnd);
  527.         for (int i = 0; i < population / 2; i++) {
  528.             int a = list.pop(), b = list.pop();
  529.             System.out.println("Pairs " + a + " and " + b);
  530.             int delim = rnd.nextInt(genes - 1);  // число разрезов на 1 меньше, чем число элементов
  531.             System.out.println(genes);
  532.             //      System.out.println(m[a].ch.length);
  533.             System.out.println("a = " + a);
  534.             short[] m1 = Arrays.copyOf(m[a].ch, genes);
  535.             short[] m2 = Arrays.copyOf(m[b].ch, genes);
  536.             for (int j = delim + 1; j < genes; j++) {
  537.                 short tmp = m1[j];
  538.                 m1[j] = m2[j];
  539.                 m2[j] = tmp;
  540.             }
  541.             Phenotype first = new PhenotypeXY(genes, m1, leftx, rightx, lefty, righty);
  542.             Phenotype second = new PhenotypeXY(genes, m2, leftx, rightx, lefty, righty);
  543.             children[i * 2] = first;
  544.             children[i * 2 + 1] = second;
  545.         }
  546.         m = children;
  547.     }
  548.  
  549.     @Override
  550.     public String toString() {
  551.         StringBuilder sb = new StringBuilder();
  552.         for (int i = 0; i < population; i++) {
  553.             for (int j = 0; j < genes; j++) {
  554.                 sb.append(m[i].ch[j]).append(" ");
  555.             }
  556.             sb.append(m[i].genotypeX).append(" ").append(m[i].genotypeY).append(" ").append(m[i].f).append(" ").append("\n");
  557.         }
  558.         return sb.toString();
  559.     }
  560. }
  561.  
  562. @Phenotype.java
  563.  
  564. import java.util.Arrays;
  565.  
  566. /**
  567.  * Класс, реализующий хромосому
  568.  */
  569. class Phenotype {
  570.     short[] ch;
  571.     double genotypeX, genotypeY;
  572.     double f;
  573.  
  574.     /**
  575.      * Конструктор сразу при создании фенотипа переводит двоичный код в код Грея
  576.      *
  577.      * @param genes - количество генов в хромосоме
  578.      * @param ch - массив генов
  579.      * @param left - левая граница интервала
  580.      * @param right - правая граница интервала
  581.      */
  582.     Phenotype(int genes, short[] ch, double left, double right) {
  583.         this.ch = Arrays.copyOf(ch, genes);
  584.         genotypeX = countGenotype(left, right);
  585.         f = countFunction();
  586.     }
  587.  
  588.     Phenotype() {
  589.  
  590.     }
  591.  
  592.     private double countGenotype(double left, double right) {
  593.         ch = GrayTranslator.grayToBinary(ch);
  594.         long value = 0;
  595.         long mul = 1;
  596.         for (int i = 0; i < ch.length; i++) {
  597.             value += ch[ch.length - 1 - i] * mul;
  598.             mul *= 2;
  599.         }
  600.         ch = GrayTranslator.binaryToGray(ch);
  601.         return left + value * (right - left) / Math.pow(2, ch.length);
  602.     }
  603.  
  604.     private double countFunction() {
  605.          return -Function.get(genotypeX); // ф-я приспособленности
  606.     }
  607.  
  608. }
  609.  
  610. @PhenotypeXY.java
  611.  
  612. import java.util.Arrays;
  613.  
  614. /**
  615.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  616.  * Date: 23.09.2017
  617.  * Time: 18:27
  618.  */
  619. class PhenotypeXY extends Phenotype {
  620.     /**
  621.      * Конструктор сразу при создании фенотипа переводит двоичный код в код Грея
  622.      *
  623.      * @param genes - количество генов в хромосоме
  624.      * @param ch    - массив генов
  625.      * @param leftx  - левая граница интервала переменной x
  626.      * @param rightx - правая граница интервала переменной x
  627.      * @param lefty  - левая граница интервала переменной y
  628.      * @param righty - правая граница интервала переменной y
  629.      */
  630.     PhenotypeXY(int genes, short[] ch, double leftx, double rightx, double lefty, double righty) {
  631.         this.ch = Arrays.copyOf(ch, genes);
  632.         genotypeY = countGenotypeY(lefty, righty);
  633.         genotypeX = countGenotypeX(leftx, rightx);
  634.         f = countFunction();
  635.     }
  636.  
  637.     private double countGenotypeY(double lefty, double righty) {
  638.         ch = GrayTranslator.grayToBinary(ch);
  639.         long value = 0;
  640.         long mul = 1;
  641.         for (int i = 0; i < ch.length / 2; i++) {
  642.             value += ch[ch.length - 1 - i] * mul;
  643.             mul *= 2;
  644.         }
  645.         return lefty + value * (righty - lefty) / Math.pow(2, ch.length / 2);
  646.     }
  647.  
  648.     private double countGenotypeX(double leftx, double rightx) {
  649.         long value = 0;
  650.         long mul = 1;
  651.         for (int i = ch.length / 2; i < ch.length; i++) {
  652.             value += ch[ch.length - 1 - i] * mul;
  653.             mul *= 2;
  654.         }
  655.         ch = GrayTranslator.binaryToGray(ch);
  656.         return leftx + value * (rightx - leftx) / Math.pow(2, ch.length / 2);
  657.     }
  658.  
  659.     private double countFunction() {
  660.         return -FunctionXY.get(genotypeX, genotypeY); // ф-я приспособленности
  661.     }
  662. }
  663.  
  664. @Function.java
  665.  
  666. /**
  667.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  668.  * Date: 23.09.2017
  669.  * Time: 19:20
  670.  */
  671. class Function {
  672.     static double get(double x) {
  673.         return (x * x + x) * Math.cos(x);
  674.  
  675.     }
  676. }
  677.  
  678. @FunctionXY.java
  679.  
  680. /**
  681.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  682.  * Date: 23.09.2017
  683.  * Time: 20:22
  684.  */
  685. class FunctionXY {
  686.     static double get(double x, double y) {
  687.         return Math.atan(x + y) * (Math.acos(x) + Math.asin(y));
  688.     }
  689. }
  690.  
  691. @GrayTranslator.java
  692.  
  693. /**
  694.  * Proger: Dmitry Savelin, kr4m, vk.com/savelin
  695.  * Date: 23.09.2017
  696.  * Time: 21:18
  697.  */
  698. class GrayTranslator {
  699.     static short[] binaryToGray(short[] b) {
  700.         short[] g = new short[b.length];
  701.         g[0] = b[0];
  702.         for (int i = 1; i < b.length; i++) {
  703.             g[i] = (short)(b[i - 1] ^ b[i]);
  704.         }
  705.         return g;
  706.     }
  707.  
  708.     static short[] grayToBinary(short[] g) {
  709.         short[] b = new short[g.length];
  710.         short value = g[0];
  711.         b[0] = value;
  712.         for (int i = 1; i < g.length; i++) {
  713.             if (g[i] == 1) {
  714.                 value = (short)(1 - value);
  715.             }
  716.             b[i] = value;
  717.         }
  718.         return b;
  719.     }
  720. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement