I'm trying to reorganize an array based on the first occurrence of a value (thus simulating similar functionality to a circular array.)
For example, in the following array I wish the first occurrence of the value 6 to become the new first element, and prior elements to become the latter:
So:
int[] myArray = {2, 3, 6, 1, 7, 6};
Becomes:
myArray = {6, 1, 7, 6, 2, 3};
What is the "best" way to achieve this?
Logic To Shift Elements of An Array by n Position. First we ask the user to input N integer numbers and store it inside array variable a[N]. We then ask the user to input the number of positions to shift the elements of the array, and then the direction of shifting.
Explanation: No. You can not change the C Basic rules of Zero Starting Index of an 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.
int[] myArray = { 2, 3, 6, 1, 7, 6 };
myArray = myArray
.SkipWhile(i => i != 6)
.Concat(myArray.TakeWhile(i => i != 6))
.ToArray();
Should do the trick!
You will need a using System.Linq
;
Thorsten's solution creates a new array; here's an in place version which only creates a temporary array as large as the amount your rotation size:
public static void RotateLeft<T>(T[] array, int places)
{
T[] temp = new T[places];
Array.Copy(array, 0, temp, 0, places);
Array.Copy(array, places, array, 0, array.Length - places);
Array.Copy(temp, 0, array, array.Length - places, places);
}
I'm sure it could be done with just a single temporary buffer item, but it would be more complicated :)
As an efficiency measure, here's a "rotate left one place" shortcut:
public static void RotateLeft<T>(T[] array)
{
T temp = array[0];
Array.Copy(array, 0, array, 1, array.Length - 1);
array[array.Length-1] = temp;
}
You could do the following:
Array.Copy()
to copy everything from start index to end of source array to destination arrayArray.Copy()
to copy everything from 0 to start index of source array to the end of the destination arrayThat way you get a copy of your source array that looks as you expected.
You'll have to play with various overloads of Array.Copy()
, however, because I don't know the exact parameter values right now.
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