Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #194 Circular shift of a two-dimensional array

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.

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']
)
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);
...
import numpy as np
b = np.roll(a, m, axis=1)
b  = a.map{|ar| ar.rotate(n) }

New implementation...
< >
tkoenig