Suggestion: dynamic array operations
Gregor Richards
Richards at codu.org
Wed Sep 6 10:51:32 PDT 2006
Nikita Kalaganov wrote:
>
> 1. Pop from array on front/back
>
> Syntax:
> ARRAY1 = ARRAY2 <<< INTEGER
> ARRAY1 <<<= INTEGER
>
> ARRAY1 = ARRAY2 >>> INTEGER
> ARRAY1 >>>= INTEGER
>
> Example:
> int[] a;
> // let a = [1,2,3,4,5]
> int[] b;
>
> b = a <<< 4; // b = [1,2,3,4] a = [5]
> b = a >>> 4; // b = [2,3,4,5] a = [1]
>
> a <<<= 3; // a = [1,2,3]
> a >>>= 1; // a = [3]
>
> 2. Array rotation
>
> Syntax:
> ARRAY1 = ARRAY2 ral INTEGER
> ARRAY1 ral= INTEGER
>
> ARRAY1 = ARRAY2 rar INTEGER
> ARRAY1 rar= INTEGER
>
> Example:
> int[] a;
> // let a = [1,2,3,4,5]
>
> b = a ral 2; // b = [3,4,5,1,2]
> b = a rar 2; // b = [4,5,1,2,3]
>
> a ral= 2; // a = [3,4,5,1,2]
> a rar= 4; // a = [4,5,1,2,3]
>
> 3. Shift array left/right
>
> Syntax:
> ARRAY1 = ARRAY2 << {ARRAY3 | INTEGER}
> ARRAY1 <<= {ARRAY2 | INTEGER}
>
> ARRAY1 = ARRAY2 >> {ARRAY3 | INTEGER}
> ARRAY1 >>= {ARRAY2 | INTEGER}
>
> Example ('di' means default initializer):
> int[] a;
> // let a = [1,2,3,4,5]
> int[] b;
> // let b = [6,7];
> int[] c;
>
> c = a << 3; // c = [4,5,di,di,di]
> c = a << b; // c = [3,4,5,6,7]
>
> c = a >> 3; // c = [di,di,di,1,2]
> c = a >> b; // c = [6,7,1,2,3]
>
> a <<= 2; // a = [3,4,5,di,di]
> a <<= b; // a = [5,di,di,6,7]
> a >>= 2; // a = [di,di,5,di,0]
> a >>= b; // a = [6,7,di,di,5]
>
> ------------
>
> Together with concatenation, these operations give us in-built standard
> containers like queue and deque (goodbye templates!). Also, they ease
> implementation of various algorithms with matrix operations.
>
> P.S. Hmm, maybe it's a good idea to add rotation operations for
> _unsigned_ integers ?
>
> Syntax & example:
> uint a;
>
> a = 0x000ff000;
> a rol= 4; // a = 0x00ff0000
> a ror= 20; // a = 0xf000000f
Arrays are arrays, not lists. You can abuse them into stacks, queues
and the ilk, but it's an inefficient use of memory. There's a reason
that stacks, queues and such are not usually implemented with arrays, in
the same way that constant strings are not generally implemented as
linear linked lists of single characters.
- Gregor Richards
More information about the Digitalmars-d
mailing list