Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.image.BufferedImage;
- import java.io.File;
- import java.io.IOException;
- import java.util.regex.Pattern;
- import javax.imageio.ImageIO;
- public class Fractal {
- public static int n;
- public static BufferedImage fractal;
- public static Pattern p;
- public static int threadNumber;
- private static int returnedThreads = 0;
- private static long t = System.nanoTime();
- public static void main(String[] args) throws IOException {
- n = Integer.parseInt(args[0]);
- p = Pattern.compile(args[1]);
- threadNumber = Integer.parseInt(args[2]);
- fractal = new BufferedImage(n, n, BufferedImage.TYPE_INT_RGB);
- for (int i = 0; i < threadNumber; i++) {
- Thread thread = new Thread(new FractalThread(n, i));
- thread.start();
- }
- }
- public static synchronized void writeImage() throws IOException {
- returnedThreads++;
- if(returnedThreads >= threadNumber) {
- long ti = System.nanoTime();
- File f = new File("fractal.png");
- ImageIO.write(fractal, "PNG", f);
- System.out.println("Done in " + (System.nanoTime()-t)/1000000000F + " s");
- }
- }
- }
- import java.io.IOException;
- import java.util.regex.Matcher;
- public class FractalThread implements Runnable {
- private int n;
- private int threads = Fractal.threadNumber;
- private int startingPoint;
- public FractalThread(int n, int startingPoint) {
- this.n = n;
- this.startingPoint = startingPoint;
- }
- @Override
- public void run() {
- for (int i = startingPoint; i < n * n; i += threads) {
- String code = getCode(i);
- Matcher m = Fractal.p.matcher(code);
- float percentage;
- int rgb = 0;
- if (m.find()) {
- String match = m.group(1);
- percentage = match.length()/(float)code.length();
- } else {
- percentage = 1;
- rgb += 255 * 65536 + 255 * 256;
- }
- int blue = (int) (255 * percentage);
- rgb += blue;
- Fractal.fractal.setRGB(i % n, i / n, rgb);
- }
- try {
- Fractal.writeImage();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- public String getCode(int pixel) {
- StringBuilder code = new StringBuilder();
- int currentN = n;
- int x = pixel % currentN;
- int y = pixel / currentN;
- while (currentN > 1) {
- if (y >= currentN / 2) {
- if (x >= currentN / 2) {
- code.append("4");
- x -= currentN / 2;
- y -= currentN / 2;
- } else {
- code.append("3");
- y -= currentN / 2;
- }
- } else {
- if (x >= currentN / 2) {
- code.append("1");
- x -= currentN / 2;
- } else {
- code.append("2");
- }
- }
- currentN /= 2;
- }
- return code.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement