How to resolve the algorithm Brownian tree step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Brownian tree step by step in the Java programming language

Table of Contents

Problem Statement

Generate and draw a   Brownian Tree.

A Brownian Tree is generated as a result of an initial seed, followed by the interaction of two processes. Because of the lax rules governing the random nature of the particle's placement and motion, no two resulting trees are really expected to be the same, or even necessarily have the same general shape.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Brownian tree step by step in the Java programming language

BrownianTree.java:

This Java program creates a visual representation of a "Brownian Tree." Here's how it works:

  1. Initialization:

    • In the constructor, it sets up a buffered image I for drawing and creates a list of Particle objects.
  2. Painting:

    • The paint method draws the I image onto the window.
  3. Particle Movement:

    • In the run method, the program creates several Particle objects and starts an infinite loop to move them around the screen.
    • Each Particle repeatedly moves in random directions until it encounters the boundary or collides with the tree (represented by black pixels).
  4. Tree Growth:

    • When a particle collides with the tree, it leaves a black pixel and stops moving.
    • This simulates the growth of a fractal-like tree structure on the screen.
  5. Main Class:

    • main method creates a BrownianTree object, sets it visible, and starts the animation in a separate thread.

Particle.java:

This class represents a single particle:

  1. Properties:

    • x and y are the coordinates of the particle.
  2. Movement:

    • move method randomly moves the particle in a 3x3 grid and checks for collisions.
    • It returns true if the particle goes out of bounds or collides with the tree.

BasicBrownianTree.java:

This is an alternative implementation that generates a static image of a Brownian Tree:

  1. Initialization:

    • It creates a buffered image img and sets background and tree color.
    • pixelCount specifies how many pixels to draw.
  2. Generation:

    • In the generate method, it repeatedly generates pixels.
    • For each pixel, it chooses a random position and moves randomly until it encounters the boundary or collides with the tree.
    • It counts the number of pixels lost due to boundary crossings.
  3. Image Output:

    • It writes the final image to a PNG file.

Main Method:

  • main method creates a BasicBrownianTree, generates the image, and saves it to a file.

Source code in the java programming language

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.*;
import javax.swing.JFrame;

public class BrownianTree extends JFrame implements Runnable {

    BufferedImage I;
    private List<Particle> particles;
    static Random rand = new Random();

    public BrownianTree() {
        super("Brownian Tree");
        setBounds(100, 100, 400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        I = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
        I.setRGB(I.getWidth() / 2, I.getHeight() / 2, 0xff00);
        particles = new LinkedList<Particle>();
    }

    @Override
    public void paint(Graphics g) {
        g.drawImage(I, 0, 0, this);
    }

    public void run() {
        for (int i = 0; i < 20000; i++) {
            particles.add(new Particle());
        }
        while (!particles.isEmpty()) {
            for (Iterator<Particle> it = particles.iterator(); it.hasNext();) {
                if (it.next().move()) {
                    it.remove();
                }
            }
            repaint();
        }
    }

    public static void main(String[] args) {
        BrownianTree b = new BrownianTree();
        b.setVisible(true);
        new Thread(b).start();
    }

    private class Particle {

        private int x, y;

        private Particle() {
            x = rand.nextInt(I.getWidth());
            y = rand.nextInt(I.getHeight());
        }

        /* returns true if either out of bounds or collided with tree */
        private boolean move() {
            int dx = rand.nextInt(3) - 1;
            int dy = rand.nextInt(3) - 1;
            if ((x + dx < 0) || (y + dy < 0)
                    || (y + dy >= I.getHeight()) || (x + dx >= I.getWidth())) {
                return true;
            }
            x += dx;
            y += dy;
            if ((I.getRGB(x, y) & 0xff00) == 0xff00) {
                I.setRGB(x - dx, y - dy, 0xff00);
                return true;
            }
            return false;
        }
    }
}


import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class BasicBrownianTree {

    private int pixelsLost;
    private Point p;
    private Point nextP;
    private int pixelCount;
    private int width;
    private int height;
    private int color;
    private BufferedImage img;

    public BasicBrownianTree( int argb, int size, double density ) {
        pixelsLost = 0;
        p = new Point();
        nextP = new Point();
        width = size;
        height = size;
        color = argb;
        pixelCount = (int) ( width * height * density );
        img = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB );
    }

    public void generate() {
        // print text to the console
        System.out.println( "Drawing " + pixelCount + " pixels" );
        int background = img.getRGB( 0, 0 );
        img.setRGB( width / 2, height / 2, color );

        for( int i = 0; i < pixelCount; i++ ) {
            p.x = (int) ( Math.random() * width );
            p.y = (int) ( Math.random() * height );

            while ( true ) {
                int dx = (int) ( Math.random() * 3 ) - 1;
                int dy = (int) ( Math.random() * 3 ) - 1;
                nextP.setLocation( p.x + dx, p.y + dy );
                // handle out-of-bounds
                if ( nextP.x < 0 || nextP.x >= width || nextP.y < 0
                        || nextP.y >= height ) {
                        // increment the number of pixels lost and escape the loop
                    pixelsLost++;
                    break;
                }
                if ( img.getRGB( nextP.x, nextP.y ) != background ) {
                    img.setRGB( p.x, p.y, color );
                    break;
                }
                p.setLocation( nextP );
            }
            // Print a message every 2%
            if ( i % ( pixelCount / 50 ) == 0 ) {
                System.out.println( "Done with " + i + " pixels" );
            }
        }
        // We're done. Let the user know how many pixels were lost
        System.out.println( "Finished. Pixels lost = " + pixelsLost );
    }

    public BufferedImage getImage() {
        return img;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }

    public static void main( String[] args ) {
        // create the new generator
        BasicBrownianTree generator = new BasicBrownianTree( 0x664444ff, 400, 0.4 );
        // generate the image
        generator.generate();
        try {
            // save the image to the file "image.png"
            ImageIO.write( generator.getImage(), "png", new File( "image.png" ) );
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}


  

You may also check:How to resolve the algorithm 24 game step by step in the Perl programming language
You may also check:How to resolve the algorithm Enumerations step by step in the J programming language
You may also check:How to resolve the algorithm Empty string step by step in the Frink programming language
You may also check:How to resolve the algorithm Sort three variables step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Determinant and permanent step by step in the Lambdatalk programming language