Last active
March 3, 2017 03:00
-
-
Save charlesreid1/e853efb52ec0a7bc2b9ac4936e379551 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
// This class implements the Fisher-Yates Shuffle Algorithm. | |
// | |
// Author: Charles Reid | |
// Class: CSC 142 | |
// Date: March 2017 | |
public class FisherYates { | |
public static void main(String[] args) { | |
// Create the array | |
int n = 50; | |
double[] z = new double[n]; | |
// Populate the array | |
for(int i=0; i<n; i++) { | |
z[i] = (i+1)*100*Math.PI; | |
} | |
// Before: | |
System.out.println(Arrays.toString(z)); | |
fisherYatesShuffle(z); | |
// After: | |
System.out.println(Arrays.toString(z)); | |
} | |
public static void fisherYatesShuffle(double[] arr) { | |
Random r = new Random(); | |
int n = arr.length; | |
int i = 0; | |
// n = 1 corresponds to swapping next-to-last with last | |
// n > 1 corresponds to having at least two possible choices | |
while( n > 1 ) { | |
n--; | |
i = r.nextInt(n); | |
swap(i,n,arr); | |
} | |
} | |
public static void swap(int i, int j, double[] arr) { | |
double temp = arr[j]; | |
arr[j] = arr[i]; | |
arr[i] = temp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment