Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- "C:\Program Files\Java\jdk1.8.0_131\bin\java" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\lib\idea_rt.jar=55283:C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.5\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_131\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar;D:\Computer Science Strath\workspace\JavaParser\javaparser\JavaParser\out\production\JavaParser;D:\Computer Science Strath\workspace\JavaParser\javaparser-core-3.6.26.jar" Driver
- Checking class MorpionSolitaire
- [MorpionSolitairePanel panel;, public static void main(String[] args) {
- JFrame f = new MorpionSolitaire();
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.setVisible(true);
- }, public MorpionSolitaire() {
- Container content = getContentPane();
- content.setLayout(new BorderLayout());
- panel = new MorpionSolitairePanel();
- content.add(panel, BorderLayout.CENTER);
- setTitle("MorpionSolitaire");
- pack();
- setLocationRelativeTo(null);
- }]
- public static void main(String[] args)
- Checking class Phone
- [private final String unformattedNumber;, public Phone(String unformattedNumber) {
- this.unformattedNumber = unformattedNumber;
- }, public String getAreaCode() {
- return unformattedNumber.substring(0, 3);
- }, public String getPrefix() {
- return unformattedNumber.substring(3, 6);
- }, public void setNumber(String str) {
- unformattedNumber = str;
- }]
- public String getAreaCode()
- public String getPrefix()
- public void setNumber(String str)
- ****************
- CODE SMELL FOUND >>> Class Phone is a data class
- ****************
- Checking class HuffmanNode
- [// subtrees
- public final HuffmanTree left, right;, public HuffmanNode(HuffmanTree l, HuffmanTree r) {
- super(l.frequency + r.frequency);
- left = l;
- right = r;
- }]
- Checking class Test
- [private double mu, sigma;, private double[] state = new double[2];, private int index = state.length;, Test(double m, double s) {
- mu = m;
- sigma = s;
- }, static double[] meanStdDev(double[] numbers) {
- if (numbers.length == 0)
- return new double[] { 0.0, 0.0 };
- double sx = 0.0, sxx = 0.0;
- long n = 0;
- for (double x : numbers) {
- sx += x;
- sxx += pow(x, 2);
- n++;
- }
- return new double[] { sx / n, pow((n * sxx - pow(sx, 2)), 0.5) / n };
- }, static String replicate(int n, String s) {
- return range(0, n + 1).mapToObj(i -> s).collect(joining());
- }, static void showHistogram01(double[] numbers) {
- final int maxWidth = 50;
- long[] bins = new long[10];
- for (double x : numbers) bins[(int) (x * bins.length)]++;
- double maxFreq = stream(bins).max().getAsLong();
- for (int i = 0; i < bins.length; i++) System.out.printf(" %3.1f: %s%n", i / (double) bins.length, replicate((int) (bins[i] / maxFreq * maxWidth), "*"));
- System.out.println();
- }, @Override
- public double getAsDouble() {
- index++;
- if (index >= state.length) {
- double r = sqrt(-2 * log(random())) * sigma;
- double x = 2 * PI * random();
- state = new double[] { mu + r * sin(x), mu + r * cos(x) };
- index = 0;
- }
- return state[index];
- }, // Easy duplicate
- public double getAsAnotherDouble() {
- index++;
- if (index >= state.length) {
- double r = sqrt(-2 * log(random())) * sigma;
- double x = 2 * PI * random();
- state = new double[] { mu + r * sin(x), mu + r * cos(x) };
- index = 0;
- }
- return state[index];
- }, // Harder Duplicate
- public double getAsYetAnotherDouble() {
- index++;
- if (index >= state.length) {
- double t = sqrt(-2 * log(random())) * sigma;
- double y = PI * 2 * random();
- state = new double[] { mu + t * sin(y), mu + t * cos(y) };
- index = 0;
- }
- return state[index];
- }, public static void main(String[] args) {
- Locale.setDefault(Locale.US);
- double[] data = DoubleStream.generate(new Test(0.0, 0.5)).limit(100_000).toArray();
- double[] res = meanStdDev(data);
- System.out.printf("Mean: %8.6f, SD: %8.6f%n", res[0], res[1]);
- showHistogram01(stream(data).map(a -> max(0.0, min(0.9999, a / 3 + 0.5))).toArray());
- }]
- static double[] meanStdDev(double[] numbers)
- static String replicate(int n, String s)
- static void showHistogram01(double[] numbers)
- public double getAsDouble()
- public double getAsAnotherDouble()
- public double getAsYetAnotherDouble()
- public static void main(String[] args)
- Checking class FloodFill
- [public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor) {
- int width = image.getWidth();
- int height = image.getHeight();
- int target = targetColor.getRGB();
- int replacement = replacementColor.getRGB();
- if (target != replacement) {
- Deque<Point> queue = new LinkedList<Point>();
- do {
- int x = node.x;
- int y = node.y;
- while (x > 0 && image.getRGB(x - 1, y) == target) {
- x--;
- }
- boolean spanUp = false;
- boolean spanDown = false;
- while (x < width && image.getRGB(x, y) == target) {
- image.setRGB(x, y, replacement);
- if (!spanUp && y > 0 && image.getRGB(x, y - 1) == target) {
- queue.add(new Point(x, y - 1));
- spanUp = true;
- } else if (spanUp && y > 0 && image.getRGB(x, y - 1) != target) {
- spanUp = false;
- }
- if (!spanDown && y < height - 1 && image.getRGB(x, y + 1) == target) {
- queue.add(new Point(x, y + 1));
- spanDown = true;
- } else if (spanDown && y < height - 1 && image.getRGB(x, y + 1) != target) {
- spanDown = false;
- }
- x++;
- }
- } while ((node = queue.pollFirst()) != null);
- }
- }]
- public void floodFill(BufferedImage image, Point node, Color targetColor, Color replacementColor)
- Checking class Underling
- [private Long id;, private String firstName;, private String lastName;, private Manager lineManager;, public Long getId() {
- return id;
- }, public void setId(Long id) {
- this.id = id;
- }, public String getFirstName() {
- return firstName;
- }, public void setFirstName(String firstName) {
- this.firstName = firstName;
- }, public String getLastName() {
- return lastName;
- }, public void setLastName(String lastName) {
- this.lastName = lastName;
- }, public void setManager(Manager boss) {
- lineManager = boss;
- }, public Manager getManager() {
- return lineManager;
- }, @Override
- public String toString() {
- return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", manager=" + lineManager + "]";
- }]
- public Long getId()
- public void setId(Long id)
- public String getFirstName()
- public void setFirstName(String firstName)
- public String getLastName()
- public void setLastName(String lastName)
- public void setManager(Manager boss)
- public Manager getManager()
- public String toString()
- Checking class Basket
- [// Basket is envious of item
- public float getTotalPrice(Item i) {
- float price = i.getPrice() + i.getTax();
- if (i.isOnSale())
- price = price - i.getSaleDiscount() * price;
- return price;
- }]
- public float getTotalPrice(Item i)
- Checking class Customer
- [private Phone mobilePhone;, public String getMobilePhoneNumber() {
- return "(" + mobilePhone.getAreaCode() + ") " + mobilePhone.getPrefix() + "-" + mobilePhone.getNumber();
- }]
- public String getMobilePhoneNumber()
- ****************
- CODE SMELL FOUND >>> Class Customer is a data class
- ****************
- Checking class HuffmanLeaf
- [// the character this leaf represents
- public final char value;, public HuffmanLeaf(int freq, char val) {
- super(freq);
- value = val;
- }]
- Checking class CipollasAlgorithm
- [private static final BigInteger BIG = BigInteger.TEN.pow(50).add(BigInteger.valueOf(151));, private static final BigInteger BIG_TWO = BigInteger.valueOf(2);, private static class Point {
- BigInteger x;
- BigInteger y;
- Point(BigInteger x, BigInteger y) {
- this.x = x;
- this.y = y;
- }
- @Override
- public String toString() {
- return String.format("(%s, %s)", this.x, this.y);
- }
- }, private static class Triple {
- BigInteger x;
- BigInteger y;
- boolean b;
- Triple(BigInteger x, BigInteger y, boolean b) {
- this.x = x;
- this.y = y;
- this.b = b;
- }
- @Override
- public String toString() {
- return String.format("(%s, %s, %s)", this.x, this.y, this.b);
- }
- }, private static Triple c(String ns, String ps) {
- BigInteger n = new BigInteger(ns);
- BigInteger p = !ps.isEmpty() ? new BigInteger(ps) : BIG;
- // Legendre symbol, returns 1, 0 or p - 1
- Function<BigInteger, BigInteger> ls = (BigInteger a) -> a.modPow(p.subtract(BigInteger.ONE).divide(BIG_TWO), p);
- // Step 0, validate arguments
- if (!ls.apply(n).equals(BigInteger.ONE)) {
- return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
- }
- // Step 1, find a, omega2
- BigInteger a = BigInteger.ZERO;
- BigInteger omega2;
- while (true) {
- omega2 = a.multiply(a).add(p).subtract(n).mod(p);
- if (ls.apply(omega2).equals(p.subtract(BigInteger.ONE))) {
- break;
- }
- a = a.add(BigInteger.ONE);
- }
- // multiplication in Fp2
- BigInteger finalOmega = omega2;
- BiFunction<Point, Point, Point> mul = (Point aa, Point bb) -> new Point(aa.x.multiply(bb.x).add(aa.y.multiply(bb.y).multiply(finalOmega)).mod(p), aa.x.multiply(bb.y).add(bb.x.multiply(aa.y)).mod(p));
- // Step 2, compute power
- Point r = new Point(BigInteger.ONE, BigInteger.ZERO);
- Point s = new Point(a, BigInteger.ONE);
- BigInteger nn = p.add(BigInteger.ONE).shiftRight(1).mod(p);
- while (nn.compareTo(BigInteger.ZERO) > 0) {
- if (nn.and(BigInteger.ONE).equals(BigInteger.ONE)) {
- r = mul.apply(r, s);
- }
- s = mul.apply(s, s);
- nn = nn.shiftRight(1);
- }
- // Step 3, check x in Fp
- if (!r.y.equals(BigInteger.ZERO)) {
- return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
- }
- // Step 5, check x * x = n
- if (!r.x.multiply(r.x).mod(p).equals(n)) {
- return new Triple(BigInteger.ZERO, BigInteger.ZERO, false);
- }
- // Step 4, solutions
- return new Triple(r.x, p.subtract(r.x), true);
- }, public static void main(String[] args) {
- System.out.println(c("10", "13"));
- System.out.println(c("56", "101"));
- System.out.println(c("8218", "10007"));
- System.out.println(c("8219", "10007"));
- System.out.println(c("331575", "1000003"));
- System.out.println(c("665165880", "1000000007"));
- System.out.println(c("881398088036", "1000000000039"));
- System.out.println(c("34035243914635549601583369544560650254325084643201", ""));
- }]
- private static Triple c(String ns, String ps)
- public static void main(String[] args)
- Checking class Item
- [float price, tax, discount;, boolean onSale;, public float getPrice() {
- return price;
- }, public float getSaleDiscount() {
- return discount;
- }, public float getTax() {
- return tax;
- }, public boolean isOnSale() {
- return onSale;
- }]
- public float getPrice()
- public float getSaleDiscount()
- public float getTax()
- public boolean isOnSale()
- ****************
- CODE SMELL FOUND >>> Class Item is a data class
- ****************
- Checking class Factory
- [BasicStockItem[] hoppers;, public Factory() {
- hoppers = new BasicStockItem[10];
- }, public Factory(int h) {
- hoppers = new BasicStockItem[h];
- }, public void fillHoppers() {
- for (int i = 0; i < hoppers.length; i = i + 3) hoppers[i] = new Chunks(10 * i, 50);
- for (int i = 1; i < hoppers.length; i = i + 3) hoppers[i] = new Chips(5 * i, 40);
- for (int i = 2; i < hoppers.length; i = i + 3) hoppers[i] = new Nuts(7 * i, 70);
- }, public void checkLevels() {
- for (int i = 0; i < hoppers.length; i++) if (hoppers[i].reorder())
- System.out.println("Hopper " + i + " low. Reorder more " + hoppers[i].getDescription());
- }]
- public void fillHoppers()
- public void checkLevels()
- Checking class BarnsleyFern
- [BufferedImage img;, public BarnsleyFern() {
- final int dim = 640;
- setPreferredSize(new Dimension(dim, dim));
- setBackground(Color.white);
- img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
- createFern(dim, dim);
- }, // long method
- void createFern(int w, int h) {
- double x = 0;
- double y = 0;
- for (int i = 0; i < 200_000; i++) {
- double tmpx, tmpy;
- double r = Math.random();
- if (r <= 0.01) {
- tmpx = 0;
- tmpy = 0.16 * y;
- } else if (r <= 0.08) {
- tmpx = 0.2 * x - 0.26 * y;
- tmpy = 0.23 * x + 0.22 * y + 1.6;
- } else if (r <= 0.15) {
- tmpx = -0.15 * x + 0.28 * y;
- tmpy = 0.26 * x + 0.24 * y + 0.44;
- } else {
- tmpx = 0.85 * x + 0.04 * y;
- tmpy = -0.04 * x + 0.85 * y + 1.6;
- }
- x = tmpx;
- y = tmpy;
- img.setRGB((int) Math.round(w / 2 + x * w / 11), (int) Math.round(h - y * h / 11), 0xFF32CD32);
- }
- }, @Override
- public void paintComponent(Graphics gg) {
- super.paintComponent(gg);
- Graphics2D g = (Graphics2D) gg;
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.drawImage(img, 0, 0, null);
- }, public static void main(String[] args) {
- SwingUtilities.invokeLater(() -> {
- JFrame f = new JFrame();
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.setTitle("Barnsley Fern");
- f.setResizable(false);
- f.add(new BarnsleyFern(), BorderLayout.CENTER);
- f.pack();
- f.setLocationRelativeTo(null);
- f.setVisible(true);
- });
- }]
- void createFern(int w, int h)
- public void paintComponent(Graphics gg)
- public static void main(String[] args)
- Checking class Company
- [public static void main(String[] args) {
- Factory nutsChipsandChunks = new Factory(50);
- nutsChipsandChunks.fillHoppers();
- nutsChipsandChunks.checkLevels();
- }]
- public static void main(String[] args)
- Checking class ValuableStockItem
- [protected double value;, public ValuableStockItem() {
- super();
- }, public ValuableStockItem(int s, int r, String d, double v) {
- super(s, r, d);
- value = v;
- }, public double getValue() {
- return value;
- }, public void setValue(double value) {
- this.value = value;
- }]
- public double getValue()
- public void setValue(double value)
- Checking class Account
- []
- Checking class Account
- [protected double balance;, public Account() {
- balance = 0;
- }, public Account(double bal) {
- balance = bal;
- }, public double getBalance() {
- return balance;
- }, public void deposit(double dep) {
- balance = balance + dep;
- }, public boolean withdraw(double amount) {
- if (amount <= balance) {
- balance = balance - amount;
- return true;
- } else
- return false;
- }, public void serviceCharge() {
- balance = balance - 0.50;
- }, public String toString() {
- return "Balance: " + balance;
- }]
- public double getBalance()
- public void deposit(double dep)
- public boolean withdraw(double amount)
- public void serviceCharge()
- public String toString()
- Checking class HuffmanTree
- [// the frequency of this tree
- public final int frequency;, public HuffmanTree(int freq) {
- frequency = freq;
- }, // compares on the frequency
- public int compareTo(HuffmanTree tree) {
- return frequency - tree.frequency;
- }]
- public int compareTo(HuffmanTree tree)
- Checking class Intermediate
- [private Child child;, public Child getChild() {
- return child;
- }, public void intermediateOp() {
- System.out.println("An intermediate operation");
- }]
- public Child getChild()
- public void intermediateOp()
- Checking class BasicStockItem
- [protected String description;, protected int stocklevel;, protected int reorderlevel;, public BasicStockItem() {
- stocklevel = 0;
- reorderlevel = 0;
- }, public BasicStockItem(int s, int r, String d) {
- stocklevel = s;
- reorderlevel = r;
- description = d;
- }, public void setReorderLevel(int r) {
- reorderlevel = r;
- }, public int getReorderLevel() {
- return reorderlevel;
- }, public void setStockLevel(int s) {
- stocklevel = s;
- }, public int getStockLevel() {
- return stocklevel;
- }, public boolean reorder() {
- if (stocklevel < reorderlevel)
- return true;
- else
- return false;
- }, public String getDescription() {
- return description;
- }]
- public void setReorderLevel(int r)
- public int getReorderLevel()
- public void setStockLevel(int s)
- public int getStockLevel()
- public boolean reorder()
- public String getDescription()
- Checking class Client
- [private Parent parent;, public void something() {
- parent.getIntermediate().getChild().something();
- }, public void somethingElse() {
- parent.getIntermediate().getChild().somethingElse();
- }, public void intermediate() {
- parent.getIntermediate().intermediateOp();
- }]
- public void something()
- public void somethingElse()
- public void intermediate()
- Checking class Manager
- [private List<Underling> subordinates;, private Long employeeNo;, private String foreName;, private String surName;, private Manager lineManager;, public Long getEmployeeNo() {
- return employeeNo;
- }, public void setEmployeeNo(Long eNo) {
- this.employeeNo = eNo;
- }, public String getForeName() {
- return foreName;
- }, public void setForeName(String foreName) {
- this.foreName = foreName;
- }, public String getSurNameName() {
- return surName;
- }, public void setSurName(String surNameName) {
- this.surName = surName;
- }, public List<Underling> getSubordinates() {
- return subordinates;
- }, public void setSubordinates(List<Underling> subordinates) {
- this.subordinates = subordinates;
- }, @Override
- public String toString() {
- return "Manager [subordinates=" + subordinates + ", details=" + super.toString() + "]";
- }]
- public Long getEmployeeNo()
- public void setEmployeeNo(Long eNo)
- public String getForeName()
- public void setForeName(String foreName)
- public String getSurNameName()
- public void setSurName(String surNameName)
- public List<Underling> getSubordinates()
- public void setSubordinates(List<Underling> subordinates)
- public String toString()
- Checking class Bresenham
- [public static void main(String[] args) {
- SwingUtilities.invokeLater(Bresenham::run);
- }, private static void run() {
- JFrame f = new JFrame();
- f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
- f.setTitle("Bresenham");
- f.getContentPane().add(new BresenhamPanel());
- f.pack();
- f.setLocationRelativeTo(null);
- f.setVisible(true);
- }]
- public static void main(String[] args)
- private static void run()
- [private final int pixelSize = 10;, BresenhamPanel() {
- setPreferredSize(new Dimension(600, 500));
- setBackground(Color.WHITE);
- }, @Override
- public void paintComponent(Graphics g) {
- super.paintComponent(g);
- int w = (getWidth() - 1) / pixelSize;
- int h = (getHeight() - 1) / pixelSize;
- int maxX = (w - 1) / 2;
- int maxY = (h - 1) / 2;
- int x1 = -maxX, x2 = maxX * -2 / 3, x3 = maxX * 2 / 3, x4 = maxX;
- int y1 = -maxY, y2 = maxY * -2 / 3, y3 = maxY * 2 / 3, y4 = maxY;
- // NNE
- drawLine(g, 0, 0, x3, y1);
- // ENE
- drawLine(g, 0, 0, x4, y2);
- // ESE
- drawLine(g, 0, 0, x4, y3);
- // SSE
- drawLine(g, 0, 0, x3, y4);
- // SSW
- drawLine(g, 0, 0, x2, y4);
- // WSW
- drawLine(g, 0, 0, x1, y3);
- // WNW
- drawLine(g, 0, 0, x1, y2);
- // NNW
- drawLine(g, 0, 0, x2, y1);
- }, private void plot(Graphics g, int x, int y) {
- int w = (getWidth() - 1) / pixelSize;
- int h = (getHeight() - 1) / pixelSize;
- int maxX = (w - 1) / 2;
- int maxY = (h - 1) / 2;
- int borderX = getWidth() - ((2 * maxX + 1) * pixelSize + 1);
- int borderY = getHeight() - ((2 * maxY + 1) * pixelSize + 1);
- int left = (x + maxX) * pixelSize + borderX / 2;
- int top = (y + maxY) * pixelSize + borderY / 2;
- g.setColor(Color.black);
- g.drawOval(left, top, pixelSize, pixelSize);
- }, private void drawLine(Graphics g, int x1, int y1, int x2, int y2) {
- // delta of exact value and rounded value of the dependent variable
- int d = 0;
- int dx = Math.abs(x2 - x1);
- int dy = Math.abs(y2 - y1);
- // slope scaling factors to
- int dx2 = 2 * dx;
- // avoid floating point
- int dy2 = 2 * dy;
- // increment direction
- int ix = x1 < x2 ? 1 : -1;
- int iy = y1 < y2 ? 1 : -1;
- int x = x1;
- int y = y1;
- if (dx >= dy) {
- while (true) {
- plot(g, x, y);
- if (x == x2)
- break;
- x += ix;
- d += dy2;
- if (d > dx) {
- y += iy;
- d -= dx2;
- }
- }
- } else {
- while (true) {
- plot(g, x, y);
- if (y == y2)
- break;
- y += iy;
- d += dx2;
- if (d > dy) {
- x += ix;
- d -= dy2;
- }
- }
- }
- }]
- public void paintComponent(Graphics g)
- private void plot(Graphics g, int x, int y)
- private void drawLine(Graphics g, int x1, int y1, int x2, int y2)
- Checking class AccountManager
- [public AccountDataProvider DataProvider;, public AccountManager(AccountDataProvider dataProvider) {
- DataProvider = dataProvider;
- }, public Account GetAccount(int id) {
- return DataProvider.GetAccount(id);
- }]
- public Account GetAccount(int id)
- Checking class NBodySim
- [private static class Vector3D {
- double x, y, z;
- public Vector3D(double x, double y, double z) {
- this.x = x;
- this.y = y;
- this.z = z;
- }
- public Vector3D plus(Vector3D rhs) {
- return new Vector3D(x + rhs.x, y + rhs.y, z + rhs.z);
- }
- public Vector3D minus(Vector3D rhs) {
- return new Vector3D(x - rhs.x, y - rhs.y, z - rhs.z);
- }
- public Vector3D times(double s) {
- return new Vector3D(s * x, s * y, s * z);
- }
- public double mod() {
- return Math.sqrt(x * x + y * y + z * z);
- }
- }, private static final Vector3D origin = new Vector3D(0, 0, 0);, private static class NBody {
- private double gc;
- private int bodies;
- public final int timeSteps;
- private double[] masses;
- private Vector3D[] positions;
- private Vector3D[] velocities;
- private Vector3D[] accelerations;
- public NBody(String fileName) throws IOException {
- Path path = Paths.get(fileName);
- List<String> lines = Files.readAllLines(path);
- String[] gbt = lines.get(0).split(" ");
- gc = Double.parseDouble(gbt[0]);
- bodies = Integer.parseInt(gbt[1]);
- timeSteps = Integer.parseInt(gbt[2]);
- masses = new double[bodies];
- positions = new Vector3D[bodies];
- Arrays.fill(positions, origin);
- velocities = new Vector3D[bodies];
- Arrays.fill(velocities, origin);
- accelerations = new Vector3D[bodies];
- Arrays.fill(accelerations, origin);
- for (int i = 0; i < bodies; ++i) {
- masses[i] = Double.parseDouble(lines.get(i * 3 + 1));
- positions[i] = decompose(lines.get(i * 3 + 2));
- velocities[i] = decompose(lines.get(i * 3 + 3));
- }
- System.out.printf("Contents of %s\n", fileName);
- for (String line : lines) {
- System.out.println(line);
- }
- System.out.println();
- System.out.print("Body : x y z |");
- System.out.println(" vx vy vz");
- }
- private Vector3D decompose(String line) {
- String[] xyz = line.split(" ");
- double x = Double.parseDouble(xyz[0]);
- double y = Double.parseDouble(xyz[1]);
- double z = Double.parseDouble(xyz[2]);
- return new Vector3D(x, y, z);
- }
- private void resolveCollisions() {
- for (int i = 0; i < bodies; ++i) {
- for (int j = i + 1; j < bodies; ++j) {
- if (positions[i].x == positions[j].x && positions[i].y == positions[j].y && positions[i].z == positions[j].z) {
- Vector3D temp = velocities[i];
- velocities[i] = velocities[j];
- velocities[j] = temp;
- }
- }
- }
- }
- private void computeAccelerations() {
- for (int i = 0; i < bodies; ++i) {
- accelerations[i] = origin;
- for (int j = 0; j < bodies; ++j) {
- if (i != j) {
- double temp = gc * masses[j] / Math.pow((positions[i].minus(positions[j])).mod(), 3);
- accelerations[i] = accelerations[i].plus(positions[j].minus(positions[i]).times(temp));
- }
- }
- }
- }
- private void computeVelocities() {
- for (int i = 0; i < bodies; ++i) {
- velocities[i] = velocities[i].plus(accelerations[i]);
- }
- }
- private void computePositions() {
- for (int i = 0; i < bodies; ++i) {
- positions[i] = positions[i].plus(velocities[i]).plus(accelerations[i].times(0.5));
- }
- }
- public void simulate() {
- computeAccelerations();
- computePositions();
- computeVelocities();
- resolveCollisions();
- }
- public void printResults() {
- String fmt = "Body %d : % 8.6f % 8.6f % 8.6f | % 8.6f % 8.6f % 8.6f\n";
- for (int i = 0; i < bodies; ++i) {
- System.out.printf(fmt, i + 1, positions[i].x, positions[i].y, positions[i].z, velocities[i].x, velocities[i].y, velocities[i].z);
- }
- }
- }, public static void main(String[] args) throws IOException {
- String filename = "nbody.txt";
- NBody nb = new NBody(filename);
- for (int i = 0; i < nb.timeSteps; ++i) {
- System.out.printf("\nCycle %s\n", i + 1);
- nb.simulate();
- nb.printResults();
- }
- }]
- public static void main(String[] args) throws IOException
- Checking class BoxingTheCompass
- [private static String[] points = new String[32];, public static void main(String[] args) {
- buildPoints();
- double heading = 0;
- for (int i = 0; i <= 32; i++) {
- heading = i * 11.25;
- switch(i % 3) {
- case 1:
- heading += 5.62;
- break;
- case 2:
- heading -= 5.62;
- break;
- default:
- }
- System.out.printf("%s\t%18s\t%s°\n", (i % 32) + 1, initialUpper(getPoint(heading)), heading);
- }
- }, private static void buildPoints() {
- String[] cardinal = { "north", "east", "south", "west" };
- String[] pointDesc = { "1", "1 by 2", "1-C", "C by 1", "C", "C by 2", "2-C", "2 by 1" };
- String str1, str2, strC;
- for (int i = 0; i <= 3; i++) {
- str1 = cardinal[i];
- str2 = cardinal[(i + 1) % 4];
- strC = (str1.equals("north") || str1.equals("south")) ? (str1 + str2) : (str2 + str1);
- for (int j = 0; j <= 7; j++) {
- points[i * 8 + j] = pointDesc[j].replace("1", str1).replace("2", str2).replace("C", strC);
- }
- }
- }, private static String initialUpper(String s) {
- return s.substring(0, 1).toUpperCase() + s.substring(1);
- }, private static String getPoint(double degrees) {
- double testD = (degrees / 11.25) + 0.5;
- return points[(int) Math.floor(testD % 32)];
- }]
- public static void main(String[] args)
- private static void buildPoints()
- private static String initialUpper(String s)
- private static String getPoint(double degrees)
- Checking class Nuts
- [public Nuts(int s, int r) {
- super(s, r, "Nuts");
- }]
- Checking class Grid
- [enum Result {
- GOOD, BAD, UGLY
- }, final int EMPTY = 0, POINT = 1, HORI = 2, VERT = 4, DIUP = 8, DIDO = 16, HORI_END = 32, VERT_END = 64, DIUP_END = 128, DIDO_END = 256, CAND = 512, ORIG = 1024, HINT = 2048;, final int[] basePoints = { 120, 72, 72, 975, 513, 513, 975, 72, 72, 120 };, int cellSize, pointSize, halfCell, centerX, centerY, origX, origY;, int minC, minR, maxC, maxR;, int[][] points;, List<Line> lines;, Map<Point, Choice> choices;, List<Choice> candidates;, class Line {
- final Point p1, p2;
- Line(Point p1, Point p2) {
- this.p1 = p1;
- this.p2 = p2;
- }
- }, class Choice {
- int[] dir;
- List<Point> points;
- Choice(List<Point> p, int[] d) {
- points = p;
- dir = d;
- }
- }, Grid(int cs, int ps) {
- cellSize = cs;
- pointSize = ps;
- halfCell = cs / 2;
- points = new int[50][50];
- minC = minR = 0;
- maxC = maxR = 50;
- newGame();
- }, final void newGame() {
- for (int r = minR; r < maxR; r++) for (int c = minC; c < maxC; c++) points[r][c] = EMPTY;
- choices = new HashMap<>();
- candidates = new ArrayList();
- lines = new ArrayList<>();
- minC = minR = 18;
- maxC = maxR = 31;
- // cross
- for (int r = 0; r < 10; r++) for (int c = 0; c < 10; c++) if ((basePoints[r] & (1 << c)) != 0)
- points[20 + r][20 + c] = POINT;
- }, void draw(Graphics2D g, int w, int h) {
- centerX = w / 2;
- centerY = h / 2;
- origX = centerX - halfCell - 24 * cellSize;
- origY = centerY - halfCell - 24 * cellSize;
- // grid
- g.setColor(Color.lightGray);
- int x = (centerX - halfCell) % cellSize;
- int y = (centerY - halfCell) % cellSize;
- for (int i = 0; i <= w / cellSize; i++) g.drawLine(x + i * cellSize, 0, x + i * cellSize, h);
- for (int i = 0; i <= h / cellSize; i++) g.drawLine(0, y + i * cellSize, w, y + i * cellSize);
- // lines
- g.setStroke(new BasicStroke(2));
- for (int i = 0; i < lines.size(); i++) {
- Line line = lines.get(i);
- if (i == lines.size() - 1)
- g.setColor(new Color(0x3399FF));
- else
- g.setColor(Color.orange);
- int x1 = origX + line.p1.x * cellSize;
- int y1 = origY + line.p1.y * cellSize;
- int x2 = origX + line.p2.x * cellSize;
- int y2 = origY + line.p2.y * cellSize;
- g.drawLine(x1, y1, x2, y2);
- }
- // points
- for (int r = minR; r < maxR; r++) for (int c = minC; c < maxC; c++) {
- int p = points[r][c];
- if (p == EMPTY)
- continue;
- if ((p & ORIG) != 0)
- g.setColor(Color.red);
- else if ((p & CAND) != 0)
- g.setColor(Color.green);
- else if ((p & HINT) != 0) {
- g.setColor(Color.lightGray);
- points[r][c] &= ~HINT;
- } else
- g.setColor(Color.darkGray);
- drawPoint(g, c, r);
- }
- }, private void drawPoint(Graphics2D g, int x, int y) {
- x = origX + x * cellSize - (pointSize / 2);
- y = origY + y * cellSize - (pointSize / 2);
- g.fillOval(x, y, pointSize, pointSize);
- }, Result computerMove(int r, int c) {
- checkLines(r, c);
- if (candidates.size() > 0) {
- Choice choice = candidates.get(0);
- addLine(choice.points, choice.dir);
- return Result.GOOD;
- }
- return Result.BAD;
- }, Result playerMove(float x, float y) {
- int r = Math.round((y - origY) / cellSize);
- int c = Math.round((x - origX) / cellSize);
- // see if inside active area
- if (c < minC || c > maxC || r < minR || r > maxR)
- return Result.BAD;
- // only process when mouse click is close enough to grid point
- int diffX = (int) Math.abs(x - (origX + c * cellSize));
- int diffY = (int) Math.abs(y - (origY + r * cellSize));
- if (diffX > cellSize / 5 || diffY > cellSize / 5)
- return Result.BAD;
- // did we have a choice in the previous turn
- if ((points[r][c] & CAND) != 0) {
- Choice choice = choices.get(new Point(c, r));
- addLine(choice.points, choice.dir);
- for (Choice ch : choices.values()) {
- for (Point p : ch.points) points[p.y][p.x] &= ~(CAND | ORIG);
- }
- choices.clear();
- return Result.GOOD;
- }
- if (points[r][c] != EMPTY || choices.size() > 0)
- return Result.BAD;
- checkLines(r, c);
- if (candidates.size() == 1) {
- Choice choice = candidates.get(0);
- addLine(choice.points, choice.dir);
- return Result.GOOD;
- } else if (candidates.size() > 1) {
- // we can make more than one line
- points[r][c] |= ORIG;
- for (Choice ch : candidates) {
- List<Point> cand = ch.points;
- Point p = cand.get(cand.size() - 1);
- if (p.equals(new Point(c, r)))
- p = cand.get(0);
- points[p.y][p.x] |= CAND;
- choices.put(p, ch);
- }
- return Result.UGLY;
- }
- return Result.BAD;
- }, void checkLine(int dir, int end, int r, int c, int rIncr, int cIncr) {
- List<Point> result = new ArrayList<>(5);
- for (int i = -4; i < 1; i++) {
- result.clear();
- for (int j = 0; j < 5; j++) {
- int y = r + rIncr * (i + j);
- int x = c + cIncr * (i + j);
- int p = points[y][x];
- if (p != EMPTY && (p & dir) == 0 || (p & end) != 0 || i + j == 0)
- result.add(new Point(x, y));
- else
- break;
- }
- if (result.size() == 5) {
- candidates.add(new Choice(new ArrayList<>(result), new int[] { dir, end }));
- }
- }
- }, void checkLines(int r, int c) {
- candidates.clear();
- checkLine(HORI, HORI_END, r, c, 0, 1);
- checkLine(VERT, VERT_END, r, c, 1, 0);
- checkLine(DIUP, DIUP_END, r, c, -1, 1);
- checkLine(DIDO, DIDO_END, r, c, 1, 1);
- }, void addLine(List<Point> line, int[] dir) {
- Point p1 = line.get(0);
- Point p2 = line.get(line.size() - 1);
- // mark end points for 5T
- points[p1.y][p1.x] |= dir[1];
- points[p2.y][p2.x] |= dir[1];
- lines.add(new Line(p1, p2));
- for (Point p : line) points[p.y][p.x] |= dir[0];
- // growable active area
- minC = Math.min(p1.x - 1, Math.min(p2.x - 1, minC));
- maxC = Math.max(p1.x + 1, Math.max(p2.x + 1, maxC));
- minR = Math.min(p1.y - 1, Math.min(p2.y - 1, minR));
- maxR = Math.max(p1.y + 1, Math.max(p2.y + 1, maxR));
- }, List<Point> possibleMoves() {
- List<Point> moves = new ArrayList<>();
- for (int r = minR; r < maxR; r++) for (int c = minC; c < maxC; c++) {
- if (points[r][c] == EMPTY) {
- checkLines(r, c);
- if (candidates.size() > 0)
- moves.add(new Point(c, r));
- }
- }
- return moves;
- }, void showHints() {
- for (Point p : possibleMoves()) points[p.y][p.x] |= HINT;
- }]
- final void newGame()
- void draw(Graphics2D g, int w, int h)
- private void drawPoint(Graphics2D g, int x, int y)
- Result computerMove(int r, int c)
- Result playerMove(float x, float y)
- void checkLine(int dir, int end, int r, int c, int rIncr, int cIncr)
- void checkLines(int r, int c)
- void addLine(List<Point> line, int[] dir)
- List<Point> possibleMoves()
- void showHints()
- Checking class Chunks
- [public Chunks(int s, int r) {
- super(s, r, "Chunks");
- }]
- Checking class Parent
- [private Intermediate intermediateContainer;, public Intermediate getIntermediate() {
- return intermediateContainer;
- }]
- public Intermediate getIntermediate()
- ****************
- CODE SMELL FOUND >>> Class Parent is a data class
- ****************
- Checking class Chips
- [public Chips(int s, int r) {
- super(s, r, "Chips");
- }]
- Checking class Child
- [public void something() {
- System.out.println("Some operation");
- }, public void somethingElse() {
- System.out.println("Some other operation");
- }]
- public void something()
- public void somethingElse()
- Checking class Eertree
- [public static void main(String[] args) {
- List<Node> tree = eertree("eertree");
- List<String> result = subPalindromes(tree);
- System.out.println(result);
- }, private static class Node {
- int length;
- Map<Character, Integer> edges = new HashMap<>();
- int suffix;
- public Node(int length) {
- this.length = length;
- }
- public Node(int length, Map<Character, Integer> edges, int suffix) {
- this.length = length;
- this.edges = edges != null ? edges : new HashMap<>();
- this.suffix = suffix;
- }
- }, private static final int EVEN_ROOT = 0;, private static final int ODD_ROOT = 1;, private static List<Node> eertree(String s) {
- List<Node> tree = new ArrayList<>();
- tree.add(new Node(0, null, ODD_ROOT));
- tree.add(new Node(-1, null, ODD_ROOT));
- int suffix = ODD_ROOT;
- int n, k;
- for (int i = 0; i < s.length(); ++i) {
- char c = s.charAt(i);
- for (n = suffix; ; n = tree.get(n).suffix) {
- k = tree.get(n).length;
- int b = i - k - 1;
- if (b >= 0 && s.charAt(b) == c) {
- break;
- }
- }
- if (tree.get(n).edges.containsKey(c)) {
- suffix = tree.get(n).edges.get(c);
- continue;
- }
- suffix = tree.size();
- tree.add(new Node(k + 2));
- tree.get(n).edges.put(c, suffix);
- if (tree.get(suffix).length == 1) {
- tree.get(suffix).suffix = 0;
- continue;
- }
- while (true) {
- n = tree.get(n).suffix;
- int b = i - tree.get(n).length - 1;
- if (b >= 0 && s.charAt(b) == c) {
- break;
- }
- }
- tree.get(suffix).suffix = tree.get(n).edges.get(c);
- }
- return tree;
- }, private static List<String> subPalindromes(List<Node> tree) {
- List<String> s = new ArrayList<>();
- subPalindromes_children(0, "", tree, s);
- for (Map.Entry<Character, Integer> cm : tree.get(1).edges.entrySet()) {
- String ct = String.valueOf(cm.getKey());
- s.add(ct);
- subPalindromes_children(cm.getValue(), ct, tree, s);
- }
- return s;
- }, // nested methods are a pain, even if lambdas make that possible for Java
- private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s) {
- for (Map.Entry<Character, Integer> cm : tree.get(n).edges.entrySet()) {
- Character c = cm.getKey();
- Integer m = cm.getValue();
- String pl = c + p + c;
- s.add(pl);
- subPalindromes_children(m, pl, tree, s);
- }
- }]
- public static void main(String[] args)
- private static List<Node> eertree(String s)
- private static List<String> subPalindromes(List<Node> tree)
- private static void subPalindromes_children(final int n, final String p, final List<Node> tree, List<String> s)
- Checking class SavingsAcc
- [protected double interestRate;, public SavingsAcc() {
- super();
- minBalance = 500;
- interestRate = 0.03;
- }, public SavingsAcc(double initBal, double limit, double rate) {
- super(initBal, limit);
- interestRate = rate;
- }, public void computeInterest() {
- balance = balance + balance * interestRate;
- }, // Refused bequest - no-op
- public void serviceCharge() {
- }, public String toString() {
- return super.toString() + " Interest Rate : " + interestRate;
- }]
- public void computeInterest()
- public void serviceCharge()
- public String toString()
- Checking class BarnsleyFernTwo
- [BufferedImage img;, // temporary fields
- double tmpx, tmpy;, public BarnsleyFernTwo() {
- final int dim = 640;
- setPreferredSize(new Dimension(dim, dim));
- setBackground(Color.white);
- img = new BufferedImage(dim, dim, BufferedImage.TYPE_INT_ARGB);
- createFernWithTemp(dim, dim);
- }, // long method
- void createFernWithTemp(int w, int h) {
- double x = 0;
- double y = 0;
- for (int i = 0; i < 200_000; i++) {
- // double tmpx, tmpy;
- double r = Math.random();
- if (r <= 0.01) {
- tmpx = 0;
- tmpy = 0.16 * y;
- } else if (r <= 0.08) {
- tmpx = 0.2 * x - 0.26 * y;
- tmpy = 0.23 * x + 0.22 * y + 1.6;
- } else if (r <= 0.15) {
- tmpx = -0.15 * x + 0.28 * y;
- tmpy = 0.26 * x + 0.24 * y + 0.44;
- } else {
- tmpx = 0.85 * x + 0.04 * y;
- tmpy = -0.04 * x + 0.85 * y + 1.6;
- }
- x = tmpx;
- y = tmpy;
- img.setRGB((int) Math.round(w / 2 + x * w / 11), (int) Math.round(h - y * h / 11), 0xFF32CD32);
- }
- }, @Override
- public void paintComponent(Graphics gg) {
- super.paintComponent(gg);
- Graphics2D g = (Graphics2D) gg;
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.drawImage(img, 0, 0, null);
- }, public static void main(String[] args) {
- SwingUtilities.invokeLater(() -> {
- JFrame f = new JFrame();
- f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- f.setTitle("Barnsley Fern");
- f.setResizable(false);
- f.add(new BarnsleyFernTwo(), BorderLayout.CENTER);
- f.pack();
- f.setLocationRelativeTo(null);
- f.setVisible(true);
- });
- }]
- void createFernWithTemp(int w, int h)
- public void paintComponent(Graphics gg)
- public static void main(String[] args)
- Checking class AccountDataProvider
- [private Account accountId;, public AccountDataProvider(Account acc) {
- accountId = acc;
- }, public Account GetAccount(int id) {
- return accountId;
- }]
- public Account GetAccount(int id)
- Checking class Munchausen
- [public static void main(String[] args) {
- for (int i = 0; i <= 5000; i++) {
- int val = String.valueOf(i).chars().map(x -> (int) Math.pow(x - 48, x - 48)).sum();
- if (i == val) {
- System.out.println(i + " (munchausen)");
- }
- }
- }]
- public static void main(String[] args)
- Checking class Consumer
- [public AccountManager AccountManager;, public Consumer(AccountManager accountManager) {
- AccountManager = accountManager;
- }, public void Get(int id) {
- Account account = AccountManager.GetAccount(id);
- }]
- public void Get(int id)
- Checking class Luhn
- [public static void main(String[] args) {
- System.out.println(luhnTest("49927398716"));
- System.out.println(luhnTest("49927398717"));
- System.out.println(luhnTest("1234567812345678"));
- System.out.println(luhnTest("1234567812345670"));
- }, public static boolean luhnTest(String number) {
- int s1 = 0, s2 = 0;
- String reverse = new StringBuffer(number).reverse().toString();
- for (int i = 0; i < reverse.length(); i++) {
- int digit = Character.digit(reverse.charAt(i), 10);
- if (i % 2 == 0) {
- // this is for odd digits, they are 1-indexed in the algorithm
- s1 += digit;
- } else {
- // add 2 * digit for 0-4, add 2 * digit - 9 for 5-9
- s2 += 2 * digit;
- if (digit >= 5) {
- s2 -= 9;
- }
- // dead code - can't ever happen as digit is in the range 0-9
- if (digit > 9) {
- System.out.println("Well that should never have happened!");
- }
- }
- }
- return (s1 + s2) % 10 == 0;
- }, public static void imDeadJim() {
- System.out.println("Somebody call me!");
- }]
- public static void main(String[] args)
- public static boolean luhnTest(String number)
- public static void imDeadJim()
- Checking class SeasonalStockItem
- [protected String season;, public SeasonalStockItem() {
- super();
- }, public SeasonalStockItem(int s, int r, String d, String sn) {
- super(s, r, d);
- season = sn;
- }]
- Checking class StockItem
- [public void setReorderLevel(int r);, public int getReorderLevel();, public void setStockLevel(int s);, public int getStockLevel();, public boolean reorder();, public String getDescription();]
- public void setReorderLevel(int r)
- public int getReorderLevel()
- public void setStockLevel(int s)
- public int getStockLevel()
- public boolean reorder()
- public String getDescription()
- Checking class ChqAcc
- [protected double minBalance;, public ChqAcc() {
- super();
- minBalance = 0;
- }, public ChqAcc(double initBal, double limit) {
- super(initBal);
- minBalance = limit;
- }, // Refused bequest
- public boolean withdraw(double amount) {
- if (balance - amount >= minBalance) {
- balance = balance - amount;
- return true;
- } else
- return false;
- }, public void setLimit(double limit) {
- minBalance = limit;
- }, public double getLimit() {
- return minBalance;
- }, public void serviceCharge() {
- if (balance < 2 * minBalance)
- super.serviceCharge();
- }, public String toString() {
- return super.toString() + " Limit : " + minBalance;
- }]
- public boolean withdraw(double amount)
- public void setLimit(double limit)
- public double getLimit()
- public void serviceCharge()
- public String toString()
- Checking class ManOrBoy
- [interface Arg {
- public int run();
- }, // long parameter list
- public static int A(final int k, final Arg x1, final Arg x2, final Arg x3, final Arg x4, final Arg x5) {
- if (k <= 0)
- return x4.run() + x5.run();
- return new Arg() {
- int m = k;
- public int run() {
- m--;
- return A(m, this, x1, x2, x3, x4);
- }
- }.run();
- }, public static Arg C(final int i) {
- return new Arg() {
- public int run() {
- return i;
- }
- };
- }, public static void main(String[] args) {
- System.out.println(A(10, C(1), C(-1), C(-1), C(1), C(0)));
- }]
- public static int A(final int k, final Arg x1, final Arg x2, final Arg x3, final Arg x4, final Arg x5)
- public static Arg C(final int i)
- public static void main(String[] args)
- Checking class HuffmanCode
- [// input is an array of frequencies, indexed by character code
- public static HuffmanTree buildTree(int[] charFreqs) {
- PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>();
- // one for each non-empty character
- for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0)
- trees.offer(new HuffmanLeaf(charFreqs[i], (char) i));
- assert trees.size() > 0;
- // loop until there is only one tree left
- while (trees.size() > 1) {
- // two trees with least frequency
- HuffmanTree a = trees.poll();
- HuffmanTree b = trees.poll();
- // put into new node and re-insert into queue
- trees.offer(new HuffmanNode(a, b));
- }
- return trees.poll();
- }, public static void printCodes(HuffmanTree tree, StringBuffer prefix) {
- assert tree != null;
- if (tree instanceof HuffmanLeaf) {
- HuffmanLeaf leaf = (HuffmanLeaf) tree;
- // print out character, frequency, and code for this leaf (which is just the prefix)
- System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix);
- } else if (tree instanceof HuffmanNode) {
- HuffmanNode node = (HuffmanNode) tree;
- // traverse left
- prefix.append('0');
- printCodes(node.left, prefix);
- prefix.deleteCharAt(prefix.length() - 1);
- // traverse right
- prefix.append('1');
- printCodes(node.right, prefix);
- prefix.deleteCharAt(prefix.length() - 1);
- }
- }, public static void main(String[] args) {
- String test = "this is an example for huffman encoding";
- // we will assume that all our characters will have
- // code less than 256, for simplicity
- int[] charFreqs = new int[256];
- // read each character and record the frequencies
- for (char c : test.toCharArray()) charFreqs[c]++;
- // build tree
- HuffmanTree tree = buildTree(charFreqs);
- // print out results
- System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
- printCodes(tree, new StringBuffer());
- }]
- public static HuffmanTree buildTree(int[] charFreqs)
- public static void printCodes(HuffmanTree tree, StringBuffer prefix)
- public static void main(String[] args)
- Checking class MorpionSolitairePanel
- [enum State {
- START, HUMAN, BOT, OVER
- }, State gameState = State.START;, Grid grid;, String message = "Click to start a new game.";, int playerScore, botScore;, Font scoreFont;, public MorpionSolitairePanel() {
- setPreferredSize(new Dimension(1000, 750));
- setBackground(Color.white);
- setFont(new Font("SansSerif", Font.BOLD, 16));
- scoreFont = new Font("SansSerif", Font.BOLD, 12);
- grid = new Grid(35, 9);
- addMouseListener(new MouseAdapter() {
- @Override
- public void mousePressed(MouseEvent e) {
- switch(gameState) {
- case START:
- gameState = State.HUMAN;
- message = "Your turn";
- playerScore = botScore = 0;
- grid.newGame();
- break;
- case HUMAN:
- if (SwingUtilities.isRightMouseButton(e))
- grid.showHints();
- else {
- Grid.Result res = grid.playerMove(e.getX(), e.getY());
- if (res == Grid.Result.GOOD) {
- playerScore++;
- if (grid.possibleMoves().isEmpty())
- gameState = State.OVER;
- else {
- gameState = State.BOT;
- message = "Computer plays...";
- }
- }
- }
- break;
- }
- repaint();
- }
- });
- start();
- }, public final void start() {
- new Thread(new Runnable() {
- @Override
- public void run() {
- Random rand = new Random();
- while (true) {
- try {
- if (gameState == State.BOT) {
- Thread.sleep(1500L);
- List<Point> moves = grid.possibleMoves();
- Point move = moves.get(rand.nextInt(moves.size()));
- grid.computerMove(move.y, move.x);
- botScore++;
- if (grid.possibleMoves().isEmpty()) {
- gameState = State.OVER;
- } else {
- gameState = State.HUMAN;
- message = "Your turn";
- }
- repaint();
- }
- Thread.sleep(100L);
- } catch (InterruptedException ignored) {
- }
- }
- }
- }).start();
- }, @Override
- public void paintComponent(Graphics gg) {
- super.paintComponent(gg);
- Graphics2D g = (Graphics2D) gg;
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- grid.draw(g, getWidth(), getHeight());
- if (gameState == State.OVER) {
- message = "No more moves available. ";
- if (playerScore > botScore)
- message += "You win. ";
- else if (botScore > playerScore)
- message += "Computer wins. ";
- else
- message += "It's a tie. ";
- message += "Click to start a new game.";
- gameState = State.START;
- }
- g.setColor(Color.white);
- g.fillRect(0, getHeight() - 50, getWidth(), getHeight() - 50);
- g.setColor(Color.lightGray);
- g.setStroke(new BasicStroke(1));
- g.drawLine(0, getHeight() - 50, getWidth(), getHeight() - 50);
- g.setColor(Color.darkGray);
- g.setFont(getFont());
- g.drawString(message, 20, getHeight() - 18);
- g.setFont(scoreFont);
- String s1 = "Player " + String.valueOf(playerScore);
- g.drawString(s1, getWidth() - 180, getHeight() - 20);
- String s2 = "Computer " + String.valueOf(botScore);
- g.drawString(s2, getWidth() - 100, getHeight() - 20);
- }]
- public final void start()
- public void paintComponent(Graphics gg)
- Process finished with exit code 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement