Sunday, April 28, 2019

Shuffle Array or ArrayList Without Using Collections



Shuffle ArrayList Without Using Collections:

package com.queue;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class ShuffleListWithoutCollections {

 public static void main(String[] args) {
  List list = new ArrayList();
  list.add(100);
  list.add(50);
  list.add(125);
  list.add(90);
  list.add(80);
  list.add(120);
  list.add(20);
  System.out.println("Before shuffling : " + list);
  shuffleList(list);
  System.out.println("After shuffling : " + list);
 }

 private static void shuffleList(List list) {
  /*list size*/
  int listSize = list.size();
  
  /*Initialize random number generator*/
  Random random = new Random();
  for (int i = 0; i < listSize; i++) {
   
   /*Get element from list at index i*/
   int currentElement = (Integer) list.get(i);
   
   /*Generate a random index number within the list size range*/ 
   int randomIndex = i + random.nextInt(listSize - i);
   
   /*set/replace the element at current index with the element of random index*/
   list.set(i, list.get(randomIndex));
   
   /*set/replace the element at random index with the element at current index*/
   list.set(randomIndex, currentElement);
  }
 }
}

Shuffle Array Without Using Collections:

package com.queue;
import java.util.Arrays;
import java.util.Random;

public class ShuffleArrayWithoutCollections {

 public static void main(String[] args) {
  int[] list = new int[7];
  list[0]=100;
  list[1]=50;
  list[2]=125;
  list[3]=90;
  list[4]=80;
  list[5]=120;
  list[6]=20;
  System.out.println("Before shuffling : " + Arrays.toString(list));
  shuffleList(list);
  System.out.println("After shuffling : " + Arrays.toString(list));
 }

 private static void shuffleList(int[] list) {
  /*list size*/
  int listSize = list.length;
  
  /*Initialize random number generator*/
  Random random = new Random();
  for (int i = 0; i < listSize; i++) {
   
   /*Get element from list at index i*/
   int currentElement = list[i];
   
   /*Generate a random index number within the list size range*/ 
   int randomIndex = i + random.nextInt(listSize - i);
   
   /*set/replace the element at current index with the element of random index*/
   list[i] =list[randomIndex];
   
   /*set/replace the element at random index with the element at current index*/
   list[randomIndex] = currentElement;
  }
 }
}

No comments:

Post a Comment