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

sábado, 15 de octubre de 2022

Arrastrar un gráfico con el mouse dentro de jFrame.

Código Java (ArrastrarGrafico.java):

package arrastrargrafico;

import javax.swing.WindowConstants;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseEvent;

public class ArrastrarGrafico extends Canvas implements MouseMotionListener {

    private int xRectangulo = 0;
    private int yRectangulo = 0;
    private final int anchoRectangulo = 64;
    private final int altoRectangulo = 64;
    private int xAnteriorRaton;
    private int yAnteriorRaton;
    private boolean arrastrando = false;

    public static void main(String[] args) {
        JFrame v = new JFrame("Arrastrar Grafico");
        ArrastrarGrafico c = new ArrastrarGrafico();
        v.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        v.getContentPane().add(c);
        v.setVisible(true);
        v.pack();
    }

    public ArrastrarGrafico() {
        addMouseMotionListener(this);
    }

    private boolean estaDentro(MouseEvent e) {
        return (e.getX() > xRectangulo)
                && (e.getX() < (xRectangulo + anchoRectangulo))
                && (e.getY() > yRectangulo)
                && (e.getY() < (yRectangulo + altoRectangulo));
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(512, 512);
    }

    @Override
    public void paint(Graphics g) {
        g.setColor(Color.BLUE);
        g.fillRect(xRectangulo, yRectangulo, anchoRectangulo, altoRectangulo);
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (!arrastrando) {
            if (estaDentro(e)) {
                xAnteriorRaton = e.getX();
                yAnteriorRaton = e.getY();
                arrastrando = true;
            }
        } else {
            xRectangulo = (xRectangulo + e.getX()) - xAnteriorRaton;
            yRectangulo = (yRectangulo + e.getY()) - yAnteriorRaton;
            xAnteriorRaton = e.getX();
            yAnteriorRaton = e.getY();
            repaint();
        }
    }

    @Override
    public void mouseMoved(MouseEvent e) {
        arrastrando = false;
    }

}


Resultado:


miércoles, 12 de octubre de 2022

Conversor a código Braille. Uso de HashMap con matriz.

Braille es un sistema de lectura y escritura táctil pensado para personas ciegas.
Un carácter en Braile se puede representar por una matriz de puntos de tamaño 2x3.
Este algoritmo lo que hace es convertir una frase a código en Braille.


Código1 (CodigoBraille.java):

package codigobraille;

public class CodigoBraille {
    public static void main(String[] args) {
        Braille m = new Braille();
        m.braille();
    }
}


Código2 (Braille.java):

package codigobraille;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
import javax.imageio.ImageIO;

public class Braille {

    HashMap<String, Boolean[][]> tablaCodigoBraille = new HashMap<>();

    public void braille() {
        tablaCodigoBraille = getTablaM();
        System.out.println("Escriba un mensaje a convertir a braille:");
        Scanner input = new Scanner(System.in);
        String mensaje = input.nextLine();

        //tamaño lienzo
        int res_x = 1024;
        int res_y = 1024;

        BufferedImage imagen = new BufferedImage(res_x, res_y, BufferedImage.TYPE_INT_RGB);
        Lienzo.Dibujar((Graphics2D) imagen.getGraphics(), res_x, res_y, mensaje, tablaCodigoBraille);
        try {
            ImageIO.write(imagen, "png", new File("Braille.png"));
        } catch (IOException e) {
        }
    }

