• This is default featured slide 1 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 2 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 3 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 4 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

  • This is default featured slide 5 title

    Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by NewBloggerThemes.com.

Mostrando entradas con la etiqueta jar. Mostrar todas las entradas
Mostrando entradas con la etiqueta jar. Mostrar todas las entradas

SUDOKU

Bueno hace tiempo vi por ahí que preguntaban como hacer un SUDOKU bueno les traigo las respuesta y en código java como tiene que ser es una aplicación de consola que pronto pasara a frame pero por lo pronto disfrútenla.
Son libres de hacer lo que deseen con el codigo:



//codigo java
/**
 *
 * @author JONATHAN
 */
import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;

public class SUDOKU {
 
 //PROPIEDADES.
 public static int nivel = 1;
 
 
 //METODO PARA CARGAR JUEGO.
 public static int[][] cargar_juego( int nivel){
  
  int[][] matriz = new int[9][9];
  
  switch (nivel){
  
  case 2:
  
  matriz[0][0] = 7;matriz[0][4] = 5;matriz[0][6] = 4;matriz[1][0] = 4;
  matriz[1][3] = 1;matriz[1][4] = 9;matriz[1][6] = 6;matriz[1][7] = 2;
  matriz[1][8] = 7;matriz[2][2] = 6;matriz[2][8] = 9;matriz[3][0] = 9;
  matriz[3][2] = 3;matriz[3][6] = 8;matriz[4][3] = 4;matriz[4][5] = 3;
  matriz[5][2] = 8;matriz[5][6] = 5;matriz[5][8] = 2;matriz[6][0] = 5;
  matriz[6][6] = 2;matriz[7][0] = 2;matriz[7][1] = 9;matriz[7][2] = 1;
  matriz[7][4] = 4;matriz[7][5] = 7;matriz[7][8] = 8;matriz[8][2] = 7;
  matriz[8][4] = 1;matriz[8][8] = 5;
  
  break;
  
  
  case 1:
  default:
  
  matriz[0][2] = 9;matriz[0][5] = 8;matriz[0][6] = 5; matriz[0][7] = 4;
  matriz[1][8] = 7;matriz[2][1] = 5;matriz[2][2] = 4; matriz[2][4] = 9;
  matriz[2][6] = 1;matriz[3][5] = 6;matriz[3][6] = 3; matriz[3][7] = 2;
  matriz[4][1] = 8;matriz[4][2] = 2;matriz[4][6] = 4; matriz[4][7] = 1;
  matriz[5][1] = 3;matriz[5][2] = 5;matriz[5][3] = 2; matriz[6][2] = 7;
  matriz[6][4] = 3;matriz[6][6] = 2;matriz[6][7] = 5; matriz[7][0] = 9;
  matriz[8][1] = 4;matriz[8][2] = 3;matriz[8][3] = 8; matriz[8][7] = 9;
  
  break;
  
  }
  
  return matriz;
 }
 
 //METODO PARA NO SOBREESCRIBIR VALORES EN EL JUEGO.
 public static boolean es_origen( int fila, int columna, int[][] matriz ){
  
  boolean resultado = false;
  if ( matriz[fila][columna] != 0)
   resultado = true;
  
  return resultado;
  
 }
 
 //METODO QUE DETECTA SI EL JUEGO FUE TERMINADO.
 public static boolean terminado( int[][] matriz ){
  
  boolean resultado = true;
  
  for ( int f = 0; f < matriz.length; f ++)
   for ( int c = 0; c < matriz[0].length; c ++)
    if ( matriz[f][c] == 0 )
     resultado = false;
  
   
  return resultado;

 }
 
 //METODO QUE IMPRIME UN MENSAJE CON BORDE.
 public static void mensaje ( String mensaje ){
  
  //CABECERA.
  System.out.print("É");
  for(int i = 0; i < (mensaje.length() + 20); i ++ )
   System.out.print ("Í");
  System.out.print ("»\n");

  //CUERPO.
  System.out.print("º          ");
  System.out.print( mensaje );
  System.out.print("          º\n");
 
  //PIE
  System.out.print("È");
  for(int i = 0; i < (mensaje.length() + 20); i ++ )
   System.out.print ("Í");
   
  System.out.print ("¼\n\n");
   
  
 }
 
 //METODO QUE IMPRIME EL VECTOR.
 public static void imprime_vector ( int[][] matriz ){
  
  
  System.out.println( " °°°°°°°°°°°°²°°°°°°°°°°°²°°°°°°°°°°°° " );
  
  for ( int f = 0; f < matriz.length; f ++ ){
  
   System.out.print(" ° ");
   
   for ( int c = 0; c < matriz.length; c++){
    
    if ( matriz[f][c] != 0 ) 
     System.out.print ( matriz[f][c] );
    else 
     System.out.print (" ");
    
    if ( es_origen( f, c, cargar_juego( nivel ) ) )
     System.out.print (" ");
    else
     System.out.print (" ");
    
    if ( c == 2 || c == 5) 
     System.out.print ("² ");
    else
     System.out.print ("° ") ;
     
   }
   System.out.println();
   if ( f != 2 && f != 5)
    System.out.print( " °°°°°°°°°°°°²°°°°°°°°°°°²°°°°°°°°°°°° " );
   else
    System.out.print( " ²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²²² " );
   System.out.println();
  }
 }

 //METODO PARA COMPROBAR FILAS.
 public static boolean existe_fila( int numero, int fila, int[][] matriz ){
  
  boolean resultado = false;
  
  for ( int i = 0; i < matriz.length; i ++ )
   if ( matriz[(fila-1)][i] == numero ){
     resultado = true;
     break;
   }
   
  //COMPROBAMOS SI ES 0.
  if ( numero == 0 ) resultado = false;
  
  return resultado;
  
 }
 
 //METODO PARA COMPROBAR COLUMNAS.
 public static boolean existe_columna( int numero, int columna, int[][] matriz ){
  
  boolean resultado = false;
  
  for ( int i = 0; i < matriz.length; i ++ )
   if ( matriz[i][(columna-1)] == numero ){
     resultado = true;
     break;
   }
   
  //COMPROBAMOS SI ES 0.
  if ( numero == 0 ) resultado = false;
  
  return resultado;
  
 }
 
 // METODO PARA COMPROBAR LOS INDICES.
 public static boolean comprobar_indice ( int indice ){
  
  if ( indice > 0 && indice < 10)
   return true;
  else
   return false;
  
 }
 
 // METODO PARA COMPROBAR LOS VALORES.
 public static boolean comprobar_valor ( int valor ){
  
  if ( valor >= 0 && valor < 10)
   return true;
  else
   return false;
  
 }
 
 //METODO PARA COMPROBAR LAS CAJAS.
 public static boolean existe_caja ( int valor, int fila, int columna, int[][] matriz ){
  
  //VARIABLES.
  int minimo_fila;
  int maximo_fila;
  int minimo_columna;
  int maximo_columna;
  boolean resultado = false;
 
  //DETERMINAMOS LAS FILAS DE LA CAJA.
  if ( fila > 0 && fila < 4){
   minimo_fila = 0;
   maximo_fila = 2;
  }else if ( fila > 3 && fila < 7 ){
   minimo_fila = 3;
   maximo_fila = 5;
  }else{
   minimo_fila = 6;
   maximo_fila = 8;
  }
    
  //DETERMINAMOS LAS COLUMNAS DE LA CAJA.
  if ( columna > 0 && columna < 4){
   minimo_columna = 0;
   maximo_columna = 2;
  }else if ( columna > 3 && columna < 7 ){
   minimo_columna = 3;
   maximo_columna = 5;
  }else{
   minimo_columna = 6;
   maximo_columna = 8;
  }
  
  //RECORREMOS EL RANGO DE LA CAJA, Y BUSCAMOS EL VALOR.
  for ( int f = minimo_fila; f <= maximo_fila; f++ )
   for ( int c = minimo_columna; c <= maximo_columna; c++)
    if ( matriz[f][c] == valor ){
     resultado = true;
     break; 
     
    }
   
   
  //COMPROBAMOS SI ES 0.
  if ( valor == 0 ) resultado = false;
  
  //REGRESAMOS EL VALOR BOOLEANO.
  return resultado;
   
 
  
 }
 
