I want to make a random list from the list, but the conditions are a bit tricky, so I'm thinking about how to implement it.
list [A1,A2,A3,B1,B2,B3,C1,C2,C3]
example
result1 [A1,B1,A2,C1,A3,B2,C2,C3,B3] result2 [C1,B1,B2,A1,A2,B3,C2,A3,C3]
I want to put it with maintain order into a new list.
Is there an algorithmically good way?
CodePudding user response:
If you conceptually arrange your data as a HashMap<Integer, Queue<T>>
, structured as
0: A1,A2,A3
1: B1,B2,B3
2: C1,C2,C3
Then once you've chosen your random number you can just do map.get(number).dequeue()
to get your value
CodePudding user response:
You can do that by randomly arranging them using Collections.shuffle()
and then correcting them using a map.
static List<String> shuffleTrickey(List<String> list) {
List<String> copy = new ArrayList<>(list);
Collections.shuffle(copy);
Map<String, Deque<String>> map = list.stream()
.collect(Collectors.groupingBy(s -> s.substring(0, 1),
Collectors.toCollection(ArrayDeque::new)));
return copy.stream()
.map(s -> map.get(s.substring(0, 1)).pop())
.toList();
}
public static void main(String[] args) {
List<String> list = Arrays.asList("A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3");
List<String> result = shuffleTricky(list);
System.out.println(result);
}
output:
[C1, A1, B1, C2, B2, B3, A2, C3, A3]
Elements with the same first letter will remain in order after shuffling.