    private static HashMap<String, Boolean[][]> getTablaM() {

        //tabla código braille español +- (2x3)
        HashMap<String, Boolean[][]> par = new HashMap<>();
        par.put(" ", new Boolean[][]{
            {false, false},
            {false, false},
            {false, false}});
        par.put("A", new Boolean[][]{
            {true, false},
            {false, false},
            {false, false}});
        par.put("B", new Boolean[][]{
            {true, false},
            {true, false},
            {false, false}});
        par.put("C", new Boolean[][]{
            {true, true},
            {false, false},
            {false, false}});
        par.put("D", new Boolean[][]{
            {true, true},
            {false, true},
            {false, false}});
        par.put("E", new Boolean[][]{
            {true, false},
            {false, true},
            {false, false}});
        par.put("F", new Boolean[][]{
            {true, true},
            {true, false},
            {false, false}});
        par.put("G", new Boolean[][]{
            {true, true},
            {true, true},
            {false, false}});
        par.put("H", new Boolean[][]{
            {true, false},
            {true, true},
            {false, false}});
        par.put("I", new Boolean[][]{
            {false, true},
            {true, false},
            {false, false}});
        par.put("J", new Boolean[][]{
            {false, true},
            {true, true},
            {false, false}});
        par.put("K", new Boolean[][]{
            {true, false},
            {false, false},
            {true, false}});
        par.put("L", new Boolean[][]{
            {true, false},
            {true, false},
            {true, false}});
        par.put("M", new Boolean[][]{
            {true, true},
            {false, false},
            {true, false}});
        par.put("N", new Boolean[][]{
            {true, true},
            {false, true},
            {true, false}});
        par.put("O", new Boolean[][]{
            {true, false},
            {false, true},
            {true, false}});
        par.put("P", new Boolean[][]{
            {true, true},
            {true, false},
            {true, false}});
        par.put("Q", new Boolean[][]{
            {true, true},
            {true, true},
            {true, false}});
        par.put("R", new Boolean[][]{
            {true, false},
            {true, true},
            {true, false}});
        par.put("S", new Boolean[][]{
            {false, true},
            {true, false},
            {true, false}});
        par.put("T", new Boolean[][]{
            {false, true},
            {true, true},
            {true, false}});
        par.put("U", new Boolean[][]{
            {true, false},
            {false, false},
            {true, true}});
        par.put("V", new Boolean[][]{
            {true, false},
            {true, false},
            {true, true}});
        par.put("W", new Boolean[][]{
            {false, true},
            {true, true},
            {false, true}});
        par.put("X", new Boolean[][]{
            {true, true},
            {false, false},
            {true, true}});
        par.put("Y", new Boolean[][]{
            {true, true},
            {false, true},
            {true, true}});
        par.put("Z", new Boolean[][]{
            {true, false},
            {false, true},
            {true, true}});
        par.put("&", new Boolean[][]{
            {true, true},
            {true, false},
            {true, true}});
        par.put(".", new Boolean[][]{
            {false, false},
            {false, false},
            {true, false}});
        par.put(",", new Boolean[][]{
            {false, false},
            {true, false},
            {false, false}});
        par.put("?", new Boolean[][]{
            {false, false},
            {true, false},
            {false, true}});
        par.put(":", new Boolean[][]{
            {false, false},
            {true, true},
            {false, false}});
        par.put(";", new Boolean[][]{
            {false, false},
            {true, false},
            {true, false}});
        par.put("!", new Boolean[][]{
            {false, false},
            {true, true},
            {true, false}});
        par.put("\"", new Boolean[][]{
            {false, false},
            {true, false},
            {true, true}});
        par.put("(", new Boolean[][]{
            {true, false},
            {true, false},
            {false, true}});
        par.put(")", new Boolean[][]{
            {false, true},
            {false, true},
            {true, false}});
        par.put("-", new Boolean[][]{
            {false, false},
            {false, false},
            {true, true}});
        par.put("*", new Boolean[][]{
            {false, false},
            {false, true},
            {true, false}});
        return par;
    }
}


Código3 (Lienzo.java):

package codigobraille;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.HashMap;

class Lienzo {

    static void Dibujar(Graphics2D g, int x, int y, String msg, HashMap<String, Boolean[][]> map) {

        //tamaño bloque
        int tCuadroX = 16;
        int tCuadroY = 16;
        int t = 10; //tamaño punto

        Boolean tmp[][] = new Boolean[3][2];

        Graphics2D g2 = (Graphics2D) g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        //fondo blanco
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, x, y);

        //dibujar escritura Braille
        g.setColor(Color.black);
        int horizontal = 1, vertical = 3, limit = 0;
        for (int k = 0; k < msg.length(); k++) {
            //dibujar el caracter en braile
            tmp = map.get("" + msg.toUpperCase().charAt(k));
            for (int i = 0; i < 2; i++) {
                for (int j = 0; j < 3; j++) {
                    if (tmp[j][i]) {
                        g.fillOval(tCuadroX * (i + horizontal), tCuadroY * (j + vertical), t, t);
                    }
                }
            }            
            //ha llegado al limite de linea?
            if (limit++ >= 21) {
                horizontal = 1;
                vertical += 6;
                limit = 0;
            } else {
                horizontal += 3;
            }
        }
    }

}


Resultado:

run:
Escriba un mensaje a convertir a braille:
En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no hace mucho tiempo que vivia un hidalgo de los de lanza en astillero, adarga antigua, rocin flaco y galgo corredor. (DON QUIJOTE DE LA MANCHA)
BUILD SUCCESSFUL (total time: 3 seconds)


sábado, 8 de octubre de 2022

Emitir notas musicales en formato sintetizado (midi).

Código (PruebaSonidoMidi.java):

package pruebasonidomidi;

import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Synthesizer;

public class PruebaSonidoMidi {

