如何根据一些数字重复具有特定序列的数组元素?

时间:2012-02-20 09:37:42

标签: c# asp.net arrays linq math

如果我有这个整数数组:

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}

等等......

4 个答案:

答案 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();