如果我有这个整数数组:
int[] columns_index = { 2, 3, 4};
如何根据给定的数量(大小)重复此序列?
例如:
如果我给你4
作为一个大小,那么数组将是
{2,3,4,2}
如果我给你5
作为一个大小,那么数组将是
{2,3,4,2,3}
如果我给你6
作为一个大小,那么数组将是
{2,3,4,2,3,4}
如果我给你7
作为一个大小,那么数组将是
{2,3,4,2,3,4,2}
等等......
答案 0 :(得分:3)
只需使用模运算符迭代columns_index
int input = 7; // change this to user input of whatever it needs to be
int[] numbers = new int[ input ];
for ( int i = 0; i < input; i++ ){
int index = i % ( columns_index.length )
numbers[i] = columns_index[ index ];
}
答案 1 :(得分:3)
public static class Extensions
{
public static T[] Multiply<T>(this T[] array, int length)
{
if ( array == null || array.Length == 0 || length <= array.Length )
return array;
var x = length % array.Length;
var y = length / array.Length;
return Enumerable.Range(1,y)
.SelectMany(c=>array)
.Concat(array.Take(x))
.ToArray();
}
}
答案 2 :(得分:2)
可以使用Linq Repeat()
和Take()
函数来获得结果。
private readonly static int[] Source = { 2, 3, 4 };
[TestMethod]
public void TestMethod1() {
Assert.IsTrue(new []{ 2, 3, 4, 2}.SequenceEqual(GetSequence(Source,4)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3 }.SequenceEqual(GetSequence(Source, 5)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3, 4 }.SequenceEqual(GetSequence(Source, 6)));
Assert.IsTrue(new[] { 2, 3, 4, 2, 3, 4, 2 }.SequenceEqual(GetSequence(Source, 7)));
}
private static int[] GetSequence(IEnumerable<int> src, int count) {
var srcRepeatCount = count / src.Count() + 1;
return Enumerable.Repeat(src, srcRepeatCount).SelectMany(itm => itm).Take(count).ToArray();
}
答案 3 :(得分:1)
如果您希望将使用all in columns index的部分与其余部分
分开 int input = 1000001;
int[] columns_index = { 2, 3, 4 };
int[] numbers = new int[input];
// Times we can use everything in columns_index
int times = input/columns_index.Length; // 333333
List<int> numbersList = new List<int>();
for (int i = 0; i < times; i++)
{
numbersList.AddRange(columns_index);
}
// numbersInt.Count is now 999999..
// Times for the rest
int modTimes = input%(columns_index.Length); // 2
for (int j = 0; j < modTimes; j++)
{
numbersList.Add(columns_index[j]);
}
numbers = numbersList.ToArray();