Mostafa_M
Mostafa_M

Reputation: 105

Insert all elements of a 2-dimensional Array into a 1-dimensional Array

Hello Dear Community,

I'm working with c++ arrays (static and dynamic ones). My static array A1 has a [30][30] size and my dynamic array A2 is [30*30] long. What I want to do is to copy A1 into A2.

The content of the arrays A1 & A2 is filled with random integer numbers between 0 and 9.

Here is my previous solution approach:(I think so far I made the copy into A2, but I can't figure out, how to return array A2. )

int main() {
    //Array 2-Dimensional
    int A1[30][30] = { 0 };
    int *A2 = new int[30*30];
    int x, j, z;

    for (x = 0; x < 30; x++) {
        for (j = 0; j < 30; j++) {
            A1[x][j] = rand() % 10;
            printf("%d ", A1[x][j]);
            for (z = 0; z < 30 * 30; z++) {
                A2[z] = A1[x][j]; 
            }
        }
        printf("\n");           
    }
    system("Pause");
    return 0;
}

Upvotes: 1

Views: 72

Answers (2)

Swordfish
Swordfish

Reputation: 13144

Wait. Which language?? C++?

#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    constexpr std::size_t num_elements{ 30 };
    constexpr std::size_t max_idx{ num_elements - 1 };

    std::array<std::array<int, num_elements>, num_elements> A1;
    std::vector<int> A2(num_elements * num_elements);

    std::srand(static_cast<unsigned>(std::time(nullptr)));
    std::generate(&A1[0][0], &A1[max_idx][max_idx] + 1, [](){ return rand() % 10; });

    for (auto const &row : A1) {
        for (auto const &col : row)
            std::cout << col << ' ';
        std::cout.put('\n');
    }

    std::copy(&A1[0][0], &A1[max_idx][max_idx] + 1, A2.begin());

    for (auto const &i : A2)
        std::cout << i << ' ';
}

Upvotes: 0

HugoTeixeira
HugoTeixeira

Reputation: 4884

You don't need three nested loops to make this happen. The trick is to calculate the index of the dynamic array using the two indices of the static array.

Here is a complete example on how to do this in C++ with just two nested loops:

#include <iostream>

const constexpr static int SIZE = 30;

int main() {
    int A1[SIZE][SIZE] = { 0 };
    int *A2 = new int[SIZE * SIZE];

    for (int row = 0; row < SIZE; row++) {
        for (int col = 0; col < SIZE; col++) {
            A1[row][col] = rand() % 10;
            std::cout << A1[row][col] << ' ';

            // calculates the index for A2
            int index = row * SIZE + col;
            A2[index] = A1[row][col];
        }
        std::cout << '\n';
    }

    // A simple loop just to print the contents of A2
    for (int i = 0; i < SIZE * SIZE; i++) {
        std::cout << A2[i] << ' ';
    }

    // don't forget to deallocate A2
    delete[] A2;

    return 0;
}

Upvotes: 1

Related Questions