I need some help in getting this right,
problem
Write a function which takes 2 arrays- One array is the source array and the other array is the array of indices and delete all those elements present at the indices of the source array taking the indices from the second array.
This is what I have come up with….
public static int[] DeleteArrayUsingIndices(int[] source, int[] indices)
{
for (int i = 0; i < indices.Length; i++)
{
if (indices[i] < source.Length)
{
source[indices[i]] = int.MinValue; // delete
}
}
return source;
}
I am not very sure with this solution, as this does not remove the value. Can anyone help me out with this.
You cannot really delete elements from an array, so you need to ask what is meant by this wording. If replacing the elements with an exceptional element (like
int.MinValuein your code) is acceptable, your solution is fine.Another interpretation could be to rearrange the array so the “not deleted” indexes are at the begining of the array in the same order they were in the original — in this case you would want to return the new “length” of the array (the number of elements that were not “deleted”) — this means that a “delete” operation will compact the array of not-yet deleted elements to the begining of the array (shifting the contents of the array toward the beginning from the deleted index to the end of the array (or to the end of the non-deleted elements). Care must be taken not to “delete” the same element twice.
To achieve the latter, you will have to either keep track of which position was moved by how many elements. Alternatively, update the index array to decrement indices larger than the current one (to accomodate the now compacted array) — in this case you coul start by sorting the index array (possibly removing duplicates at the same time) and just keep track of how many positions have been shifted so far