Localización en Android



public void setLocation(Location loc) {
    //Obtener la direcci—n de la calle a partir de la latitud y la longitud    
   if (loc.getLatitude() != 0.0 && loc.getLongitude() != 0.0) {
        try {
            Geocoder geocoder = new Geocoder(this, Locale.getDefault());
            List<Address> list = geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(), 1);
            if (!list.isEmpty()) {
                Address address = list.get(0);
                Toast.makeText(getBaseContext(), "Mi dirección es: \n" 
                     address.getAddressLine(0), Toast.LENGTH_LONG).show();

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Selección en java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Seleccion {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("ingrese numero de datos a ingresar: ");
int tam = Integer.parseInt(in.readLine());
int arr[] = new int[tam];
int j = 0;
for (int i = 0; i < arr.length; i++) {
j+=1;
System.out.println("Elemento "+j+":");
arr[i]=Integer.parseInt(in.readLine());
}
OrdenarSeleccion(arr);
imprimir(arr);
}
private static void OrdenarSeleccion(int[] vector) {
int menor, pos,j, tmp;
for (int i = 0; i < vector.length-1; i++) {
menor=vector[i];
pos=i;
for ( j = i+1; j < vector.length; j++) {
if(vector[j]<menor){
menor=vector[j];
pos=j;
}
}
if(pos!=i){
tmp= vector[i];
vector[i]=vector[pos];
vector[pos]=tmp;
}
}
}
public static void imprimir(int[] vector){
for (int i = 0; i < vector.length-1; i++) {
System.out.print(vector[i]+" ");
}
System.out.println(vector[vector.length-1]);
}
}


Curiosidades del bloc de notas de windows 1


Trick Attack World Trade Center


  1. Abrir el Bloc de Notas
  2. Escribir “Q33N” (sin comillas) en Mayusculas.
  3. Cambie el tamaño a 72.
  4. Cambie la Fuente a Wingdings.

Quicksort en java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Quicksort {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("ingrese numero de datos a ingresar: ");
int tam = Integer.parseInt(in.readLine());
int arr[] = new int[tam];
int j = 0;
for (int i = 0; i < arr.length; i++) {
j+=1;
System.out.println("Elemento "+j+":");
arr[i]=Integer.parseInt(in.readLine());
}
OrdenarQuicksort(arr,0,arr.length-1);
imprimir(arr);
}
private static void OrdenarQuicksort(int[] a, int izq, int der) {
int pivote=a[izq];
int i = izq;
int j = der;
int aux;
while(i<j){ //mientras no se crucen las busquedas
while(a[i]<=pivote&&i<j) i++; //busca el elemento mayor que piivote
while(a[j]>pivote) j--; //busca elemento menor que pivote
if(i<j){ //si no se han cruzado
aux = a[i]; //los intercambia
a[i]=a[j];
a[j]=aux;
}
}
a[izq]=a[j]; //se coloca el pivote en sulugar d forma que tendremos
a[j]=pivote; //los menores a su izquierda y los mayores a su derecha
if(izq<j-1)
OrdenarQuicksort(a, izq, j-1); //ordenamos subarray izquierdo
if(j+1<der)
OrdenarQuicksort(a, j+1, der); //ordenamos subarray derrecho
}
public static void imprimir(int[] vector){
for (int i = 0; i < vector.length-1; i++) {
System.out.print(vector[i]+" ");
}
System.out.println(vector[vector.length-1]);
}

}


Códigos windows para apagar, reiniciar, suspender e hibernar el ordenador desde bloc de notas

Abre el bloc de notas y escribe lo siguiente:

shutdown.exe -s     ---     Comando que apaga el ordenador.

Si le añades -t esperará 30 segundos de forma predeterminada. También puedes añadir despues de -t el tiempo que quieras que espere en segundos. 

     Ejemplo:
          shutdown.exe -s -t 45     ---     Espera 45 segundos.
          shutdown.exe -s -t 00     ---     Apaga inmediatamente el ordenador.

Puedes añadirle un comentario:

     shutdown.exe -s -t 30 -c "comentario"
     Ejemplo:
          shutdown.exe -s -t 30 -c "La computadora se apagará en 30 segundos"



Después haz clic en archivo y selecciona "guardar como". Deberás guardar el archivo como un archivo de procesamiento por lotes.

Haz clic en el menú desplegable "Guardar como tipo" y selecciona "Todos los archivos (*.*)"

Cambia la extensión de ".txt" a ".bat".

Guarda el archivo.

Cuando lo abras se apagará el ordenador.
     

Inserción en java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Insercion {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("ingrese numero de datos a ingresar: ");
int tam = Integer.parseInt(in.readLine());
int arr[] = new int[tam];
int j = 0;
for (int i = 0; i < arr.length; i++) {
j+=1;
System.out.println("Elemento "+j+":");
arr[i]=Integer.parseInt(in.readLine());
}
OrdenarInserccion(arr);
imprimir(arr);
}
public static void OrdenarInserccion (int vector[]){
for (int i = 0; i < vector.length; i++) {
int x = vector[i];
int j = i-1;
while(j>=0&&x<vector[j]){
vector[j+1]=vector[j];
j--;
}
vector[j+1]=x;
}
}
public static void imprimir(int[] vector){
for (int i = 0; i < vector.length-1; i++) {
System.out.print(vector[i]+" ");
}
System.out.println(vector[vector.length-1]);
}
}

