Sunday, 5 January 2020

How to shuffle an array?



Shuffle array using Collections.shuffle
public static void shuffleArray(Character[] charArray) {

	List<Character> chars = Arrays.asList(charArray);

	long seed = System.currentTimeMillis();

	Random rand = new Random(seed);

	Collections.shuffle(chars, rand);

	chars.toArray(charArray);
}


App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class App {

	private static void printArray(Character[] arr) {
		for (Character obj : arr) {
			System.out.print(obj + " ");
		}
		System.out.println();
	}

	public static void shuffleArray(Character[] charArray) {

		List<Character> chars = Arrays.asList(charArray);

		long seed = System.currentTimeMillis();

		Random rand = new Random(seed);

		Collections.shuffle(chars, rand);

		chars.toArray(charArray);
	}

	public static void main(String args[]) {
		Character[] charArray = { 'a', 'b', 'c', 'd', 'e' };

		shuffleArray(charArray);

		printArray(charArray);

	}

}

Shuffle array using Knuth Shuffle algorithm

Following snippet implements Knuth Shuffle Algorithm.
public static void shuffleArray(Character[] charArray) {

	Random random = new Random();
	int length = charArray.length;
	for (int i = length - 1; i > 0; i--) {
		int position = random.nextInt(i);

		char temp = charArray[i];
		charArray[i] = charArray[position];
		charArray[position] = temp;

	}
}


App.java
package com.sample.app;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class App {

	private static void printArray(Character[] arr) {
		for (Character obj : arr) {
			System.out.print(obj + " ");
		}
		System.out.println();
	}

	// Knuth Shuffle Algorithm
	public static void shuffleArray(Character[] charArray) {

		Random random = new Random();
		int length = charArray.length;
		for (int i = length - 1; i > 0; i--) {
			int position = random.nextInt(i);

			char temp = charArray[i];
			charArray[i] = charArray[position];
			charArray[position] = temp;

		}
	}

	public static void main(String args[]) {
		Character[] charArray = { 'a', 'b', 'c', 'd', 'e' };

		shuffleArray(charArray);

		printArray(charArray);

	}

}


You may like

No comments:

Post a Comment