2008-10-10 108 views
3

我有一個大的int []數組和一個小得多的int []數組。我想用小數組中的值填充大數組,通過重複將小數組複製到大數組中,直到它被填滿(所以large [0] = large [13] = large [26] ... =小[0]等)。我已經有一個簡單的方法:在C#中用較小的數組複製/填充大數組的最佳方式是什麼?

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++]; 
} 

但我需要的東西更優雅,並希望更快。

回答

2

有趣的是,獲勝的答案是提供的源數組最慢!

我要提出的解決方案是

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

,但是當我在使用的答題輸入100000次迭代測試PERF比發問循環表現較差。

這裏是我的小測試程序

 
array copy 164ms  (Nelson LaQuet's code) 
assign copy 77ms  (MusiGenesis code) 
assign mod copy 161ms (headsling's 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(); 
     } 
    } 
} 

:)

編輯 發現錯誤:如果他們不是整除被對方就會崩潰。現在修復:)

+0

由於輸出。男孩,這個網站有時候會很有用。 – MusiGenesis 2008-10-10 03:51:18

+0

除非我遺漏了一些東西,否則`i%array.Length`將永遠不會是0以外的任何東西。 – 2008-10-10 04:09:46

相關問題