Códigos windows para apagar, reiniciar, suspender e hibernar el ordenador desde acceso directo

Crea un nuevo acceso directo.

Introduce el siguiente código (Elige el que necesites):
  • Suspender: C:\Windows\System32\Rundll32.exe powrprof.dll, SetSuspendState
  • Hibernara: C:\Windows\System32\shutdown.exe /h
  • Apagar: C:\Windows\System32\shutdown.exe -s -t 00
  • Reiniciar: C:\Windows\System32\shutdown.exe -r -t 00
Pulsa finalizar para completar la operación y ya dispondrás de un botón donde tu desees.

Al hacer clic en él se apagará/reiniciará/hibernará/suspenderá el ordenador.

Máximo común divisor en Java

Iterativo y recursivo

public class Mcd {

public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Scanner lee = new java.util.Scanner(System.in);
int n = lee.nextInt();
int m = lee.nextInt();
int divisor = mcd(n,m);
System.out.println(divisor);
System.out.println(mcd_iterativo(n,m));
lee.close();
}
public static int mcd(int a, int b){
if(a%b==0){
return b;
}else{
return mcd(b, a%b);
}
}
public static int mcd_iterativo(int a, int b){
while(a>0){
int aux = a;
a=b%a;
b=aux;
}
return b;
}
}

Manejo de strings en Matlab


Escribir una función que convierta un número romano a su equivalente decimal. Los valores de los números romanos son:
        I            1
        V          5
        X        10
        L        50
        C      100
Se utilizará como representación el sistema en el que la posición de los caracteres importa, es decir, el valor 4 sería IV.


function out = practica1_10()

    num=input('Ingrese el numero romano: ', 's');
    total=0;
    valor_anterior=0;
    for i=1:length(num)
        letra=num(i);
        switch letra
            case 'C'
                valor=100;
            case 'M'
                valor=1000;
            case 'D'
                valor=500;
            case 'L'
                valor=50;
            case 'X'
                valor=10;
            case 'V'
                valor=5;
            case 'I'
                valor=1;
        end
        if (valor>valor_anterior&&valor_anterior>0)
            valor_anterior = 0-valor_anterior;
        end
        total = total + valor_anterior;
        valor_anterior = valor;
        
        
    end
    out=total+valor_anterior;
end



Escribir una función que se le pase como parámetro una frase y que devuelva un cell array con todas las palabras que se han utilizado en la frase y el número de veces que se repite cada palabra.
Probar los resultados con las frases ‘Primera frase de prueba de este ejercicio’ ‘Otra frase para la prueba de la frase de la practica’

function out = practica1_ejercicio11() 
    resto = input('Introduzca la frase: ','s'); 
    separadas = {}; 
    i = 1; 
    while length(resto) ~=0 
        [primera,resto] = strtok(resto); 
        separadas{i} = primera; 
        i = i+1; 
    end
    lonngitudCellArray=i-1;
    posicion=1;
    numeroPalabras={};
    for j=1:lonngitudCellArray
        contador=0;
        for k=1:lonngitudCellArray
            if(strcmp(separadas{j},separadas{k})==1)
                contador=contador+1;
            end
            
        end    
        
        numeroPalabras{posicion}=contador;
        posicion=posicion+1;
        
    end
    out=[separadas;numeroPalabras];
    