 //METODO PRINCIPAL
 public static void main ( String[] args ) throws Exception
 {
  
  //VARIABLES.
  BufferedReader teclado = new BufferedReader( new InputStreamReader ( System.in ) );
  int[][] sudoku = new int[9][9];
  int fila = 0;
  int columna = 0;
  int valor = 0;
  
  //CARGAMOS EL JUEGO.
  sudoku = cargar_juego( nivel );
   
  while ( true ){
  
  //IMPRIMIMOS EL VECTOR.
  imprime_vector ( sudoku );
  
  //PEDIMOS LOS DATOS.
  System.out.println( "Inserte las coordenadas (fila/columna): " );
  
  //FILA.
  System.out.print( "[fila]: " );
  fila = Integer.parseInt( teclado.readLine() );
  
  //COLUMNA.
  System.out.print( "[columna]: " );
  columna = Integer.parseInt( teclado.readLine() );
  
  //VALOR.
  System.out.print( "[valor]: " );
  valor = Integer.parseInt( teclado.readLine() );
  
  //COMPROBAMOS LA FILA ESTA EN RANGO.
  if ( !comprobar_indice(fila) )
   mensaje ("El valor de la fila no es correcto..");
  
  //COMPROBAMOS LA COLUMNA ESTA EN RANGO.
  else if ( !comprobar_indice(columna) )
   mensaje ( "El valor de la columna no es correcto.");
   
  //COMPROBAMOS QUE EL VALOR ESTA EN RANGO.
  else if ( !comprobar_valor(valor) )
   mensaje ( "El valor introducido no es valido..");
   
  //COMPROBAMOS QUE USE CASILLAS DISPONIBLES.
  else if ( es_origen( (fila - 1), (columna - 1), cargar_juego( nivel ) ) )
   mensaje ( "Ese valor es predeterminado del juego...");
   
  //COMPRUEBA QUE NO SE REPITA EL VALOR EN LA FILA.
  else if ( existe_fila( valor, fila, sudoku ) )
   mensaje ("[X] El valor " + valor + " ya ha sido usado en la fila..");
   
  //COMPRUEBA QUE NO SE REPITA EL VALOR EN LA COLUMNA..
  else if ( existe_columna( valor, columna, sudoku ) )
   mensaje ( "[X] El valor " + valor + " ya ha sido usado en la columna..");
   
  //COMPRUEBA QUE EL VALOR NO ESTÉ EN LA CAJA.
  else if ( existe_caja( valor, fila, columna, sudoku ) )
   mensaje ( "[X] El valor ya existe en la caja..");
   
  //INTRODUCIMOS EL VALOR A LA MATRIZ.
  else {
   sudoku[(fila - 1)][(columna - 1)] = valor;
   mensaje( "[" + fila + "," + columna + "]=" + valor + " Correcto.");
  }
  
  
  //COMPRUEBA SI SE TERMINÓ EL JUEGO.
  if ( terminado( sudoku ) ){
   mensaje( "FELICIDADES!!!! HAS TERMINADO EL JUEGO!!");
   imprime_vector( sudoku );
   System.out.println ( "Presiona una tecla para continuar en el siguiente nivel..");
   teclado.readLine();
   
   //AUMENTAMOS EL NIVEL DEL JUEGO.
   nivel ++;
   sudoku = cargar_juego( nivel );
   mensaje( "SUDOKU NIVEL " + nivel );
  }
 
 
  }
 
 } 

 
}


Share:

Metodo de ordenamiento propio

