Estoy intentando dividir la matriz en un tamaño de fragmento determinado. Se me ocurrió una solución, pero ¿se puede simplificar más?

programación


Dada la matriz y el tamaño del fragmento. Tengo que producir el resultado deseado.
matriz = [1,2,3,4,5]

tamaño del trozo = 1
salida deseada [1] [2] [3] [4] [5]

Lo que he probado:

He intentado usar IntStream

Java
public static List<int[]> chunk(int[] input, int chunkSize) {
        return IntStream.iterate(0, i -> i + chunkSize)
                .limit((long) Math.ceil((double) input.length / chunkSize))
                .mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
                .collect(Collectors.toList());//how to fix this line error on new
    }

La llamada a la función que estoy haciendo en el método principal es la siguiente:
Lista lista = trozo(original, tamaño dividido);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));

Solución 1

Podría haber varias formas de hacerlo. Si no hay problema de espacio, preferiría Arrays.copyOfRange()

En él, el copyOfRange() crea una nueva matriz del mismo tipo que la matriz original y contiene los elementos del rango especificado de la matriz original en una nueva matriz.

Sintaxis:

Java
public static T[] copyOfRange(T[] original, int from, int to)

// original – the array from which a range is to be copied
// from – the initial index of the range to be copied, inclusive
// to – the final index of the range to be copied, exclusive

Más detalles: Método Java.util.Arrays.copyOfRange()[^]

Uso de ejemplo:

Java
int[] arr1 = new int[] {15, 10, 45, 55};
int chunk = 2; // provided as input
for(int i=0; i<arr1.length; i+=chunk){
    System.out.println(Arrays.toString(Arrays.copyOfRange(arr1, i, Math.min(arr1.length,i+chunk))));
}

Solución 2

/*************************************************** *******************************
Bienvenido a BGF en línea.
Codifique, compile, ejecute y depure en línea desde cualquier parte del mundo.
************************************************** *******************************/
importar java.util.*;

clase principal
{
principal vacío estático público (cadena[] argumentos) {
En t[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10};
int tamaño dividido = 3;

/* Rendimiento esperado
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]

*/

Lista lista = splitArray(original, splitSize);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));
}

Lista estática pública dividirArray(int[] matriz, int tamaño dividido) {
intk=0;
ListaMatriz resultado=nueva ArrayList();
En t[] arr=nulo;
int longitud=matriz.longitud;
int tamaño=tamaño dividido;
for(int i=0;i “arr=”nuevo” int[size];
=”” }
=”” arr[k]=”matriz[i];
“k++;
=””>=tamaño dividido || i==matriz.longitud-1){
k=0;
resultado.add(arr);
longitud=longitud-divisiónTamaño;
si (longitud

コメント

タイトルとURLをコピーしました