AlameerAshraf
AlameerAshraf

Reputation: 872

Cutting an array?

I want to take a number N from user and split the array according to that number and save the new elements in new one.

For example, when the user enters 2, and I have an array like

["alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"]

the result will be

["alameeer", "alameer"], ["alameeer", "alameer"], ["alameeer", "ashraf"]

When N equals 3

["alameeer", "alameer", "alameeer"], ["alameeer", "alameer", "alameeer"]

I tried below code but it is very static and very bad performance and I don't know how to change it.

string str = UserCorpus.TrimEnd();
string[] Oops = str.Split(' ', ',', '!');
int stringCounter = Oops.Length;
string[] holder = new string[10];
for (int i = 0; i < stringCounter - 2; i++)
{
    holder[i] = Oops[i] + Oops[i + 1] + Oops[i + 2]; 
}

Upvotes: 0

Views: 465

Answers (1)

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

You should not be worry about bad performance here. What you are trying to do cant become better than O(n).

How ever i suggest you use Batch from MoreLinq. its also written by jon skeet, any questions? ;)

string[] array = new[] {"alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"};
int cut = 2;
var result = array.Batch(cut, piece => string.Join(" ", piece)).ToArray();

Any way if you want to write your own implementation you can do this. which works for any cut length and array length. (I doubt this one be O(n) because i think Skip(i) is not O(1))

string[] array = new[] {"alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf"};
int cut = 2;

string[] result = new string[(int)Math.Ceiling(array.Length / (double)cut)];
for (int i = 0, j = 0; i < array.Length; i += cut, j++)
{
    result[j] = string.Join(" ", array.Skip(i).Take(cut));
}

If you dont want to use Linq at all. (O(n))

string[] array = new[] { "alameeer", "alameer", "alameer", "alameer", "alameer", "ashraf" };
int cut = 4;

string[] result = new string[(int)Math.Ceiling(array.Length / (double)cut)];
for (int i = 0, j = 0; i < array.Length; i += cut, j++)
{
    string[] temp = new string[Math.Min(cut, array.Length)];
    for (int k = i; k < i + cut && k < array.Length; k++)
    {
        temp[k - i] = array[k];
    }
    result[j] = string.Join(" ", temp).Trim();
}

Upvotes: 1

Related Questions