我有一个大的int []数组和一个小得多的int []数组。我想用小数组中的值填充大数组,通过重复将小数组复制到大数组中,直到它被填满(所以large [0] = large [13] = large [26] ... =小[0]等)。我已经有一个简单的方法:
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++];
}
发布于 2018-06-26 16:01:30
我要提出的解决办法是
for (int i = 0; i < destArray.Length; i++)
{
destArray[i] = sourceArray[i%sourceArray.Length];
}
这是我的小测试应用程序的输出
array copy 164ms (Nelson LaQuet's code)
assign copy 77ms (MusiGenesis code)
assign mod copy 161ms (headsling's code)
发布于 2018-06-26 17:21:24
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();
}
}
}
https://stackoverflow.com/questions/-100000349
复制相似问题