Dividir Array en subarreglos de tamaño K llenando elementos

Dado un arreglo nums[ ] de tamaño N , la tarea es dividir el arreglo en grupos de tamaño K usando el siguiente procedimiento:

  • El primer grupo consta de los primeros K elementos del arreglo, el segundo grupo consta del siguiente K elemento del arreglo, y así sucesivamente. Cada elemento puede ser parte de exactamente un grupo.
  • Para el último grupo, si a la array no le quedan K elementos, use 0 para completar el grupo.

Ejemplos:

Entrada: nums[ ] = {1,2,3,4,5,6,7,8}, K = 4
Salida: [[1, 2, 3, 4] [ 5, 6, 7, 8]]
Explicación :
Los primeros 4 elementos [1, 2, 3, 4] forman el primer grupo.
Los siguientes 4 elementos [5, 6, 7, 8] forman el segundo grupo.
Dado que todos los grupos pueden llenarse completamente con elementos de la array, no es necesario usar 0.

Entrada: nums[ ] = {3,2,5,7,9,1,3,5,7}, K = 2
Salida: [[3, 2] ,[5, 7], [9,1], [3, 5], [7, 0]]
Explicación: Al último grupo le faltaba uno para tener el tamaño 2. Por lo tanto, se usa un 0.

 

Enfoque: Este es un problema relacionado con la implementación fácil. Siga los pasos que se mencionan a continuación para resolver el problema:

  • Mantenga un vector temporal que represente cada grupo en la string.
  • Si el índice i+1 es divisible por K entonces se puede concluir que el grupo ha terminado con este i-ésimo índice.
  • Empuje la temperatura en el vector ans si el grupo termina.
  • Compruebe si el último grupo tiene una talla K o no.
  • Si no es igual, agregue K – (len+1) relleno de tamaño con 0.

A continuación se muestra la implementación del enfoque anterior: 

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to split the array
vector<vector<int> > divideArray(int nums[],
                                 int K, int N)
{
    vector<vector<int> > ans;
    vector<int> temp;
    for (int i = 0; i < N; i++) {
        temp.push_back(nums[i]);
        if(((i+1)%K)==0) {
            ans.push_back(temp);
            temp.clear();
        }
    }
     // If last group doesn't have enough
    // elements then add 0 to it
    if (!temp.empty()) {
        int a = temp.size();
        while (a != K) {
            temp.push_back(0);
            a++;
        }
        ans.push_back(temp);
    }
    return ans;
}
 
// Function to print answer
void printArray(vector<vector<int> >& a)
{
    int n = a.size();
      cout << n;
    for (int i = 0; i < n; i++) {
        cout << "[ ";
        for (int j = 0; j < a[i].size(); j++)
            cout << a[i][j] << " ";     
        cout << "]";
    }
}
// Driver Code
int main()
{
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int N = sizeof(nums) / sizeof(nums[0]);
    int K = 4;
    vector<vector<int> > ans
        = divideArray(nums, K, N);
    printArray(ans);
    return 0;
}

Java

// Java program for the above approach
import java.util.ArrayList;
 
class GFG {
 
  // Function to split the array
  static ArrayList<ArrayList<Integer>> divideArray(int nums[], int K, int N) {
    ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> temp = new ArrayList<Integer>();
    for (int i = 0; i < N; i++) {
      temp.add(nums[i]);
      if (((i + 1) % K) == 0) {
        ans.add(temp);
        temp = new ArrayList<Integer>();
      }
    }
    // If last group doesn't have enough
    // elements then add 0 to it
    if (temp.size() != 0) {
      int a = temp.size();
      while (a != K) {
        temp.add(0);
        a++;
      }
      ans.add(temp);
    }
    return ans;
  }
 
  // Function to print answer
  static void printArray(ArrayList<ArrayList<Integer>> a) {
    int n = a.size();
    for (int i = 0; i < n; i++) {
      System.out.print("[ ");
      for (int j = 0; j < a.get(i).size(); j++)
        System.out.print(a.get(i).get(j) + " ");
      System.out.print("]");
    }
  }
 