    public static void main(String[] args) {

        try {
            Synthesizer synth = MidiSystem.getSynthesizer();
            synth.open();
            MidiChannel[] channels = synth.getChannels();
            for (int i = 5; i < 100; i++) {
                channels[0].noteOn(i, 50);
                Thread.sleep(200);
            }
            synth.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


domingo, 2 de octubre de 2022

Conversor a código Morse. Uso de HashMap.

Este algoritmo lo que hace es convertir una frase a código morse. Para ello hace uso de HashMap (un mapa de estructura de datos) para acceder a una "tabla" de códigos morse.
Una de las ventajas de uso de HashMap es que ofrece un acceso a datos más rápido que usando un arreglo.


Código 1 (CodigoMorse2.java):

package codigomorse2;

public class CodigoMorse2 {
    public static void main(String[] args) {
        Morse m = new Morse();
        m.morse();
    }
}


Código 2 (Morse.java):

package codigomorse2;

import java.util.HashMap;
import java.util.Scanner;

public class Morse {

    HashMap<String, String> tablaCodigoMorse = new HashMap<>();

    public void morse() {

        tablaCodigoMorse = getTabla();

        //añadir nuevos códigos morse a la tabla
        tablaCodigoMorse.put(" ", " ");
        tablaCodigoMorse.put(".", ".-.-.-");
        
        System.out.println("Escriba un mensaje a convertir:");
        Scanner input = new Scanner(System.in);
        String mensaje = input.nextLine();
        String strMorse = conversorStrToMorse(mensaje);

        //resultado
        System.out.println("\nEn morse:\n" + strMorse);

    }

    private String conversorStrToMorse(String frase) {
        String arrTmp[] = frase.split("");
        String morse = "";
        for (String arrTmp1 : arrTmp) {
            morse += tablaCodigoMorse.get(arrTmp1.toUpperCase()) + " ";
        }
        return morse;
    }

    private static HashMap<String, String> getTabla() {
        //tabla código morse internacional
        HashMap<String, String> par = new HashMap<>();
        par.put("A", ".-");
        par.put("B", "-...");
        par.put("C", "-.-.");
        par.put("D", "-..");
        par.put("E", ".");
        par.put("F", "..-.");
        par.put("G", "--.");
        par.put("H", "....");
        par.put("I", "..");
        par.put("J", ".---");
        par.put("K", "-.-");
        par.put("L", ".-..");
        par.put("M", "--");
        par.put("N", "-.");
        par.put("O", "---");
        par.put("P", ".--.");
        par.put("Q", "--.-");
        par.put("R", ".-.");
        par.put("S", "...");
        par.put("T", "-");
        par.put("U", "..-");
        par.put("V", "...-");
        par.put("W", ".--");
        par.put("X", "-..-");
        par.put("Y", "-.--");
        par.put("Z", "--..");
        par.put("0", "-----");
        par.put("1", ".----");
        par.put("2", "..---");
        par.put("3", "...--");
        par.put("4", "....-");
        par.put("5", ".....");
        par.put("6", "-....");
        par.put("7", "--...");
        par.put("8", "---..");
        par.put("9", "----.");
        return par;
    }

}


Resultado:

run:
Escriba un mensaje a convertir:
Esto es una prueba de codigo morse.

En morse:
. ... - ---   . ...   ..- -. .-   .--. .-. ..- . -... .-   -.. .   -.-. --- -.. .. --. ---   -- --- .-. ... . .-.-.-
BUILD SUCCESSFUL (total time: 15 seconds)


domingo, 25 de septiembre de 2022

Almacenar información alfanumérica en matriz gráfica. Tipo código Qr.

Código 1 (CodigoQR.java):

package codigoqr;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import javax.imageio.ImageIO;

public class CodigoQR {

    public static void main(String[] args) {

        //QR Bin
        String xyn = " abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789!#$%&'()*+,-./:;<=>?@[]^_`{|}~";
        List<String> miLista = new ArrayList<>(Arrays.asList(xyn.split("")));
        String binaryString;
        String strCodigo;
        int pos;

        //input código de 8 caracteres        
        System.out.println("Introduce código (8 caracteres mínimo): ");
        Scanner input = new Scanner(System.in);
        strCodigo = input.nextLine();
        if (strCodigo.length() < 8) {
            strCodigo = "        " + strCodigo;
        } else if (strCodigo.length() > 8) {
            System.out.println("Sólo se registrarán los 8 primeros caracteres.");
        }

        //limitar a 8 carácteres máximo.
        strCodigo = strCodigo.substring(0, 8);
        System.out.println("Código registrado <" + strCodigo + ">");

        //generar código QR *** se puede eliminar Lista y Arrays?
        Boolean map[][] = new Boolean[8][8];
        for (int i = 0; i < map.length; i++) {
            pos = miLista.indexOf("" + strCodigo.charAt(i));

            //pasar a formato "binario"
            binaryString = "00000000" + Integer.toString(pos, 2);

            //pasar a formato 00000ABC
            binaryString = binaryString.substring(binaryString.length() - 8);

            //pasar a matriz boleana
            for (int j = 0; j < map.length; j++) {
                map[i][j] = binaryString.charAt(j) != '0';
            }
        }

        //dibujar código pre-QR (.png)
        int res_x = 256;
        int res_y = 256;
        BufferedImage imagen = new BufferedImage(res_x, res_y, BufferedImage.TYPE_INT_RGB);
        Lienzo.Dibujar((Graphics2D) imagen.getGraphics(), res_x, res_y, map);
        try {
            ImageIO.write(imagen, "png", new File("CodigoQR.png"));
        } catch (IOException e) {
        }
        
    }
}


Código 2 (Lienzo.java):

package codigoqr;

import java.awt.Color;
import java.awt.Graphics2D;

class Lienzo {

    static void Dibujar(Graphics2D g, int x, int y, Boolean[][] map) {

        //tamaño bloque
        int tCuadroX = x / 8;

        //fondo blanco
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, x, y);

        //dibujar bloques muro
        g.setColor(Color.black);
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                if (map[j][i]) {
                    g.fillRect(tCuadroX * i, tCuadroX * j, tCuadroX, tCuadroX);
                }
            }
        }

        //rejilla
        g.setColor(Color.blue);
        for (int i = 0; i < x; i = i + tCuadroX) {
            g.drawLine(0, i, x, i); //horizontal
            g.drawLine(i, 0, i, x); //vertical
        }

    }
    
}


Resultado:

run:
Introduce código (8 caracteres mínimo):
E*7r@yHj0yHvwRI
Sólo se registrarán los 8 primeros caracteres.
Código registrado <E*7r@yHj>
BUILD SUCCESSFUL (total time: 3 seconds)




miércoles, 14 de septiembre de 2022

