views:

557

answers:

3

I have a large int[] array and a much smaller int[] array. I want to fill up the large array with values from the small array, by repeat copying the small array into the large array until it is full (so that 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.

+2  A: 

Have your loop work using the Array.Copy() overload that lets you copy from one array into the a particular index in the destination array.

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);
Michael Burr
+2  A: 
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 Found bug where if they were not dividable by each other it would crash. Fixed now :)

nlaq
Thanks. Boy, this site can be useful sometimes.
MusiGenesis
Unless I'm missing something, `i % array.Length` will never be anything other than 0.
Michael Burr
hehe, good call. Fixed :)
nlaq
+1  A: 

Interestingly the winning answer is the slowest with the provided source array!

The solution I was going to propose was

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

but when i tested the perf over 100000 iterations using the inputs in the answering question it performed worse than the questioners loop.

here is the output from my little test app

array copy 164ms      (Nelson LaQuet's code) 
assign copy 77ms      (MusiGenesis code)
assign mod copy 161ms (headsling's code)
headsling
Are you saying my original code was the fastest? (I never benchmarked any of these)
MusiGenesis
yes! assign copy (yours) scored 77ms for 1 million iterations. not bad eh?
headsling
Not bad at all. :)
MusiGenesis