Una forma sencilla y rápida de aprender JAVA, observando y deduciendo cómo se comporta el lenguaje a través de ejemplos prácticos.

Archivo del blog

domingo, 12 de febrero de 2023

Espirales. Graficar Espiral de Arquímedes.

La espiral de Arquímedes es una curva matemática que se genera mediante la rotación de una recta alrededor de un punto fijo.


Código Java (ArquimedesSpiral.java):

package arquimedesspiral;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class ArquimedesSpiral extends JComponent {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        int width = getWidth();
        int height = getHeight();

        g2d.translate(width / 2, height / 2);
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        double t = 0.1;
        double a = 5;

        int x1 = 0;
        int y1 = 0;

        g2d.setColor(Color.BLUE);

        for (int i = 0; i <= 500; i++) {
            int x2 = (int) (a * t * Math.cos(t));
            int y2 = (int) (a * t * Math.sin(t));

            g2d.setStroke(new BasicStroke((float) i / 100));
            g2d.drawLine(x1, y1, x2, y2);

            x1 = x2;
            y1 = y2;

            t += 0.1;
        }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new ArquimedesSpiral());
        frame.setSize(800, 800);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}


Resultado:


Espirales. Graficar Espiral Logarítmica.

La espiral logarítmica es una curva matemática que se genera a partir de la relación logarítmica entre su distancia radial y su ángulo polar.


Código java (LogarithmicSpiral.java):

package logarithmicspiral;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class LogarithmicSpiral extends JComponent {

@Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    int width = getWidth();
    int height = getHeight();

    g2d.translate(width / 2, height / 2);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    double theta = 0.5;
    double a = 1;
    double b = 0.12;

    int x1 = 0;
    int y1 = 0;

    g2d.setColor(Color.BLUE);

    for (int i = 0; i <= 500; i++) {
      double r = a * Math.exp(b * theta);
      int x2 = (int) (r * Math.cos(theta));
      int y2 = (int) (r * Math.sin(theta));

      g2d.setStroke(new BasicStroke((float) i / 100));
      g2d.drawLine(x1, y1, x2, y2);

      x1 = x2;
      y1 = y2;

      theta += 0.1;
    }
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new LogarithmicSpiral());
    frame.setSize(800, 800);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

}


Resultado:



sábado, 28 de enero de 2023

Permutaciones. Algoritmo lexicográfico.

El algoritmo lexicográfico es un algoritmo de generación de permutaciones que genera todas las permutaciones de un conjunto de elementos en orden lexicográfico. Es similar al algoritmo de Heap, pero en lugar de usar una estructura de datos específica, utiliza una técnica de backtracking para generar las permutaciones. Tiene una complejidad temporal de O(n! * n).


Código Java (LexicographicPermutation.java):

import java.util.Arrays;

public class LexicographicPermutation {
    private static int[] elements = {1, 2, 3, 4, 5, 6, 7, 8};
    private static boolean[] used = new boolean[elements.length];

    public static void main(String[] args) {
        lexicographicPermutation(new int[elements.length], 0);
    }

    private static void lexicographicPermutation(int[] permutation, int index) {
        if (index == elements.length) {
            System.out.println(Arrays.toString(permutation));
            return;
        }

        for (int i = 0; i < elements.length; i++) {
            if (!used[i]) {
                used[i] = true;
                permutation[index] = elements[i];
                lexicographicPermutation(permutation, index + 1);
                used[i] = false;
            }
        }
    }
}


Resultado:

[1, 2, 3, 4]
[1, 2, 4, 3]
[1, 3, 2, 4]
[1, 3, 4, 2]
[1, 4, 2, 3]
[1, 4, 3, 2]
[2, 1, 3, 4]
[2, 1, 4, 3]
[2, 3, 1, 4]
[2, 3, 4, 1]
[2, 4, 1, 3]
[2, 4, 3, 1]
[3, 1, 2, 4]
[3, 1, 4, 2]
[3, 2, 1, 4]
[3, 2, 4, 1]
[3, 4, 1, 2]
[3, 4, 2, 1]
[4, 1, 2, 3]
[4, 1, 3, 2]
[4, 2, 1, 3]
[4, 2, 3, 1]
[4, 3, 1, 2]
[4, 3, 2, 1]

Con la tecnología de Blogger.