Rotate Array Elements to the Left (Move First Element to Last and Re-Index)

Rotate array elements to the left (move first element to last and re-index)

Most of the current answers are correct, but only if you don't care about your indices:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');
array_push($arr, array_shift($arr));
print_r($arr);

Output:

Array
(
[baz] => qux
[wibble] => wobble
[0] => bar
)

To preserve your indices you can do something like:

$arr = array('foo' => 'bar', 'baz' => 'qux', 'wibble' => 'wobble');

$keys = array_keys($arr);
$val = $arr[$keys[0]];
unset($arr[$keys[0]]);
$arr[$keys[0]] = $val;

print_r($arr);

Output:

Array
(
[baz] => qux
[wibble] => wobble
[foo] => bar
)

Perhaps someone can do the rotation more succinctly than my four-line method, but this works anyway.

How to move each element of an array one position to the left?

You miss the last element.

static void rotateArray(char [] S) {

// if is empty nothing to do
if(S.length < 1)
return;

// we save the first element to put at the last position
char first = S[0];

// for each element but last
for(int i = 0; i < S.length - 1; i++)
S[i] = S[i + 1];

// now the saved first value is used
S[S.length - 1] = first;

}

public static void main(String... args) {

char [] helloWorld = "Hello World!".toCharArray();

System.out.println(helloWorld);
for(int i = 0; i < 10; i++) {
rotateArray(helloWorld);
System.out.println(helloWorld);
}

}

with output

Hello World!
ello World!H
llo World!He
lo World!Hel
o World!Hell
World!Hello
World!Hello
orld!Hello W
rld!Hello Wo
ld!Hello Wor
d!Hello Worl

Rotate the elements in an array in JavaScript

Type-safe, generic version which mutates the array:

Array.prototype.rotate = (function() {
// save references to array functions to make lookup faster
var push = Array.prototype.push,
splice = Array.prototype.splice;

return function(count) {
var len = this.length >>> 0, // convert to uint
count = count >> 0; // convert to int

// convert count to value in range [0, len)
count = ((count % len) + len) % len;

// use splice.call() instead of this.splice() to make function generic
push.apply(this, splice.call(this, 0, count));
return this;
};
})();

In the comments, Jean raised the issue that the code doesn't support overloading of push() and splice(). I don't think this is really useful (see comments), but a quick solution (somewhat of a hack, though) would be to replace the line

push.apply(this, splice.call(this, 0, count));

with this one:

(this.push || push).apply(this, (this.splice || splice).call(this, 0, count));

Using unshift() instead of push() is nearly twice as fast in Opera 10, whereas the differences in FF were negligible; the code:

Array.prototype.rotate = (function() {
var unshift = Array.prototype.unshift,
splice = Array.prototype.splice;

return function(count) {
var len = this.length >>> 0,
count = count >> 0;

unshift.apply(this, splice.call(this, count % len, len));
return this;
};
})();

How can we rotate an array to the left?

Rotating to the left by n is the same as rotating to the right by length-n.

Rotate right (for positive n):

for(int i = 0; i < data.length; i++){
result[(i+n) % data.length ] = data[i];
}

Rotate left (for positive n):

for(int i = 0; i < data.length; i++){
result[(i+(data.length-n)) % data.length ] = data[i];
}

This way you can avoid a modulo of a negative number.

If you want to input an integer n that rotates right if n is positive and left if n is negative, you can do it like this:

 int[] rotateArray(int n, int[] data)
{
if(n < 0) // rotating left?
{
n = -n % data.length; // convert to +ve number specifying how
// many positions left to rotate & mod
n = data.length - n; // rotate left by n = rotate right by length - n
}
int[] result = new int[data.length];
for(int i = 0; i < data.length; i++){
result[(i+n) % data.length ] = data[i];
}
return result;
}

Rotating an array to the left without using shift

Wel, if you want it simple, try Linq and modulo arithmetics:

  int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };

int shift = 4;

int[] result = Enumerable
.Range(0, array.Length)
.Select(i => array[(i + shift % array.Length + array.Length) % array.Length])
.ToArray();

Same modulo arithmetics and no Linq

  int shift = 4;

int[] result = new int[array.Length];

for (int i = 0; i < result.Length; ++i)
result[i] = array[(i + shift % array.Length + array.Length) % array.Length];

If you want to rotate to right, assign negative values to shift.

Edit: what's going under the hood, modulo arithmetics explained. Our task is when we are given i (index of result) to compute index of the initial array:

 array  = {1 2 3 4 5 6 7 8}
result = {5 6 7 8 1 2 3 4}

as we can see,

 index = i + shift 

when shift is small enough (5 is taken from 0 + 4 == 4th index). However we can't exceed arrays length but should subtract it (i.e. restart from 0)

 7 + 4 == 11 -> 11 - 8 == 3

I.e.

 index = i + shift

index >= array.Length
? index - array.Length // index is too large, restart from 0
: index; // index is small enough

This operation is equal to remainder %:

 index = (i + shift) % array.Length

It's good enough, but we still have 2 specific issues with .Net:

  1. i + shift can result in integer oveflow (when, say shift = int.MaxValue)
  2. .Net can well return negative remainder (if shift < 0)

That's why shift % array.Length to meet the first issue and + array.Length for the second. Finally

(i + shift % array.Length + array.Length) % array.Length

How to move first element to the end of array

There is Array#rotate:

[a,b,c,d].rotate(1)

Shift elements in array by index

You can use ranged subscripting and concatenate the results. This will give you what you're looking for, with names similar to the standard library:

extension Array {
func shiftRight(var amount: Int = 1) -> [Element] {
guard count > 0 else { return self }
assert(-count...count ~= amount, "Shift amount out of bounds")
if amount < 0 { amount += count } // this needs to be >= 0
return Array(self[amount ..< count] + self[0 ..< amount])
}

mutating func shiftRightInPlace(amount: Int = 1) {
self = shiftRight(amount)
}
}

Array(1...10).shiftRight()
// [2, 3, 4, 5, 6, 7, 8, 9, 10, 1]
Array(1...10).shiftRight(7)
// [8, 9, 10, 1, 2, 3, 4, 5, 6, 7]

Instead of subscripting, you could also return Array(suffix(count - amount) + prefix(amount)) from shiftRight().



Related Topics



Leave a reply



Submit