I am preparing a New Year's party with friends, we decided to play a secret Santa. But before the new year we are not meeting, so the draw is remote. I wanted to play around with the code, it came out like this:
The goal is to randomly scatter someone to whom a gift is presented, so that the situation that a person gives to himself does not come out)
Embarrassed by the presence of a crutch
if (j + 1 == guests.get(j)) What do you think can be improved? A concise, simple, not hanging on a large number of participants, performing its task algorithm is expected.
import java.util.*; class Rextester { public static void main(String args[]) { int GUESTS_NUMBER = 10; List<Integer> guests = new ArrayList<>(); for (int i = 0; i < GUESTS_NUMBER;) { guests.add(++i); } boolean shuffled = false; outer: while (!shuffled) { Collections.shuffle(guests); shuffled = true; for (int j = 0; j < guests.size(); j++) { if (j + 1 == guests.get(j)) { shuffled = false; continue outer; } } } for (int j = 0; j < guests.size(); j++) System.out.println(j + 1 + " gives a gift to -> " + guests.get(j)); } }