Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Manually shuffle the array list

Tags:

java

arraylist

I have an arraylist contains some values that are in an order (correct positions), Now I want to swipe/set/manual shuffle change the values into disorder of the arraylist. Below image can give my idea.Change Array-II to Array-I. To shuffle we can use collection.shuffle(), but here I have a text file, in that text file i wrote a original position as well as current position of the data in the array on to the text file. for example imaging, we have a text file name MyFile.txt, I wrote data in that like this, "original_position~Current_position" for example 0~0 1~2 2~4 3~3 4~1 so, based on the above data i would to shuffle/ set the array.

like image 444
user3285681 Avatar asked Apr 02 '14 11:04

user3285681


1 Answers

Use Collections.shuffle(YOUR_ARRAY_LIST); to do it.

    List<String> ranList = new ArrayList<String>();
    // populate the list
    ranList.add("A");
    ranList.add("B");
    ranList.add("C");
    System.out.println("Initial collection: " + ranList);
    // shuffle the list
    Collections.shuffle(ranList);
    System.out.println("Final collection after shuffle: " + ranList);

The way of approach for manual sorting goes like this:

Read and add your data from file to Map

    private static Map<String, String> readFile(String fileNameWithPath) throws Exception {
    Map<String, String> map = new LinkedHashMap<String, String>();
    File file = new File(fileNameWithPath);
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    String sCurrentLine;
    String[] splitPosition;
    while ((sCurrentLine = bufferedReader.readLine()) != null) {
        splitPosition = sCurrentLine.split("~");
        map.put(splitPosition[0], splitPosition[1]);
    }
    return map;
}

And your main method is like:

   try {
        List<String> list = new ArrayList<String>();
        List<String> customeRandomList = new LinkedList<String>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        list.add("E");
        Map<String, String> map = Test.readFile("D://RandomList.txt");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            customeRandomList.add(list.get(Integer.parseInt(entry.getValue())));
        }
        for (String result : customeRandomList) {
            System.out.println(result);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
like image 161
ashokramcse Avatar answered Oct 02 '22 02:10

ashokramcse