I have a challenge to solve which is slitting a string into evenly-sized chunks.
Examples
Given the string s = "abcdefg"
and chunks = 3
, return ["abc", "de", "fg"]
. Note that the remainder of 1 was distributed to the first element in the list.
Given the string s = "abcdefgh"
and chunks = 3
, return ["abc", "def", "gh"]
. Again, note that the remainder of 2 was distributed to the first element in the list followed by the second element in the list.
So, I have this solution from an old question but the "evenly" isn't consider
public static IEnumerable<string> Iterator(string s, int chunks)
{
for (int i = 0; i < s.Length; i += s.Length - chunks)
{
if (i + chunks > s.Length) chunks = s.Length - i;
yield return s.Substring(i, chunks);
}
}
public static string[] Result(string s, int chunks)
{
if (chunks <= 0)
throw new ArgumentException();
return Iterator(s, chunks).ToArray();
}
Second example would pass with this but the first doesn't, how do I adjust this to pass both test?