end 


Programa deshacer en Java swing


DESCARGAR

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.UndoManager;
public class Deshacer extends JFrame 
{
  protected JTextArea textArea = new JTextArea();
  
  protected UndoManager undoManager = new UndoManager();
  protected JButton deshacerBoton = new JButton("Deshacer");
  protected JButton rehacerBoton = new JButton("Rehacer");
  public Deshacer() {
    super("Prueba deshacer/rehacer");//nombre de la ventana
    deshacerBoton.setEnabled(false);
    rehacerBoton.setEnabled(false);
    JPanel buttonPanel = new JPanel(new GridLayout());
    buttonPanel.add(deshacerBoton);
    buttonPanel.add(rehacerBoton);
    JScrollPane scroller = new JScrollPane(textArea);
    getContentPane().add(buttonPanel, BorderLayout.NORTH);
    getContentPane().add(scroller, BorderLayout.CENTER);
    textArea.getDocument().addUndoableEditListener(
        new UndoableEditListener() {
          public void undoableEditHappened(UndoableEditEvent e) {
            undoManager.addEdit(e.getEdit());
            updateButtons();
          }
        });
    deshacerBoton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          undoManager.undo();
        } catch (CannotRedoException cre) {
          cre.printStackTrace();
        }
        updateButtons();
      }
    });
    rehacerBoton.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        try {
          undoManager.redo();
        } catch (CannotRedoException cre) {
          cre.printStackTrace();
        }
        updateButtons();
      }
    });
    setSize(400, 300);
    setVisible(true);
  }
  public void updateButtons() {
    
    deshacerBoton.setText("Se puede Deshacer");
    rehacerBoton.setText("Se puede Rehacer");
    deshacerBoton.setEnabled(undoManager.canUndo());
    rehacerBoton.setEnabled(undoManager.canRedo());
  }
  public static void main(String argv[]) {
    new Deshacer();
  }
}

Fibonnacci en java

Iterativo y Recursivo
public class Fibonnacci {

public static void main(String[] args) {
// TODO Auto-generated method stub
java.util.Scanner lee = new java.util.Scanner(System.in);
int n = lee.nextInt();
for (int i = 1; i <= n; i++) {
System.out.print(fib(i)+" ");
}
System.out.println();
for (int i = 2; i < args.length; i++) {
System.out.print(fib_iterativo(i)+" ");
}
lee.close();
}
public static int fib( int n){
if(n==1||n==2){
return 1;
}else{
return (fib(n-1)+fib(n-2));
}
}
public static int fib_iterativo(int n){
int serie, fb1, fb2;
fb1 = fb2 = serie = 1;
if((n==1)||(n==2)){
serie = 1;
}
else{
for (int i = 3; i <=n; i++) {
serie = fb1+fb2;
fb2 = fb1;
fb1 = serie;
}
}
return serie;
}
}



Como calcular la letra de un DNI en Matlab

Escribir una función en Matlab una función cuyo parámetro de entrada sea un número
comprendido entre 1.000.000 y 99.999.999 que permita calcular la letra del DNI. La
función debe devolver la letra del DNI.


function letra = Ej8DNI ()
numero = input('Ingrese el valor de la variable: ');
if(numero<1000000||numero>99999999)
    letra=99;
else
resto = mod(numero, 23);
switch resto
    case 0
        letra = 'T';
    case 1
        letra = 'R';
    case 2
        letra = 'W';
    case 3
        letra = 'A';
    case 4
        letra = 'G';
    case 5
        letra = 'M';
    case 6
        letra = 'Y';
    case 7
        letra = 'F';
    case 8
        letra = 'P';
    case 9
        letra = 'D';
    case 10
        letra = 'X';
    case 11
        letra = 'B';
    case 12
        letra = 'N';
    case 13
        letra = 'J';
    case 14
        letra = 'Z';
    case 15
        letra = 'S';
    case 16
        letra = 'Q';
    case 17
        letra = 'V';
    case 18
        letra = 'H';
    case 19
        letra = 'L';
    case 20
        letra = 'C';
    case 21
        letra = 'K';
    case 22
        letra = 'E';
      
    otherwise
        letra = 99;
