Logo

Programming-Idioms

Given an array a, set b to an array which has the values of a along its second dimension shifted by n. Elements shifted out should come back at the other end.
New implementation

Be concise.

Be useful.

All contributions dictatorially edited by webmasters to match personal tastes.

Please do not paste any copyright violating material.

Please try to avoid dependencies to third-party libraries and frameworks.

Other implementations
b = cshift(a,n,dim=2)
type
  TSomeType = Integer;
  TArr = array of array of TSomeType; 

...
procedure ShiftArr(src: TArr; var dest: TArr; n: Integer);
var
  i,j,j2: integer;
begin
  SetLength(dest, length(src), length(src[0]));
  n := n mod length(src[0]);
  for i := low(src) to high(src) do
  begin
    for j := low(src[0]) to high(src[0]) do
    begin
      j2 := j + n;
      if j2 > high(src[0]) then
        j2 := j2 - high(src[0]) - 1;
      dest[i,j2] := src[i,j];
    end;
  end;
end;

...
ShiftArr(a,b,n);
...
my @a = (
    ['a' .. 'g'],
    ['h' .. 'm'],
    ['n' .. 'z']
);
my $n = 5;
my @b = map {
    my @c = @$_;
    push @c, splice @c, 0, $n;
    \@c;
} @a;
__END__
@b = (
    ['f', 'g', 'a' .. 'e'],
    ['m', 'h' .. 'l'],
    ['s' .. 'z', 'n' .. 'r']
)
import numpy as np
b = np.roll(a, m, axis=1)
b  = a.map{|ar| ar.rotate(n) }