I have this very simple array which I want to be able to move around some items in. Are there any built in tools in c# to do this? If not, du you have any suggestion in how to do it.
In example
var smallArray = new string[4];
smallArray[0] = "a";
smallArray[1] = "b";
smallArray[2] = "c";
smallArray[3] = "d";
And lets say I want to (programmatically) swap index 2 and 0, creating
smallArray[0] = "c";
smallArray[1] = "a";
smallArray[2] = "b";
smallArray[3] = "d";
Thanks.
An array is said to be right rotated if all elements of the array are moved to its right by one position. One approach is to loop through the array by shifting each element of the array to its next position. The last element of the array will become the first element of the rotated array.
The array can be left rotated by shifting its elements to a position prior to them which can be accomplished by looping through the array and perform the operation arr[j] = arr[j+1]. The first element of the array will be added to the last of rotated array.
Shift Matrix Elements Create a numeric array with a cluster of ones in the top left. Use circshift to shift each column of A one position to the right. Shift the elements of A by one position in each dimension. The cluster of ones is now in the center of the matrix.
EDIT: Okay, now you've changed the example, there's nothing built-in - and it would actually be a bit of a pain to write... you'd need to consider cases where you're moving it "up" and where you're moving it "down", for example. You'd want unit tests, but I think this should do it...
public void ShiftElement<T>(this T[] array, int oldIndex, int newIndex)
{
// TODO: Argument validation
if (oldIndex == newIndex)
{
return; // No-op
}
T tmp = array[oldIndex];
if (newIndex < oldIndex)
{
// Need to move part of the array "up" to make room
Array.Copy(array, newIndex, array, newIndex + 1, oldIndex - newIndex);
}
else
{
// Need to move part of the array "down" to fill the gap
Array.Copy(array, oldIndex + 1, array, oldIndex, newIndex - oldIndex);
}
array[newIndex] = tmp;
}
You should probably consider using a List<T>
instead of an array, which allows you to insert and remove at particular indexes. Those two operations will be more expensive than only copying the relevant section, but it'll be a lot more readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With