Thursday, March 24, 2005

Shuffle

Considering , i have not been posting a lot , does it make me busy perhpas not but my lethargy wins over me again .

Good link for shuffle
1. http://www.cs.princeton.edu/introcs/25array/

public class Shuffle {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String[] a = new String[N];

// read in data
for (int i = 0; i < N; i++) {
a[i] = StdIn.readString();
}

// shuffle
for (int i = 0; i < N; i++) {
int r = (int) (Math.random() * (i+1)); // int between 0 and i
String swap = a[r];
a[r] = a[i];
a[i] = swap;
}

// print permutation
for (int i = 0; i < N; i++)
System.out.println(a[i]);

}
}

No comments: