decon2
decon2

Reputation:

how to make an array size cap

I have two string arrays

string[] input; //user input could be any size
string[] output; //a copy of user input but, should not be larger than 50

if input length <= 50, then output is an exact copy of input.

if input array length > 50 then it will copy only 50 elements from input

It must have the first and last element from input and select the rest evenly; it's not just simply taking the first or last 50 elements.

What's the most efficient way to do this?

UPDATE say input[] has 98 elements. then you would take the first and last elements and then divide the rest by 2 to get 50 elements

98-2=96
96/2=48

2+48=50

Upvotes: 1

Views: 541

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503220

Something like:

public static T[] CopyEvenly<T>(T[] from, int size)
{
    if (from.Length <= size)
    {
        return (T[]) from.Clone();
    }
    T[] ret = new T[size];
    for (int i=0; i < size; i++)
    {
        ret[i] = from[(i * (from.Length + size - 1)) / size];
    }
    return ret;
}

This will fail if you get to the stage where the multiplication overflows an int, admittedly.

Upvotes: 2

dsrekab
dsrekab

Reputation: 476

This may be way off, but I thought it would be fun to try. Hope I don't make things more confusing.

static T[] CopyEvenly<T>(T[] srcArray, int size)
{
   int factor=srcArray.Length/size; //this will be the "step" size
   T[] retArray=new T[size];

   int counter = 0;

   //add element 0 and every [factor]'ith element until 1 less than size
   while (counter < size - 1 && counter<srcArray.Length)
   {
      retArray[counter] = srcArray[counter * factor];
      counter++;
   }

   //add the last element
   retArray[size] = srcArray[srcArray.Length - 1];

   return retArray;
}

Upvotes: 0

Maghis
Maghis

Reputation: 1103

I think you have an approximation problem dealing with int divisions, try to keep it in doubles till you get the index:

static T[] CopyEvenly<T>(T[] source, int size)
{
    if (size >= source.Length)
        // or copy it to a new one if you prefer
        return source;

    T[] ret = new T[size];
    // keep everything in doubles
    double factor = (double)(source.Length - 1) / (double)(size - 1);
    for (int i = 0; i < ret.Length; i++)
    {
        // cast to int just now
        int inputIndex = (int)((double)i * factor);

        ret[i] = source[inputIndex];
    }
    return ret;
}

I hope I understood your answer correctly.

Upvotes: 0

Paul Sonier
Paul Sonier

Reputation: 39510

for (float i = 0, int count = 0; count < 50; i+= arraySize / 50.0f, count++)
{
output[count] = input[(int)i];
}

Upvotes: 2

Related Questions