Answer the question
In order to leave comments, you need to log in
Java how to do a circular shift of a LinkedList?
It is required to form a HashMap or SortedMap from a list cyclically shifted for each key.
The actual list:
LinkedList<Character> line = new LinkedList<>(Arrays.asList(' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E',
'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'!', ',', '.', ':', ';', '-'));
Map<Character, LinkedList<Character>> square = new TreeMap<>();
private void buildSquare() {
int i = 0;
LinkedList<Character> tmp = new LinkedList<>(line);
for(Character elem: line) {
Collections.rotate(tmp, 1);
square.put(elem, tmp);
i += 1;
}
}
Answer the question
In order to leave comments, you need to log in
Here you have two errors:
1. Collections.rotate(tmp, 1); // here, apparently, there should be i, instead of one. So you have i incremented, but not used anywhere.
2. LinkedList tmp = new LinkedList<>(line); // You guessed right to make a copy of the original sheet, but you need to create it every time inside the loop. In your implementation, the same object always gets into all Values of the resulting Map (because the reference is the same), it is iterated, and, as a result, goes full circle.
3*. I'm not sure, but it seems to need to be shifted the other way.
So the method will look like this:
private static void buildSquare() {
int i = 0;
for(Character elem: line) {
LinkedList<Character> tmp = new LinkedList<>(line);
Collections.rotate(tmp, i++); // i инкрементируется сразу в месте использования. (Попробуйте i--, так, кажется, будет правильнее)
square.put(elem, tmp);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question