Circular a plano. Algoritmo sin uso práctico conocido.

Este algoritmo no tiene ningún uso práctico, sólo sirve para fines didácticos y apredizaje.
La premisa consiste en dibujar un máximo de dos pixeles por línea horizontal, línea vertical y línea diagonal.


Código 1 (Circular_a_Plano.java):

package circular_a_plano;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Circular_a_Plano {

    public static void main(String[] args) {

        Boolean[][] map = new Boolean[32][32];

        //inicializar matrix
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                map[j][i] = false;
            }
        }

        map[0][0] = true;
        map[1][1] = true;

        boolean X_libre = true, Y_libre = true;
        boolean Dx_libre = true;
        for (int y = 0; y < map.length; y++) {
            for (int x = 0; x < map.length; x++) {
                X_libre = comprobarX(y, map);
                Y_libre = comprobarY(x, map);
                Dx_libre = comprobarDx(x, y, map);

                if (X_libre && Y_libre && Dx_libre) {
                    map[x][y] = true;
                }
            }
        }
        
        Resultados(map);

        //tamaño lienzo
        int res_x = 1024;
        int res_y = 1024;

        BufferedImage imagen = new BufferedImage(res_x, res_y, BufferedImage.TYPE_INT_RGB);
        Lienzo.Dibujar((Graphics2D) imagen.getGraphics(), res_x, res_y, map);
        try {
            ImageIO.write(imagen, "png", new File("Laberinto.png"));
        } catch (IOException e) {
        }
    }

    private static boolean comprobarX(int y, Boolean[][] map) {
        //comprobación i
        int cont = 0;
        boolean libre = true;
        for (int i = 0; i < map.length; i++) {
            if (map[i][y]) {
                cont++;
            }
            if (cont >= 2) {
                libre = false;
                break;
            }
        }
        return libre;
    }

    private static boolean comprobarY(int x, Boolean[][] map) {
        //comprobación j
        int cont = 0;
        boolean libre = true;
        for (int i = 0; i < map.length; i++) {
            if (map[x][i]) {
                cont++;
            }
            if (cont >= 2) {
                libre = false;
                break;
            }
        }
        return libre;
    }

    private static boolean comprobarDx(int x, int y, Boolean[][] map) {
        //comprobación j
        int cont = 0;
        boolean libre = true;
        int aux = 0;
        if (x <= y) {
            aux = y - x;
            for (int i = 0; i < map.length - aux; i++) {
                if (map[i][aux + i]) {
                    cont++;
                }
            }
            if (cont >= 2) {
                libre = false; //¿funciona?
            }
        }
        if (x >= y) {
            aux = x - y;
            for (int i = 0; i < map.length - aux; i++) {
                if (map[aux + i][i]) {
                    cont++;
                }
            }
            if (cont >= 2) {
                libre = false; //¿funciona?
            }
        }
        return libre;
    }

    private static boolean comprobarDy(int x, int y, Boolean[][] map) {
        int cont = 0;
        int aux = 0;
        boolean libre = true;
        if (x < y) { //if x<y parcial resolve...
            for (int i = x - aux; i < map.length; i++) {
                if (map[i][(y + aux - cont)] || map[y - cont][i]) {
                    cont++;
                }
                if (cont >= 2) {
                    libre = false;
                    break;
                }
            }
        }
        return libre;
    }

    private static void Resultados(Boolean[][] map) {
        System.out.println("Resultado:\n");
        String libre = "";
        for (int i = 0; i < map.length; i++) {
            for (int j = 0; j < map.length; j++) {
                if (map[j][i]) {
                    libre = libre + "█";
                } else {
                    libre = libre + "·";
                }
            }
            libre = libre + ("\n");
        }
        System.out.println(libre);
    }

}


Código 2 (Lienzo.java):

package circular_a_plano;

import java.awt.Color;
import java.awt.Graphics2D;

class Lienzo {

    static void Dibujar(Graphics2D g, int x, int y, Boolean[][] map) {

        //tamaño bloque
        int tCuadroX = x / map.length;

        //fondo blanco
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, x, y);

