I am trying to create a C# function to left rotate array elements and store it in another array.
inputl = array to which rotated array has to be stored,
inputr = array to be rotated
shift = number of shifts.
Even though I pass the value of shift as any value the rotation takes place only once. Please help.
public static void LeftShift(int[] inputl,int[] inputr, int shift)
{
for (int j = 0; j < shift; j++)
{
int temp = inputr[0];
var last = inputr.Length - 1;
for (int i = 0; i < last; i++)
{
inputl[i] = inputr[i+1];
}
inputl[last] = temp;
}
}
}
Here is my solution to your problem:
public static void shift(int[]al, int[]ar,int shift)
{
shift=ar.Length-shift%ar.Length;
for (int i = 0; i < ar.Length; i++)
al[(i+shift)%al.Length]=ar[i];
}
If you remove the first line inside the shift method the output will be a right shift
Hope I could understand your problem and this is what you want
public static void shift(int[]al, int[]ar,int shift)
{
int ind=0;
for (int i = shift; i < ar.Length; i++)
{
al[ind] = ar[i];
ind++;
}
for (int i = 0; i < shift; i++)
{
al[ind] = ar[i];
ind++;
}
}
I solved above program using below code.
public static List<int> rotateLeft(int d, List<int> arr) {
int n = arr.Count;
List<int> t = new List<int>();
int h = d;
for (int j = 0; j < n; j++)
{
if ((j + d) % n == 0)
{
h = 0;
}
t.Add(arr[h]);
h++;
}
return t;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.