0

How to shuffle only some elements in ArrayList and fix the remaining elements I have an ArrayList which contains locked and unlocked values I want to shuffle only the unlocked elements and fix the locked elements.

I have followed this Java: Exclude array index in shuffle now my unlocked array list get shuffled but i have noticed that some elements get their same index while shuffling my requirement is that every element has to get different index in array list after shuffling i.e original array list element index must not match with shuffled array list elements index

Community
  • 1
  • 1
  • 1
    This post might help: http://stackoverflow.com/questions/19358631/java-exclude-array-index-in-shuffle – Mike M. Jul 16 '14 at 05:20
  • thanks that linked helped me but i want to Shuffle arraylist, that no item remains in its original position – user3840825 Jul 17 '14 at 04:27
  • I don't understand. Your question says that you "want to shuffle only the unlocked elements and fix the locked elements." If you want to shuffle so "that no item remains in its original position", use `Collections.shuffle()` on the whole list. – Mike M. Jul 17 '14 at 04:31
  • i want to shuffle only the unlocked elements and fix the locked elements but shuffling of unlocked elements must be done in such a way that they must not remain in its original position even after multiple shuffles for eg if A's original position is 2 after shuffling it must not get 2nd position even after multiple shuffles – user3840825 Jul 17 '14 at 04:45
  • You should edit your question to specify that requirement. You might also specify what should happen when only one element is unlocked. – Mike M. Jul 17 '14 at 04:50
  • Can you describe your situation? Specifically, why must every element have a different index? Would a mapping suffice in lieu of a shuffle? – Mike M. Jul 17 '14 at 07:26

1 Answers1

0

Assuming that you need to keep the position (index) of the locked items fixed, you can try this. First you save all the unlockedItems in separate ArrayList. Assuming your original list is items

ArrayList<T> unLockedItems = new ArrayList<T>();
for(T item : items)
{
   if(!item.isLocked)
      unLockedItems.add(item);
}

Now you have list of unlocked items;

Then shuffle the unlocked items

Collections.shuffle(unLockedItems)

Then you have replace the initial unlocked items with shuffled unlocked items

for(T item : items)
{
   if(!item.isLocked)
   {
      int pos = items.indexOf(item);
      items.remove(pos);
      items.add(pos, unLockedItem.get(O));
      unlockedItem.remove(0);
    }

}
Abhishek Batra
  • 1,539
  • 1
  • 18
  • 45