R
R
Roman Tomchenko2020-10-10 21:32:08
Java
Roman Tomchenko, 2020-10-10 21:32:08

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',
            '!', ',', '.', ':', ';', '-'));


Hashmap:
Map<Character, LinkedList<Character>> square = new TreeMap<>();


The function that fills the map:
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;
        }
    }


Actually, it is required that the map for each key contains a list shifted by 1 element to the left.
However, the result is a complete lack of shift.
For the second day I can not figure it out.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2020-10-10
@Widestrip

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 question

Ask a Question

731 491 924 answers to any question