Is there any method to swap and reverse at the same time? Let's me explain:
If i have, for example, ten integers: 1 2 3 4 5 6 7 8 9 10, now i want to reverse from 6 to 10, with result: 1 2 3 4 5 10 9 8 7 6, and now from 8 to 6, with result: 1 2 3 4 5 10 9 6 7 8, and again and again.
I tried to split into two arrays, reverse one and join both of them:
List<Integer> listaFinal = new ArrayList<Integer>();
for (int i = 0; i < vueltasDar; i++) {
int b = 1;
int resta = intTortitas.length - intVueltas[b];
List<Integer> crawl_list1 = arrayTortitasList.subList(0, resta);
List<Integer> crawl_list2 = arrayTortitasList.subList(
resta + 1, intTortitas.length - 1);
Collections.reverse(crawl_list2);
listaFinal.addAll(crawl_list1);
listaFinal.addAll(crawl_list2);
b++;
}
But it doesn't work.
Thank you very much
Update: So... the final code. Thank you. This code allows a input of numbers finished with a -1 and in the next input you can put a number of inputs and then the reversing numbers.
Input example:
5 4 3 2 1 -1
0
5 4 3 2 1 -1
2 3 2
5 4 3 2 1 -1
1 5
-1
0
Output example:
1
2
5
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
public class pancake {
public static void main(String[] args) throws NumberFormatException,
IOException {
boolean corriendo = true;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while (corriendo) {
String tortitas = br.readLine();
if (tortitas.equals("0")) {
corriendo = false;
break;
}
String vueltas = br.readLine();
String[] tortitasArray = tortitas.split(" ");
int[] intTortitas = new int[tortitasArray.length];
for (int i = 0; i < tortitasArray.length; i++) {
intTortitas[i] = Integer.parseInt(tortitasArray[i]);
}
String[] vueltasArray = vueltas.split(" ");
int[] intVueltas = new int[vueltasArray.length];
for (int i = 0; i < vueltasArray.length; i++) {
intVueltas[i] = Integer.parseInt(vueltasArray[i]);
}
int[] arrayTortitas = Arrays.copyOf(intTortitas,
intTortitas.length - 1);
int vueltasDar = intVueltas[0];
ArrayList<Integer> arrayTortitasList = new ArrayList<>();
for (int i = 0; i < intTortitas.length - 1; i++) {
arrayTortitasList.add(arrayTortitas[i]);
}
if (arrayTortitas.length > 0) {
for (int i = 1; i <= vueltasDar; i++) {
reverse(arrayTortitas,
arrayTortitas.length - intVueltas[i],
arrayTortitas.length - 1);
}
}
if (arrayTortitas.length < 1) {
break;
} else {
int resultado = arrayTortitas[arrayTortitas.length - 1];
System.out.println(resultado);
}
}
}
public static void reverse(int[] arrayTortitas, int a, int b) {
while (a < b) {
int temp = arrayTortitas[a];
arrayTortitas[a] = arrayTortitas[b];
arrayTortitas[b] = temp;
a++;
b--;
}
}
}