  // Driver Code
  public static void main(String args[]) {
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    int N = nums.length;
    int K = 4;
    ArrayList<ArrayList<Integer>> ans = divideArray(nums, K, N);
    printArray(ans);
  }
}
 
// This code is contributed by saurabh_jaiswal.

Python3

# python3 program for the above approach
 
# Function to split the array
def divideArray(nums, K, N):
 
    ans = []
    temp = []
    for i in range(0, N):
        temp.append(nums[i])
        if(((i+1) % K) == 0):
            ans.append(temp.copy())
            temp.clear()
 
    # If last group doesn't have enough
    # elements then add 0 to it
    if (len(temp) != 0):
        a = len(temp)
        while (a != K):
            temp.append(0)
            a += 1
 
        ans.append(temp)
 
    return ans
 
# Function to print answer
def printArray(a):
 
    n = len(a)
    for i in range(0, n):
        print("[ ", end="")
        for j in range(0, len(a[i])):
            print(a[i][j], end=" ")
        print("]", end="")
 
# Driver Code
if __name__ == "__main__":
 
    nums = [1, 2, 3, 4, 5, 6, 7, 8]
    N = len(nums)
    K = 4
    ans = divideArray(nums, K, N)
    printArray(ans)
 
# This code is contributed by rakeshsahni

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
  // Function to split the array
  static List<List<int> > divideArray(int[] nums, int K,
                                      int N)
  {
    List<List<int> > ans = new List<List<int> >();
    ;
    List<int> temp = new List<int>();
    for (int i = 0; i < N; i++) {
      temp.Add(nums[i]);
      if (((i + 1) % K) == 0) {
        ans.Add(temp);
        temp = new List<int>();
      }
    }
    // If last group doesn't have enough
    // elements then add 0 to it
    if (temp.Count != 0) {
      int a = temp.Count;
      while (a != K) {
        temp.Add(0);
        a++;
      }
      ans.Add(temp);
    }
    return ans;
  }
 
  // Function to print answer
  static void printArray(List<List<int> > a)
  {
    int n = a.Count;
    for (int i = 0; i < n; i++) {
      Console.Write("[ ");
      for (int j = 0; j < a[i].Count; j++)
        Console.Write(a[i][j] + " ");
      Console.Write("]");
    }
  }
   
  // Driver Code
  public static int Main()
  {
    int[] nums = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
    int N = nums.Length;
    int K = 4;
    List<List<int> > ans = divideArray(nums, K, N);
    printArray(ans);
    return 0;
  }
}
 
// This code is contributed by Taranpreet

Javascript

<script>
       // JavaScript code for the above approach
 
       // Function to split the array
       function divideArray(nums, K, N) {
           let ans = [];
           let temp = [];
           for (let i = 0; i < N; i++) {
               temp.push(nums[i]);
               if (((i + 1) % K) == 0) {
                   ans.push(temp);
                   temp = [];
               }
           }
            
           // If last group doesn't have enough
           // elements then add 0 to it
           if (temp.length != 0) {
               let a = temp.length;
               while (a != K) {
                   temp.push(0);
                   a++;
               }
               ans.push(temp);
           }
           return ans;
       }
 
       // Function to print answer
       function printArray(a) {
           let n = a.length;
           for (let i = 0; i < n; i++) {
               document.write("[ ");
               for (let j = 0; j < a[i].length; j++)
                   document.write(a[i][j] + " ");
               document.write("]");
           }
       }
        
       // Driver Code
       let nums = [1, 2, 3, 4, 5, 6, 7, 8];
       let N = nums.length;
       let K = 4;
       let ans = divideArray(nums, K, N);
       printArray(ans);
 
        // This code is contributed by Potta Lokesh
   </script>
Producción

[ 1 2 3 4 ][ 5 6 7 8 ]

Complejidad temporal: O(N) 
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por sauarbhyadav y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *