griplur
griplur

Reputation: 15

Reverse3 ArrayList

given an Array List with the values [10, 13, 2, 8, 7, 90, -1, 2]. I have to create a method that will reverse each successive sequence of 3 values within said list. For example (10, 13, 2) will become (2,13 10) and the (8, 7, 90) will become (90,7,8) However, it will not print out numbers that aren't part of a sequence of 3. So far this is what I have:

public static ArrayList<Integer> reverse3(ArrayList<Integer> list) {
    ArrayList<Integer> newList = new ArrayList<Integer>();

    for(int i = 0; i <list.size()-1; i++){
        for(int j = list.size()-1; j >= 0 ; j--){
            newList.add(list.get(j)); 
    }
}

    return newList;

I'm having issues getting this to work properly. The output reverses the sequences of three but -1 and 2 are printed as well.

Upvotes: 0

Views: 222

Answers (4)

Dima
Dima

Reputation: 40500

Since it looks like it's "do my homework for free" day today, for extra credit, write it in scala:

list
  .grouped(3)
  .map(_.reverse)
  .flatten
  .toList

Upvotes: 1

sprinter
sprinter

Reputation: 27956

It sounds like all you really need to do is to swap 1 and 3, 2 and 4 etc. So:

for (int i = 0; i < list.size(); i += 3) {
    Collections.swap(list, i, i + 2);
    for (int j = i; j < i + 3; j++)
        System.out.println(list.get(j) + " ");
}

Or you could just print them out without even swapping the items:

for (int i = 0; i < list.size(); i += 3) {
    for (int j = i + 2; j >= i; j--)
        System.out.println(list.get(j) + " ");
}

And here's a solution using sublist and Java 8 streams:

IntStream.range(0, list.size() / 3)
    .mapToObj(n -> list.sublist(n, n + 3))
    .map(Collections::reverse)
    .flatMap(List::stream)
    .forEach(System.out::println); 

Upvotes: 2

Krasimir Stoev
Krasimir Stoev

Reputation: 1754

This is the code you need:

public static ArrayList<Integer> reverse3(List<Integer> list) {

    ArrayList<Integer> newList = new ArrayList<Integer>();

    for (int i = 0; i < list.size(); i+=3) {
        for (int j = i+2; j >= i && j < list.size(); j--) {
            newList.add(list.get(j));
        }
    }
    return newList;
}

This is a demo: public static void main(String[] args) {

    List<Integer> list = Arrays.asList(10, 13, 2, 8, 7, 90, -1, 2);
    System.out.println(list);
    System.out.println(reverse3(list));
}

Input: [10, 13, 2, 8, 7, 90, -1, 2]

Results: [2, 13, 10, 90, 7, 8]

Upvotes: 0

Frank Puffer
Frank Puffer

Reputation: 8215

Something like that should do it:

for( int i = 1; i < list.size()-1; i+=3 ) {
    int tmp = list.get(i+1);
    list.set(i+1, list.get(i-1));
    list.set(i-1, tmp);
}

Upvotes: 0

Related Questions