2

How Can I Shuffle below array

String[] firstName =["a","b","c","d","e"];
String[] lastName =["p","q","r","s","t"];
String[] salary =["10","20","30","40",50"];
String[] phoneNo= ["1","2","3","4","5"];

after shuffling the array i need result like

String[] firstName =["d","b","e","c","a"];
String[] lastName =["s","q","t","r","p"];
String[] salary =["40","20","50","30",10"];
String[] phoneNo= ["4","2","5","3","1"];

means for example if index of "a" from firstName Changes from 0 to 4, respective index of "p","10","1" to be changed from 0 to 4..

  • 1
    @Sabik JavaScript is not Java. – MikeCAT Mar 05 '16 at 09:12
  • Did you begin with something or are you hoping someone will dump you the code? – Yassin Hajaj Mar 05 '16 at 09:13
  • One of the best ways to accomplish this would be to create a custom object with those 4 String fields. Then you can have a constructor such as `MyObject(String fN, String lN, String sal, String pN)` and use that to set initial values. Then create an array of `MyObject` – Calvin P. Mar 05 '16 at 09:14
  • 1
    Sorry, my mistake, see: http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array http://stackoverflow.com/questions/4228975/how-to-randomize-arraylist – Sabik Mar 05 '16 at 09:18

2 Answers2

10

If you task isn’t implementation of the snuffle algorithm you can use standard java.util.Collections#shuffle method:

String[] firstName = new String[] {"a","b","c","d","e"};
List<String> strList = Arrays.asList(firstName);
Collections.shuffle(strList);
firstName = strList.toArray(new String[strList.size()]);
Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41
2

just create an array (or list) which has the values

Integer[] arr = new Integer[firstName.length];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i;
}

Collections.shuffle(Arrays.asList(arr));

and then just create a new string array to move the values into

string[] newFirstName = new string[arr.length]();
for(int i=0; i < arr.length; i++)
{
    newFirstName[i] = firstName[arr[i]];
    //etc ....
}
Grant Nilsson
  • 565
  • 5
  • 18