0

if i need to split array in to specific length as example let say i have array with 16 elements and i wanna split this in to 3 arrays and each array include 5 elements when it comes to last array should take rest of them so output should be something like this

  • array 1 with 5 elements
  • array 2 with 5 elements
  • array 3 with 6 elements

i really like this answer but it cannot split in to predefined length

public static IEnumerable<List<int>> SplitWhenNotIncreasing(List<int> numbers)
{
    for (int i = 1, start = 0; i <= numbers.Count; ++i)
    {
        if (i != numbers.Count && numbers[i] > numbers[i - 1])
            continue;

        yield return numbers.GetRange(start, i - start);
        start = i;
    }
}
2
  • If the final array were just the left overs it would be easy. Commented Nov 22, 2017 at 4:46
  • What if your array contains less than 3 elements? What if it contains 10 elements? how about 60? and 28? What's the rules? Commented Nov 22, 2017 at 4:48

1 Answer 1

1
public static IEnumerable<List<T>> SplitArray<T>(T[] arr, int splitsNumber)
{
    var list = arr.ToList();
    int size = list.Count / splitsNumber;
    int pos = 0;
    for (int i = 0; i + 1 < splitsNumber; ++i, pos += size)
    {
        yield return list.GetRange(pos, size);
    }

    yield return list.GetRange(pos, list.Count - pos);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.