        //rejilla
        g.setColor(Color.blue);
        for (int i = 0; i < x; i = i + tCuadroX) {
            g.drawLine(0, i, x, i); //horizontal
            g.drawLine(i, 0, i, x); //vertical
        }

        //dibujar bloques muro
        g.setColor(Color.black);
        for (int j = 0; j < map.length; j++) {
            for (int i = 0; i < map.length; i++) {
                if (map[i][j]) {
                    g.fillRect(tCuadroX * i, tCuadroX * j, tCuadroX, tCuadroX);
                }
            }
        }
    }

}


Resultado:


Mastermind 2. Uso de expresión regular para validar entrada de datos.

Siguiendo el post anterior sobre el juego Mastermind, se mejora método de validación de entradas de datos usando expresiones regulares. También se realizan leves cambios de código.


Código (Mastermind.java):

package mastermind;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Mastermind {

    public static void main(String[] args) {

        //presentación e instrucciones juego
        System.out.println(""
                + "-------------\n"
                + " MASTER-MIND\n"
                + "-------------\n\n"
                + "Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.\n"
                + "EJEMPLO: El número a decifrar es el <1234>\n"
                + "Si introduces el <2136>. Esto te dará:\n"
                + "1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.\n\n"
        );

        //inicializar variables
        List<String> valores = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
        int i_hallar[] = new int[4];
        int i_buscar[] = new int[4];
        int muerto, herido, cont = 1;
        String hallar = "", buscar;
        Scanner input;

        //generar código aleatorio        
        Collections.shuffle(valores); //mezclar valores
        for (int i = 0; i < 4; i++) {
            hallar += valores.get(i);
            i_hallar[i] = Integer.parseInt("" + hallar.charAt(i));
        }

        //iniciar partida
        System.out.println("Escriba número de 4 cifras (ej: 1234):\n");
        do {
            muerto = 0;
            herido = 0;

            //introducir y validar
            do {
                System.out.println(cont + "º intento:");
                input = new Scanner(System.in);
                buscar = input.nextLine();
            } while (!ValidarNum(buscar));

            for (int i = 0; i < 4; i++) {
                i_buscar[i] = Integer.parseInt("" + buscar.charAt(i));
            }


            //búsqueda muertos y heridos
            for (int i = 0; i < i_hallar.length; i++) {
                for (int j = 0; j < i_buscar.length; j++) {
                    if (i_buscar[j] == i_hallar[i]) {
                        herido++;
                        if (j == i) {
                            herido--;
                            muerto++;
                        }
                    }
                }
            }
            System.out.println(muerto + " muerto/s y " + herido + " herido/s\n");
        } while (cont++ < 10 && muerto != 4);

        //resultado final
        if (muerto > 3) {
            System.out.println("\nCódigo descifrado! " + Arrays.toString(i_hallar));
            System.out.println("Has ganado!\n");
        } else {
            System.out.println("\nHas perdido!");
            System.out.println("Código era " + Arrays.toString(i_hallar) + "\n");
        }
    }

    private static boolean ValidarNum(String buscar) {
        Boolean valido;
        Pattern pat = Pattern.compile("^\\d{4}$");
        Matcher mat = pat.matcher(buscar);
        valido = mat.find();
        if (!valido) {
            System.out.println("\nCódigo <" + buscar + "> no válido, intente de nuevo.\n");
        }
        return valido;
    }


}


Resultado:

run:
-------------
 MASTER-MIND
-------------

Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.
EJEMPLO: El número a decifrar es el <1234>
Si introduces el <2136>. Esto te dará:
1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.


Escriba número de 4 cifras (ej: 1234):

1º intento:
d34456

Código <d34456> no válido, intente de nuevo.

1º intento:
3458
1 muerto/s y 1 herido/s

2º intento:


domingo, 11 de septiembre de 2022

Mastermind. Crear un juego sencillo.

Código (Mastermid.java):

