What is the best way to copy / populate a large array with a smaller array in C #?

I have a large int [] array and a much smaller int [] array. I want to fill a large array with values ​​from a small array, repeating copying a small array into a large array until it is full (so large [0] = large [13] = large [26] ... = small [0 ] etc.). I already have a simple method:

int iSource = 0;
for (int i = 0; i < destArray.Length; i++)
{
    if (iSource >= sourceArray.Length)
    {
        iSource = 0; // reset if at end of source
    }
    destArray[i] = sourceArray[iSource++];
}

But I need something more elegant and hopefully faster.

+3
source share
3 answers

Interestingly, the winning answer is the slowest with the original array provided!

The solution I was going to offer was

for (int i = 0; i < destArray.Length; i++)
{
    destArray[i] = sourceArray[i%sourceArray.Length];
}

perf 100000 , , , .

array copy 164ms      (Nelson LaQuet code) 
assign copy 77ms      (MusiGenesis code)
assign mod copy 161ms (headsling code)
+2

Array.Copy(), .

if (sourceArray.Length == 0) return; // don't get caught in infinite loop

int idx = 0;

while ((idx + sourceArray.Length) < destArray.Length) {
    Array.Copy( sourceArray, 0, destArray, idx, sourceArray.Length);

    idx += sourceArray.Length;
}

Array.Copy( sourceArray, 0, destArray, idx, destArray.Length - idx);
+2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Temp
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
            int[] array2 = new int[213];

            for (int i = 0; i < array2.Length; i += array.Length)
            {
                int length = array.Length;
                if ((i + array.Length) >= array2.Length)
                    length = array2.Length - i;
                Array.Copy(array, 0, array2, i, length);
            }

            int count = 0;
            foreach (int i in array2)
            {
                Console.Write(i.ToString() + " " + (count++).ToString() + "\n");
            }

            Console.Read();
        }
    }
}

:)

EDIT An error was found where, if they were not divided by each other, it would have crashed. Fixed:)

+2
source

Source: https://habr.com/ru/post/1698132/


All Articles