K
K
K A2019-02-27 11:14:13
Arrays
K A, 2019-02-27 11:14:13

Is the array copy logic correct?

The task is to create a two-dimensional array with 3 rows and 5 columns, then transfer the values ​​​​to a new array with 5 columns and 3 rows.
The code itself:

using System;

class TwoArray
{
    static void Main()
    {
        int[,] numbs = new int[3, 5];
        Random rand = new Random();

        int[] numb = new int[numbs.Length];

        for (int i = 0, z = 0; i < numbs.GetLength(0); i++)
        {
            for (int j = 0; j < numbs.GetLength(1); j++, z++)
            {
                numbs[i, j] = rand.Next(0, 100);
                Console.Write(numbs[i, j] + " ");
                numb[z] = numbs[i, j];
            }
            Console.WriteLine();
        }
        Console.WriteLine();

        int[,] numbs2 = new int[5, 3];

        for (int i = 0, z = 0; i < numbs2.GetLength(0); i++)
        {
            for (int j = 0; j < numbs2.GetLength(1); j++, z++)
            {
                numbs2[i, j] = numb[z];
                Console.Write(numbs2[i, j] + " ");
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }
}

I first copied from the first two-dimensional array to a one-dimensional one, then from the one-dimensional one I filled the second two-dimensional array.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Foggy Finder, 2019-02-27
@FoggyFinder

If you need to preserve the order of the elements, then just use the ready- made Array.Copy method:
Otherwise, you can use loops.

for (int i = 0, z = 0; i < numbs2.GetLength(0); i++)
{
    for (int j = 0; j < numbs2.GetLength(1); j++)
    {
        numbs2[i, j] = numbs[j, i];
        Console.Write(numbs2[i, j] + " ");
    }
Console.WriteLine();
}

K
K A, 2019-02-28
@russrage

And if so:

using System;

class TwoArray
{
    static void Main()
    {
        int[,] numbs = new int[3, 5];
        Random rand = new Random();

        int[,] numbs2 = new int[5, 3];

        for (int i = 0, z = 0; i < numbs.GetLength(0); i++)
        {
            for (int j = 0; j < numbs.GetLength(1); j++, z++)
            {
                numbs[i, j] = rand.Next(0, 100);
                Console.Write(numbs[i, j] + " ");
            }
            Console.WriteLine();
        }
        Console.WriteLine();
        
        for (int i = 0; i < numbs2.GetLength(0); i++)
        {
            for (int j = 0; j < numbs2.GetLength(1); j++)
            {
                numbs2[i, j] = numbs[j, i];
                Console.Write(numbs2[i, j] + " ");
            }
            Console.WriteLine();
        }
        Console.ReadKey();
    }
}

That is no exception

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question