I can't use a built-in function for this, I must use my own logic.
I've done element shifting to the left side, but the right side doesn't work for me. Not sure why.
My method for left:
public int[] shiftLeft(int[] arr) {
int[] demo = new int[arr.length];
int index = 0;
for (int i = 0; i < arr.length - 1; i++) {
demo[index] = arr[i + 1];
index++;
}
return demo;
}
and my attempt for the right shifting:
public int[] shiftRight(int[] arr) {
int[] demo = new int[arr.length];
int index = 0;
for (int i = arr.length - 1; i >= 0; i--) {
demo[index] = arr[(i - 1 > 0) ? i - 1 : 0];
index++;
}
return demo;
}
What am I doing wrong?
By shifting I mean:
you have an array, 1 2 3 4 5 6
Shifting it to left by one: 2 3 4 5 6 1
Shifting it to right by one: 6 1 2 3 4 5
//right shift with modulus
for (int i = 0; i < arr.length; i++) {
demo[(i+1) % demo.length] = arr[i];
}
LINQ solution, just to add some diversity.
static int[] LeftShift(int[] array)
{
// all elements except for the first one... and at the end, the first one. to array.
return array.Skip(1).Concat(array.Take(1)).ToArray();
}
static int[] RightShift(int[] array)
{
// the last element (because we're skipping all but one)... then all but the last one.
return array.Skip(array.Length - 1).Concat(array.Take(array.Length - 1)).ToArray();
}
Probably not recommended if performance matters (for large arrays).
I realize that the OP is not supposed to use a "built-in function".
The easiest way to go:
public int[] shiftLeft(int[] arr)
{
int[] demo = new int[arr.Length];
for (int i = 0; i < arr.Length - 1; i++)
{
demo[i] = arr[i + 1];
}
demo[demo.Length - 1] = arr[0];
return demo;
}
public int[] shiftRight(int[] arr)
{
int[] demo = new int[arr.Length];
for (int i = 1; i < arr.Length; i++)
{
demo[i] = arr[i - 1];
}
demo[0] = arr[demo.Length - 1];
return demo;
}
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