Hola como algunos de uds saben existen multiples metodos de ordenar elementos ya sea de un arreglo o de otro tipo de objeto.
Presento mi propio metodo de ordenamiento que me vino a la mente en un chispaso hoy.
por ejemplo si tenemos esto:
ingreso = 5,7,15,0,2,1
de salida tendriamos esto
salida = 0,1,2,5,7,15
Para ello existe la burbuja,el de ciclos y muchos otros mas pero como me gusta generar contenido propio muestro el mio.
Consta de 2 clases para no marearlos con tanto codigo.

Clase Main.java

import java.util.Random;
/**
 *
 * @author JONATHAN
 */
public class Main {
    public static void main(String[] args) {
        // TODO code application logic here
        int[] arreglo_temp = null;
        arreglo_temp = Crear_lista(5);
        Libreria objeto = new Libreria();
        System.out.println("ORIGINAL : "+ objeto.Visualizar(arreglo_temp));
        System.out.println("ORDENADO : "+ objeto.Visualizar(objeto.ordenar(arreglo_temp)));
    }

    private static int[] Crear_lista(int n) {
        int[] arre = new int[n];
        Random generador = new Random();
        for (int i = 0; i < arre.length; i++) {
            arre[i] = generador.nextInt(10);
        }
        return arre;
    }
}
Hasta ahi simple verdad, cumplo con la regla de orientado a objetos, sin nada de complicaciones de codigo.
El metodo Crear_lista genera un array de elementos aleatorios,jejeje asi no parece predeterminado a nada.
Ahora pasemos a la clase Libreria.java es decir la que trabaja con el ordenamiento.

import java.util.ArrayList;
/**
 *
 * @author JONATHAN
 */
class Libreria {
    private int[] vector;
    private int elementos;

    public Libreria() {
    }
    //para imprimir el array de la forma / 0 / 1 / 2 / 3 / 4 /5

    public String Visualizar(int[] v) {
        String s = " / ";
        for (int i = 0; i < v.length; i++) {
            s += v[i] + " / ";
        }
        return s;
    }

