I have a simple problem, but I am having a hard time getting the concept.
I have an array of doubles (doublesarray) and I want to slice the array so that I get the last "x" values.
x could be 2,5,7,12,etc
example:
doublesarray = {0,2,4,5,7,8,2,4,6};
doublesarray.slice(-4,-1);
output:
[8,2,4,6]
doublesarray.slice(-2,-1);
output:
[4,6]
Attempt:
I found some code online that slices, but it does not handle 2 negative inputs.
public static class Extensions
{
/// <summary>
/// Get the array slice between the two indexes.
/// ... Inclusive for start index, exclusive for end index.
/// </summary>
public static T[] Slice<T>(this T[] source, int start, int end)
{
// Handles negative ends.
if (end < 0)
{
end = source.Length + end;
}
int len = end - start;
// Return new array.
T[] res = new T[len];
for (int i = 0; i < len; i++)
{
res[i] = source[i + start];
}
return res;
}
}