DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Unique Random Array

12.15.2005
| 12149 views |
  • submit to reddit
        // 无���机数组

import java.util.Random;
public class Util
{
 private static Random rd = null;
 
  public static int[] random(int[] src)
 {
    if(src == null){
   return null; 
  }
  
  rd = new Random();
   int[] tmp = new int[src.length];
  
  int num = src.length;
  
 
  int index;

  for(int i = 0;i < src.length;i++)
  {
  
   index = Math.abs(rd.nextInt()) % num;
    tmp[i] = src[index];
      src[index] = src[num - 1];
      num--;
  }
  return tmp;
 }
 
 public static void main(String[] args)
 {
  int[] test = {1,2,3,4,5,6,7,8,9};
  int a[] = random(test);
  
  for(int i = 0;i < a.length;i++){
   System.out.println(a[i]); 
  } 
 }
    

Comments

Snippets Manager replied on Tue, 2007/06/05 - 11:43am

Math.abs(rd.nextInt()) % num should be written as rd.nextInt(num)