end    
end
%letra  = dni(23);

Burbuja en java



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Burbuja {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("ingrese numero de datos a ingresar: ");
int tam = Integer.parseInt(in.readLine());
int arr[] = new int[tam];
int j = 0;
for (int i = 0; i < arr.length; i++) {
j+=1;
System.out.println("Elemento "+j+":");
arr[i]=Integer.parseInt(in.readLine());
}
OrdenarBurbuja2(arr);
imprimir(arr);
}
public static void OrdenarBurbuja(int[] vector){
for (int i = 0; i < vector.length-1; i++) {
for (int j = 0; j < vector.length-1; j++) {
if(vector[j+1]<vector[j]){ //de menor a mayor
int tmp = vector[j+1];
vector[j+1]=vector[j];
vector[j]=tmp;
}
}
}
}
public static void OrdenarBurbuja2(int[] vector){
for (int i = 0; i < vector.length; i++) {
for (int j = i+1; j < vector.length; j++) {
if(vector[i]<vector[j]){
int aux = vector[i];
vector[i]=vector[j];
vector[j]=aux;
}
}
}
}
public static void imprimir(int[] vector){
for (int i = 0; i < vector.length-1; i++) {
System.out.print(vector[i]+" ");
}
System.out.println(vector[vector.length-1]);
}
public static void imprimir2(int[] vector){
for (int i = 0; i < vector.length; i++) {
if(i==(vector.length-1)){
System.out.println(vector[i]);
}else{
System.out.print(vector[i]+" ");
}
}
}
}





Ejercicio saltos de caballo

Casilla.java

import java.util.ArrayList;


public class Casilla {
public int tamano;
public int fila;
public int columna;
public Casilla(int tam, int filaSalida, int columnaSalida) {
tamano = tam;
fila = filaSalida;
columna = columnaSalida;
}
public int calcularMinimoSaltosCaballo(Casilla llegada) {
//calcula en numero de movimientos
ArrayList<Casilla> solucionParcial = new ArrayList<Casilla>();
ArrayList<ArrayList<Casilla>> soluciones = new ArrayList<ArrayList<Casilla>>();
return 0;
}
}

Caballo.java


import java.util.ArrayList;
import java.util.Scanner;


public class Caballo {
public static void main(String[] args) {
Scanner lee = new Scanner(System.in);
int tes = lee.nextInt();
for (int i = 0; i < tes; i++) {
int tam = lee.nextInt();
int columnaSalida = lee.nextInt();
int filaSalida = lee.nextInt();
int columnaLlegada = lee.nextInt();
int filaLlegada = lee.nextInt();
Casilla salida= new Casilla(tam,filaSalida,columnaSalida);
Casilla llegada = new Casilla(tam, filaLlegada, columnaLlegada);
ArrayList<Casilla> visitadas = new ArrayList<Casilla>();
int N_SOLS = salida.calcularMinimoSaltosCaballo(llegada);
vueltaAtrasSaltosCaballo()
System.out.println(N_SOLS);
}
}
}


Descargar

Notificaciones con sonido, led y vibración en Android

Llamada al método:

NotificacionNueva("Mensaje","Mensaje2", "4", "");

Método:


public void NotificacionNueva(String titulo, String texto, String info, String tick){

    long[] pattern = new long[]{1000,500,1000};
    Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(Main.this)
                    .setSmallIcon(android.R.drawable.stat_sys_warning)
                    .setLargeIcon((((BitmapDrawable) getResources()
                            .getDrawable(R.mipmap.ic_launcher)).getBitmap()))
                    .setContentTitle(titulo)
                    .setContentText(texto)
                    .setContentInfo(info)
                    .setTicker(tick)
                    .setVibrate(pattern)
                    .setLights(Color.RED, 1, 0)
                    .setSound(defaultSound);

    Intent notIntent =
            new Intent(Main.this, Main.class);

    PendingIntent contIntent =
            PendingIntent.getActivity(
                    Main.this, 0, notIntent, 0);

    mBuilder.setContentIntent(contIntent);

    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mNotificationManager.notify(1, mBuilder.build());
}