    int[] ordenar(int[] v) {
        this.vector = v;
        elementos = vector.length;
        ArrayList uno = new ArrayList();
        for (int i = 0; i < elementos; i++)
        {
            uno.add(vector[i]);//Recorro el arreglo y agrego cada elemento al arraylist
        }
        for(int i=0;i
        {
            vector[i]=toEntero(uno.get(indice_Menor(uno)));//Asigno al arreglo
            //primitivo el elemento menor del arraylist
            uno.remove(toEntero(indice_Menor(uno)));
            //Proceso a eliminar dicho elemento del arraylist
            //Se ejecuta un bucle rescatando el menor elemento.
            //Asi ordenaria mi arreglo
        }
        return vector;
    }

    private int indice_Menor(ArrayList indice) {
        int b = 0;
        for (int i = 0; i < indice.size(); i++) {
            if (toEntero(indice.get(i)) < toEntero(indice.get(b))) {
                b = i;
            }
        }
        return b;
    }

    private int toEntero(Object get) {
        //los arraylist retornan objetos pero necesito trabajar con enteros
        //Simplemente convierto a entero un objeto cuando es llamada esta funcion
        return Integer.parseInt(get.toString());
    }

}



Hagamos un resumen existen los metodos:
  • Visualizar(int[] v);
  • ordenar(int[] v);
  • indice_Menor(ArrayList indice);
  • toEntero(Object get);
El metodo  Visualizar(int[] v) es solo para la presentacion de datos de modo que no aparescan todos juntos.
El metodo ordenar(int[] v) es para realizar el ordenamiento propiamente dicho.
El metodo indice_Menor(ArrayList indice) sirve para obtener el menor elemento de un arraylist y retorna su indice para procesarlo.
Finalmente como los arraylist trabajan con objetos necesito un convertidor porque lo que usare seran enteros, para ese caso esta toEntero(Object get) que me retornara como entero cualquier objeto enviado.
Espero les sirva es algo que se me ocurrio comenten y diganme que les parece.
Share:

Trabajos de Impresion

Cuantas veces no hemos querido imprimir algun texto generado por un programa para un reporte simple pues con este ejemplo lo podran hacer.
Consta de 2 clases y usaremos PrinterJob.
Para este caso digitaremos un texto y cuando le demos al boton imprimir saldra el texto en papel hacia la impresora predeterminada.

Clase Impresora
package Imprimir;
/**
*
* @author JONATHAN
*/
/********************************************************************
* El siguiente programa es un ejemplo bastante sencillo de *
* impresion con JAVA. *
********************************************************************/
import java.awt.*;
/********************************************************************
* La siguiente clase llamada "Impresora", es la encargada de *
* establecer la fuente con que se va a imprimir, de obtener el *
* trabajo de impresion, la página. En esta clase hay un metodo *
* llamado imprimir, el cual recibe una cadena y la imprime. *
********************************************************************/
class Impresora {
Font fuente = new Font("Dialog", Font.PLAIN, 10);
PrintJob trabajo_impresion;
Graphics pagina;
/********************************************************************
* A continuacion el constructor de la clase. Aqui lo unico que *
* hago es tomar un objeto de impresion. *
********************************************************************/
Impresora() {
trabajo_impresion = Toolkit.getDefaultToolkit().getPrintJob(new Frame(), "Desde Java", null);
}
/********************************************************************
* A continuacion el metodo "imprimir(String)", el encargado de *
* colocar en el objeto grafico la cadena que se le pasa como *
* parámetro y se imprime. *
********************************************************************/
public void imprimir(String Cadena) {
//LO COLOCO EN UN try/catch PORQUE PUEDEN CANCELAR LA IMPRESION
try {
pagina = trabajo_impresion.getGraphics();
pagina.setFont(fuente);
pagina.setColor(Color.black);
pagina.drawString(Cadena, 60, 60);
pagina.dispose();
trabajo_impresion.end();
} catch (Exception e) {
System.out.println("LA IMPRESION HA SIDO CANCELADA...");
}
}//FIN DEL PROCEDIMIENTO imprimir(String...)
}//FIN DE LA CLASE Impresora

Ahora con la Clase principal.



package Imprimir;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
/**
*
* @author JONATHAN
*/
//A CONTINUACION LA CLASE PRINCIPAL
public class Programa_Impresion extends JFrame {
String cadena;
JTextField campo;
JButton imprimir;
JLabel info;
Impresora impresion;
JPanel principal = new JPanel(new BorderLayout());
JPanel etiq = new JPanel(new FlowLayout());
JPanel dos = new JPanel(new FlowLayout());
//CONSTRUCTOR DE LA CLASE
Programa_Impresion() {
super("Muestra Simple de Impresión en JAVA...");
info = new JLabel("ESCRIBA ALGO EN EL CAMPO Y HAGA CLIC EN IMPRIMIR...");
cadena = new String();
campo = new JTextField(30);
imprimir = new JButton("IMPRIMIR");
dos.add(campo);
dos.add(imprimir);
etiq.add(info);
campo.setToolTipText("ESCRIBA ALGO AQUÍ...");
imprimir.setToolTipText("CLIC AQUI PARA IMPRIMIR...");
principal.add(etiq, BorderLayout.NORTH);
principal.add(dos, BorderLayout.CENTER);
getContentPane().add(principal);
//AJUSTO EL TAMAÑO DE LA VENTANA AL MINIMO
pack();
//NO PERMITO QUE PUEDAN CAMBIAR EL TAMAÑO DE LA VENTANA
this.setResizable(false);
//AHORA LA CENTRARA EN LA PANTALLA
Dimension pantalla, cuadro;
pantalla = Toolkit.getDefaultToolkit().getScreenSize();
cuadro = this.getSize();
this.setLocation(((pantalla.width - cuadro.width) / 2),
(pantalla.height - cuadro.height) / 2);

//LE AGREGAMOS EL EVENTO AL BOTON "imprimir"
imprimir.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
cadena = "";
cadena = String.valueOf(campo.getText());
if (!cadena.equals("")) {
impresion = new Impresora();//Instanciamos clase y se la mandamos al metodo imprimir
impresion.imprimir(cadena);
} else {
System.out.println("NO SE IMPRIME NADA EN BLANCO...");
}
campo.requestFocus();
campo.select(0, cadena.length());
}
});


}//FIN DEL CONSTRUCTOR
public static void main(String jm[]) {
Programa_Impresion p = new Programa_Impresion();//Instanciamos clase
p.show();
p.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}//FIN DEL MAIN
}//FIN DE LA CLASE PRINCIPAL

