Ver Mensaje Individual
  #2 (permalink)  
Antiguo 17/06/2007, 19:03
picaporte
 
Fecha de Ingreso: noviembre-2003
Mensajes: 59
Antigüedad: 20 años, 5 meses
Puntos: 0
Re: Rellenar array con numeros aleatorios y sin repetir

Genera numeros random (n) sin repetirse.

Código:
/*
 * GeneraRandom31.java
 * 
 * Created on 17-06-2007, 20:57:49 PM
 * 
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package Prueba;
import java.util.Random;
import java.util.Arrays;

/**
 *
 * @author Picaporte
 */
public class GeneraRandom {
   

    
    public  static void main(String[] args){
         
        int n=31;  //numeros aleatorios
       int k=n;  //auxiliar;
        int[] numeros=new int[n];
        int[] resultado=new int[n];
        Random rnd=new Random();
        int res;
        
        
        //se rellena una matriz ordenada del 1 al 31(1..n)
        for(int i=0;i<n;i++){
            numeros[i]=i+1;
        }
        
        for(int i=0;i<n;i++){
            res=rnd.nextInt(k);            
            resultado[i]=numeros[res];
            numeros[res]=numeros[k-1];
            k--;
            
        }
         //se imprime el resultado;
        System.out.println("El resultado de la matriz es:");
        for(int i=0;i<n;i++){
        System.out.println(resultado[i]);
        }
   }
}
Saludos