package mastermind;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Mastermind {

    public static void main(String[] args) {

        //presentación e instrucciones juego
        System.out.println("\n"
                + "-------------\n"
                + " MASTER-MIND\n"
                + "-------------\n\n"
                + "Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.\n"
                + "EJEMPLO: El número a decifrar es el <1234>\n"
                + "Si tu introduces el <2136>. Esto te dará:\n"
                + "1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.\n\n"
        );

        //inicializar variables
        List<String> valores = Arrays.asList("0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
        int i_hallar[] = new int[4];
        int i_buscar[] = new int[4];
        int muerto, herido, cont = 1;
        String hallar = "", buscar;
        Scanner input;

        //generar código aleatorio        
        Collections.shuffle(valores); //mezclar valores
        for (int i = 0; i < 4; i++) {
            hallar += valores.get(i);
            i_hallar[i] = Integer.parseInt("" + hallar.charAt(i));
        }
        //System.out.println("Código decifrado: " + hallar);

        //iniciar partida
        System.out.println("Escriba número de 4 cifras (ej: 1234):\n");
        do {
            muerto = 0;
            herido = 0;
            do {
                System.out.println(cont + "º intento:");
                input = new Scanner(System.in);
                buscar = input.nextLine();
                if (buscar.length() != 4) {
                    System.out.println("Código no válido!\n");
                }
            } while (buscar.length() != 4);
            for (int i = 0; i < 4; i++) {
                i_buscar[i] = Integer.parseInt("" + buscar.charAt(i));
            }

            //búsqueda muertos y heridos
            for (int i = 0; i < i_hallar.length; i++) {
                for (int j = 0; j < i_buscar.length; j++) {
                    if (i_buscar[j] == i_hallar[i]) {
                        herido++;
                        if (j == i) {
                            herido--;
                            muerto++;
                        }
                    }
                }
            }
            System.out.println(muerto + " muerto/s y " + herido + " herido/s\n");
        } while (cont++ < 10 && muerto != 4);

        //resultado final
        if (muerto > 3) {
            System.out.println("\nCódigo descifrado! " + Arrays.toString(i_hallar));
            System.out.println("Has ganado!\n");
        } else {
            System.out.println("\nHas perdido!");
            System.out.println("Código era " + Arrays.toString(i_hallar) + "\n");
        }
    }

}


Resultado:

run:

-------------
 MASTER-MIND
-------------

Se trata de adivinar un número, si adivinas el número y el lugar correcto es un muerto, si aciertas el número pero no el lugar es un herido.
EJEMPLO: El número a decifrar es el <1234>
Si tu introduces el <2136>. Esto te dará:
1 muerto(el 3) y 2 heridos(1 y 2). El 6 al no estar no cuenta.


Escriba número de 4 cifras (ej: 1234):
 
1º intento:
4237
1 muerto/s y 1 herido/s

2º intento:
324
Código no válido!

2º intento:
6453
0 muerto/s y 1 herido/s

3º intento:
4712
2 muerto/s y 1 herido/s

4º intento:
4710
2 muerto/s y 2 herido/s

5º intento:
4701
4 muerto/s y 0 herido/s


Código descifrado! [4, 7, 0, 1]
Has ganado!

BUILD SUCCESSFUL (total time: 1 minute 12 seconds)


domingo, 28 de agosto de 2022

Generación de números primos.

Código (Limit.java):

package limit;

public class Limit {

    public static void main(String[] args) {
        boolean p;
        int limit = 100;
        String aux = "";
        for (int n = 3; n < limit; n++) {
            p = esPrimo(n);
            aux += p ? n : "·";
        }
        System.out.println(aux);        
    }

    private static boolean esPrimo(int n) {
        //es numero par?
        if (n % 2 == 0) {
            return false;
        }
        //es numero multiplo del resto de numeros impares?
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

}


Resultado:

run:
3·5·7···11·13···17·19···23·····29·31·····37···41·43···47·····53·····59·61·····67···71·73·····79···83·····89·······97··
BUILD SUCCESSFUL (total time: 0 seconds)

Con la tecnología de Blogger.