Como se daran cuenta instanciaremos la clase Impresora y le pasaremosmediante un metodo la cadena a imprimir ahora esto no se queda asi, lo pueden exterder osea lo que iria en el metodo podria ser algo mas grande.

Se los dejo a su imaginacion
Share:

Primos en un arreglo

Ahora buscaremos numeos primos en un arreglo es sencillo ya rapido solo refrescaremos que primo es aquel divisible sobre si y el 1.
/*
 * Realizar el programa que asigne a un arreglo lineal n numeros enteros
 * se pide calcular e imprimir cuantos numeros primos existen en el arreglo.
 */
package arreglos;

/**
 *
 * @author Jonathan
 */
public class arreglos1{

    public static void main(String[] args) {
        int n, i, cnp = 0, res;
        n = (int) (Math.random() * 100);
        int num[] = new int[n + 1];
        for (i = 0; i < n; i++) {
            num[i] = (int) (Math.random() * 100);
            res = 0;
            for (int j = 1; j <= num[i]; j++) {
                if (num[i] % j == 0) {
                    res++;
                }
            }
            if (res == 2) {
                cnp++;
                System.out.println("numero primo =" + num[i]);
            }

        }
        System.out.println("La cantidad de numeros primos es :" + cnp);
    }
}
Ya vimos un unidimensional tenemos la idea apliquemos al bidimensional.
/* 
* Realizar el programa que asigne aleatoriamente a un arreglo bidimensional 
* de mxn elementos datos de tipo entero, se pide calcular e imprimir cuantos 
* nùmeros primos existen en cada fila y en cada columna del arreglo. 
*/ 
package arreglos;

public class arreglos2{

    public static void main(String[] args) {
        int m, n, i, j, cnp, res;
        m = (int) (Math.random() * 10 + 2);
        n = (int) (Math.random() * 10 + 2);
        int beta[][] = new int[m + 1][n + 1];
        cnp = 0;
        for (i = 0; i < m; i++) {
            for (j = 0; j < n; j++) {
                beta[i][j] = (int) (Math.random() * 100);
                res = 0;
                for (int k = 1; k <= beta[i][j]; k++) {
                    if (beta[i][j] % k == 0) {
                        res++;
                    }
                }
                if (res == 2) {
                    cnp++;
                    System.out.println("numero primo =" + beta[i][j]);
                }

            }
        }//Fin de la generacion de filas
        System.out.println("La cantidad de numeros primos en la fila " + i + " son:" + cnp);
        for (j = 0; j < n; j++) {
            for (i = 0; i < m; i++) {
                beta[i][j] = (int) (Math.random() * 100);
                res = 0;
                for (int k = 1; k <= beta[i][j]; k++) {
                    if (beta[i][j] % k == 0) {
                        res++;
                    }
                }
                if (res == 2) {
                    cnp++;
                    System.out.println("numero primo =" + beta[i][j]);
                }

            }
        } //Fin de la generacion de columnas

        System.out.println("La cantidad de numeros primos en la columna " + j + " son:" + cnp);
    }
}
http://www.mediafire.com/?mgtybdwnjmb
Share:

Visitantes

Flag Counter

Popular Posts

Etiquetas

Recent Posts