Necesito un método que produce la siguiente salida para la entrada dada:
Entrada:
4, 5, 1, 6, 2 | 6, 1, 0 | 9, 3, 1, 5, 2, 0, 4, 6, 7, 8
Salida:
5, 1, 6, 2, 4 | 1, 0, 6 | 3, 1, 5, 2, 0, 4, 6, 7, 8, 9
El programa solicita al usuario que introduzca varias matrices de enteros, separados por '|'. El programa convierte la entrada del usuario desde una cadena a varias matrices de INT. Tiene un método que tiene una matriz de enteros como un parámetro. El método se mueve cada elemento de la matriz una posición a la izquierda; es decir, el valor en el elemento 1 se mueve con el elemento 0, el valor en el elemento 2 se almacena en el elemento 1, y así sucesivamente. Por último, el valor en el primer elemento se mueve en torno a la última posición.
Debe utilizar un bucle for para rotar la matriz. Tenga en cuenta que necesitará para almacenar el valor del elemento 0 en una variable temporal de forma que posteriormente se puede mover en el último elemento una vez que todos los demás elementos han sido movidos.
//Below is my code so far:
public class IntArrayRotation {
public static void main(String[] args) {
IntArrayRotation prog = new IntArrayRotation();
prog.start();
}
//Begin your code here
public void start() {
int[] data = {4, 5, 1, 6, 2};
int[] result = new int[data.length];
for (int i = 0; i < data.length; i++) {
result[(i + (data.length - 1)) % data.length] = data[i];
}
for (int i : result) {
System.out.println(i);
}
}
}
Hacerlo de la siguiente manera:
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter multiple arrays of ints, separated by '|': ");
String input = in.nextLine();
// Split the input on '|'
String[] substrs = input.split("\\|");
StringBuilder sb = new StringBuilder();
for (String substr : substrs) {// Iterate substrs []
// Split each substr on ','
String arr[] = substr.split(",");
// Rotate arr[] as per the requirement
rotate(arr);
// String representation of array e.g. [1, 2, 3]
String str = Arrays.toString(arr);
// Remove '[' from the string representation of array
str = str.substring(1);
// Remove ']' from the string representation of array
str = str.substring(0, str.length() - 1);
// Append the remaining part of the string representation of the array along
// with a '|' at the end
sb.append(str).append("|");
}
sb.deleteCharAt(sb.length() - 1);// Delete the last '|'
System.out.println("After rotation: " + sb);
}
static void rotate(String[] arr) {
// Store the first element
String temp = arr[0];
for (int i = 1; i < arr.length; i++) {
// Shift all elements starting from index 1 to the left by one place
arr[i - 1] = arr[i];
}
// put the first element at the end
arr[arr.length - 1] = temp;
}
}
Un análisis de la muestra:
Enter multiple arrays of ints, separated by '|': 4, 5, 1, 6, 2|6, 1, 0|9, 3, 1, 5, 2, 0, 4, 6, 7, 8
After rotation: 5, 1, 6, 2, 4| 1, 0, 6| 3, 1, 5, 2, 0, 4, 6, 7, 8, 9
He puesto las observaciones requeridas en el código de modo que será más fácil para que usted entienda. Siéntase libre de comentar en caso de cualquier duda / problema.
[Actualizar]
OP: Como usted ha solicitado, he fijado por debajo del mismo programa sin usar una StringBuilder
. Siéntase libre de comentar en caso de cualquier duda / problema.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter multiple arrays of ints, separated by '|': ");
String input = in.nextLine();
// Split the input on '|'
String[] substrs = input.split("\\|");
String result = "";
for (String substr : substrs) {// Iterate substrs []
// Split each substr on ','
String arr[] = substr.split(",");
// Rotate arr[] as per the requirement
rotate(arr);
// String representation of array e.g. [1, 2, 3]
String str = Arrays.toString(arr);
// Remove '[' from the string representation of array
str = str.substring(1);
// Remove ']' from the string representation of array
str = str.substring(0, str.length() - 1);
// Append the remaining part of the string representation of the array along
// with a '|' at the end
result += str + "|";
}
result = result.substring(0, result.length() - 1);// Drop the last '|'
System.out.println("After rotation: " + result);
}
static void rotate(String[] arr) {
// Store the first element
String temp = arr[0];
for (int i = 1; i < arr.length; i++) {
// Shift all elements starting from index 1 to the left by one place
arr[i - 1] = arr[i];
}
// put the first element at the end
arr[arr.length - 1] = temp;
}
}