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 the input length <= 50 then the output is an exact copy of the input.
if the length of the input array> 50 then it will only copy 50 elements from the input
It must have element first and last of input
and select the rest evenly ; it doesn't just take the first or last 50 elements.
What's the most efficient way to do this?
UPDATE For example, input [] has 98 elements. then you will 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
Sort of:
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 multiplication overflows int
, admittedly.
a source to share
I think you have an approximation problem related to int divisions, try to keep it doubled until 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;
}
Hope I understood your answer correctly.
a source to share
It may be far away, but I thought it would be interesting to try. I hope I don't mess things up anymore.
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;
}
a source to share