Array concatenation: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Go}}: package change: reflect.ArrayCopy renamed to Copy)
Line 330: Line 330:
targ := ret
targ := ret
for _,v := range vals {
for _,v := range vals {
reflect.ArrayCopy(targ, v)
reflect.Copy(targ, v)
targ = targ.Slice(v.Len(),targ.Len())
targ = targ.Slice(v.Len(),targ.Len())
}
}

Revision as of 03:58, 22 January 2011

Task
Array concatenation
You are encouraged to solve this task according to the task description, using any language you may know.

Show how to concatenate two arrays in your language. If this is as simple as array1 + array2, so be it.

ActionScript

<lang ActionScript>var array1:Array = new Array(1, 2, 3); var array2:Array = new Array(4, 5, 6); var array3:Array = array1.concat(array2); //[1, 2, 3, 4, 5, 6]</lang>

Ada

In Ada arrays are concatenated using the operation &. It works with any one dimensioned array: <lang Ada>type T is array (Positive range <>) of Integer; X : T := (1, 2, 3); Y : T := X & (4, 5, 6); -- Concatenate X and (4, 5, 6)</lang>

ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

Includes operators for appending and prefixing an array to an existing flexible array: <lang Algol68>MODE ARGTYPE = INT; MODE ARGLIST = FLEX[0]ARGTYPE;

OP + = (ARGLIST a, b)ARGLIST: (

 [LWB a:UPB a - LWB a + 1 + UPB b - LWB b + 1 ]ARGTYPE out;
 ( 
   out[LWB a:UPB a]:=a,
   out[UPB a+1:]:=b
 );
 out

);

  1. Append #

OP +:= = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs; OP PLUSAB = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;

  1. Prefix #

OP +=: = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs; OP PLUSTO = (ARGLIST lhs, REF ARGLIST rhs)ARGLIST: rhs := lhs + rhs;

ARGLIST a := (1,2),

       b := (3,4,5);

print(("a + b",a + b, new line));

VOID(a +:= b); print(("a +:= b", a, new line));

VOID(a +=: b); print(("a +=: b", b, new line))</lang>

a + b         +1         +2         +3         +4         +5
a +:= b         +1         +2         +3         +4         +5
a +=: b         +1         +2         +3         +4         +5         +3         +4         +5

AutoHotkey

AutoHotkey does not have real Arrays, but the user can implement them quite easily. For example: <lang autohotkey>List1 = 1,2,3 List2 = 4,5,6

List2Array(List1 , "Array1_") List2Array(List2 , "Array2_")

ConcatArrays("Array1_", "Array2_", "MyArray") MsgBox, % Array2List("MyArray")


---------------------------------------------------------------------------

ConcatArrays(A1, A2, A3) { ; concatenates the arrays A1 and A2 to A3

---------------------------------------------------------------------------
   local i := 0
   %A3%0 := %A1%0 + %A2%0
   Loop, % %A1%0
       i++, %A3%%i% := %A1%%A_Index%
   Loop, % %A2%0
       i++, %A3%%i% := %A2%%A_Index%

}


---------------------------------------------------------------------------

List2Array(List, Array) { ; creates an array from a comma separated list

---------------------------------------------------------------------------
   global
   StringSplit, %Array%, List, `,

}


---------------------------------------------------------------------------

Array2List(Array) { ; returns a comma separated list from an array

---------------------------------------------------------------------------
   Loop, % %Array%0
       List .= (A_Index = 1 ? "" : ",") %Array%%A_Index%
   Return, List

}</lang> Message box shows:

1,2,3,4,5,6

C

A way to concatenate two C arrays when you know their size (and usually so it is) <lang c>#include <stdio.h>

  1. include <stdlib.h>
  2. include <string.h>
  1. define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
 (TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *array_concat(const void *a, size_t an,

                  const void *b, size_t bn, size_t s)

{

 char *p = malloc(s * (an+bn));
 memcpy(p, a, an*s);
 memcpy(p + an*s, b, bn*s);
 return p;

}

// testing const int a[] = { 1, 2, 3, 4, 5 }; const int b[] = { 6, 7, 8, 9, 0 };

int main() {

 int i;
 int *c = ARRAY_CONCAT(int, a, 5, b, 5);
 for(i=0; i < 10; i++) {
   printf("%d\n", c[i]);
 }
 free(c); // it is up to the programmer to free
          // the concatenated array
 return 0;

}</lang>

C++

<lang cpp>#include <vector>

  1. include <iostream>

int main() {

 std::vector<int> a(3), b(4);
 a[0] = 11; a[1] = 12; a[2] = 13;
 b[0] = 21; b[1] = 22; b[2] = 23; b[3] = 24;
 a.reserve(a.size() + b.size());
 a.insert(a.end(), b.begin(), b.end());
 for (int i = 0; i < a.size(); ++i)
   std::cout << "a[" << i << "] = " << a[i] << "\n";

}</lang>

C#

<lang csharp>using System;

namespace RosettaCode {

   class Program
   {
       static void Main(string[] args)
       {
           int[] a = { 1, 2, 3 };
           int[] b = { 4, 5, 6 };
           int[] c = new int[a.Length + b.Length];
           a.CopyTo(c, 0);
           b.CopyTo(c, a.Length);
           foreach(int n in c)
           {
               Console.WriteLine(n.ToString());
           }
       }
   }

}</lang>

Alternatively, using LINQ extension methods:

Works with: C# version 3

<lang csharp>using System.Linq;

class Program {

   static void Main(string[] args)
   {
       int[] a = { 1, 2, 3 };
       int[] b = { 4, 5, 6 };
       int[] c = a.Concat(b).ToArray();
   }

}</lang>

Clojure

<lang lisp>(concat [1 2 3] [4 5 6])</lang> The inputs can be any collection, including Java arrays, and returns a lazy sequence of the elements.


Common Lisp

concatenate is a general function for concatenating any type of sequence. It takes the type of sequence to produce, followed by any number of sequences of any type. <lang lisp>(concatenate 'vector #(0 1 2 3) #(4 5 6 7))

 => #(0 1 2 3 4 5 6 7)</lang>

D

<lang d>import std.stdio: writeln;

void main() {

   int[] a = [1, 2];
   int[] b = [4, 5, 6];
   int[] c = a ~ b;
   writeln(a, " ~ ", b, " = ", c);

}</lang> Output:

[1, 2] ~ [4, 5, 6] = [1, 2, 4, 5, 6]

E

<lang e>? [1,2] + [3,4]

  1. value: [1, 2, 3, 4]</lang>

Efene

using the ++ operator and the lists.append function

<lang efene> @public run = fn () {

   A = [1, 2, 3, 4]
   B = [5, 6, 7, 8]
   C = A ++ B
   D = lists.append([A, B])
   io.format("~p~n", [C])
   io.format("~p~n", [D])

}</lang>

Erlang

In erlang, you can use the ++ operator or lists:append, which is implemented via ++.

On the shell, <lang erlang> 1> [1, 2, 3] ++ [4, 5, 6]. [1,2,3,4,5,6] 2> lists:append([1, 2, 3], [4, 5, 6]). [1,2,3,4,5,6] 3> </lang>


F#

Array concatenation. <lang fsharp>let a = [|1; 2; 3|] let b = [|4; 5; 6;|] let c = Array.append a b</lang> List concatenation (@ and List.append are equivalent). <lang fsharp>let x = [1; 2; 3] let y = [4; 5; 6] let z1 = a @ b let z2 = List.append x y</lang>

Factor

<lang factor>append</lang>

Example: <lang factor>( scratchpad ) USE: sequences ( scratchpad ) { 1 2 } { 3 4 } append . { 1 2 3 4 }</lang>

Fortran

Works with: Fortran version 90 and later

<lang fortran>program Concat_Arrays implicit none

 integer, dimension(3) :: a = [ 1, 2, 3 ]
 integer, dimension(3) :: b = [ 4, 5, 6 ]
 integer, dimension(:), allocatable :: c
 
 allocate(c(size(a)+size(b)))
 c(1:size(a)) = a
 c(size(a)+1:size(a)+size(b)) = b
 write(*,*) c

end program Concat_Arrays</lang>

GAP

<lang gap># Concatenate arrays Concatenation([1, 2, 3], [4, 5, 6], [7, 8, 9]);

  1. [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
  1. Append to a variable

a := [1, 2, 3]; Append(a, [4, 5, 6); Append(a, [7, 8, 9]); a;

  1. [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]</lang>

Go

Easier to make the generic version accept any number of arguments, and loop trough them. Otherwise there will be lots of code duplication. <lang go>package main

import (

 "reflect"
 "fmt"

)

// Generic version func ArrayConcat(arrays ...interface{}) interface{} {

 if len(arrays) == 0 {
   panic("Need at least one arguemnt")
 }
 var vals = make([]*reflect.SliceValue, len(arrays))
 var arrtype *reflect.SliceType
 var totalsize int
 for i,a := range arrays {
   v := reflect.NewValue(a)
   switch t := v.Type().(type) {
   case *reflect.SliceType:
     if arrtype == nil {
       arrtype = t
     } else if t != arrtype {
       panic("Unequal types")
     }
     vals[i] = v.(*reflect.SliceValue)
     totalsize += vals[i].Len()
   default: panic("not a slice")
   }
 }
 ret := reflect.MakeSlice(arrtype,totalsize,totalsize)
 targ := ret
 for _,v := range vals {
   reflect.Copy(targ, v)
   targ = targ.Slice(v.Len(),targ.Len())
 }
 return ret.Interface()

}

// Type specific version func ArrayConcatInts(a, b []int) []int {

 ret := make([]int, len(a) + len(b))
 copy(ret, a)
 copy(ret[len(a):], b)
 return ret

}

func main() {

 test1_a, test1_b := []int{1,2,3}, []int{4,5,6}
 test1_c := ArrayConcatInts(test1_a, test1_b)
 fmt.Println(test1_a, " + ", test1_b, " = ", test1_c)
 test2_a, test2_b := []string{"a","b","c"}, []string{"d","e","f"}
 test2_c := ArrayConcat(test2_a, test2_b).([]string)
 fmt.Println(test2_a, " + ", test2_b, " = ", test2_c)

}</lang>

Output:

[1 2 3]  +  [4 5 6]  =  [1 2 3 4 5 6]
[a b c]  +  [d e f]  =  [a b c d e f]

Haskell

A list is in Haskell one of the most common composite data types (constructed from other types). In the documentation we read for the append operation ++: <lang haskell>(++) :: [a] -> [a] -> [a]</lang>

Append two lists, i.e.:

 
[x1, ..., xm] ++ [y1, ..., yn] == [x1, ..., xm, y1, ..., yn]
[x1, ..., xm] ++ [y1, ...] == [x1, ..., xm, y1, ...]

If the first list is not finite, the result is the first list.

HicEst

<lang HicEst>REAL :: a(7), b(3), c(10)

c = a DO i = 1, LEN(b)

  c(i + LEN(a)) = b(i)

ENDDO</lang>

Icon and Unicon

Works with: Unicon

Both languages have list concatenation built in. Lists are fully dynamic arrays which can be truncated or extended at either end. <lang icon> procedure main()

   L1 := [1, 2, 3, 4]
   L2 := [11, 12, 13, 14]
   L3 := L1 ||| L2
   sep := ""
   every writes(sep, !L3) do
       sep := ", "
   write()

end </lang>

IDL

Array concatenation can mean different things, depending on the number of dimensions of the arguments and the result. In the simplest case, with 1-dimensional arrays to begin with, there are two obvious ways to concatenate them. If my arrays are these: <lang IDL>

> a = [1,2,3]
> b = [4,5,6]
> help,a
     A               INT       = Array[3]
> help,b
     B               INT       = Array[3]
> print,a
     1       2       3
> print,b
     4       5       6

</lang> Then they can be concatenated "at the ends": <lang IDL>

> help,[a,b]
     <Expression>    INT       = Array[6]
> print,[a,b]
      1       2       3       4       5       6

</lang> or "at the sides": <lang IDL>

> help,[[a],[b]]
     <Expression>    INT       = Array[3, 2]
> print,[[a],[b]]
      1       2       3
      4       5       6

</lang> Note that this requires that the arrays have the same size at the side at which they are concatenated: <lang IDL>

> b = transpose(b)
> help,b
     B               INT       = Array[1, 3]
> print,b
      4
      5
      6
> print,[a,b]
Unable to concatenate variables because the dimensions do not agree: B.
Execution halted at: $MAIN$          
> print,[[a],[b]]
Unable to concatenate variables because the dimensions do not agree: B.
Execution halted at: $MAIN$    

</lang> This can get a lot more complicated as a 3x4x5-element three-dimensional array can be concatenated with a 5x2x3-element array at exactly two "surfaces".

Inform 7

<lang inform7>let A be {1, 2, 3}; let B be {4, 5, 6}; add B to A;</lang>

Ioke

<lang ioke>iik> [1,2,3] + [3,2,1] [1,2,3] + [3,2,1] +> [1, 2, 3, 3, 2, 1]</lang>

J

Solution: ,

Example: <lang j> array1 =: 1 2 3

  array2 =: 4 5 6
  array1 , array2

1 2 3 4 5 6</lang>

Of course, in J, array concatenation works (consistently) on arrays of any rank or dimension.

The verb , concatenates by treating the argument array with the largest number of dimensions as a list. Other primary verbs concatenate along other axes.

<lang j> ]ab=: 3 3 $ 'aaabbbccc' aaa bbb ccc

  ]wx=: 3 3 $ 'wxyz'

wxy zwx yzw

  ab , wx

aaa bbb ccc wxy zwx yzw

  ab ,. wx

aaawxy bbbzwx cccyzw

  ab ,: wx

aaa bbb ccc

wxy zwx yzw

  $ ab , wx    NB. applies to first (highest) axis

6 3

  $ ab ,. wx   NB. applies to last (atomic) axis

3 6

  $ ab ,: wx   NB. applies to new (higher) axis

2 3 3</lang>

Java

From [1]: <lang java5>public static Object[] objArrayConcat(Object[] o1, Object[] o2) {

 Object[] ret = new Object[o1.length + o2.length];

 System.arraycopy(o1, 0, ret, 0, o1.length);
 System.arraycopy(o2, 0, ret, o1.length, o2.length);

 return ret;

}</lang>

Or with Collections simply call addAll: <lang java5>Collection list1, list2, list1And2; //...list1 and list2 are instantiated... list1And2 = new ArrayList(list1); //or any other Collection you want list1And2.addAll(list2);</lang>

JavaScript

The Array.concat() method returns a new array comprised of this array joined with other array(s) and/or value(s). <lang javascript>var a = [1,2,3]; var b = [4,5,6]; var c = a.concat(b); // [1,2,3,4,5,6]</lang>

Liberty BASIC

<lang lb> x=10

   y=20
   dim array1(x)
   dim array2(y)

[concatenate]

   dim array3(x + y)
   for i = 1 to x
       array3(i) = array1(i)
   next
   for i = 1 to y
       array3(i + x) = array2(i)
   next

[print]

   for i = 1 to x + y
       print array3(i)
   next</lang>

COMBINE is used to combine lists or words. SENTENCE is used to combine lists and words into a single list. <lang logo> to combine-arrays :a1 :a2

 output listtoarray sentence arraytolist :a1 arraytolist :a2

end show combine-arrays {1 2 3} {4 5 6}  ; {1 2 3 4 5 6} </lang>

Lua

<lang lua>a = {1,2,3} b = {4,5,6} table.foreach(b,function(i,v)table.insert(a,i)end) for i,v in next,a do io.write (v..' ') end</lang>

Mathematica

<lang Mathematica>Join[{1,2,3}, {4,5,6}]

-> {1, 2, 3, 4, 5, 6}</lang>

Objeck

<lang objeck> bundle Default {

 class Arithmetic {
    function : Main(args : String[]) ~ Nil {
      array1 := [3, 5, 7];
      array2 := [2, 4, 6];
     
      array3 := Copy(array1, array2);
      each(i : array3) {
        array3[i]->PrintLine();
      };
 }
 
 function : native : Copy(array1 : Int[], array2 : Int[]) ~ Int[] {
    max := array1->Size() + array2->Size();
    array3 := Int->New[max];
     
    i := 0;
    for(i := i; i < array1->Size(); i += 1;) {
      array3[i] := array1[i];
    };
     
    j := 0;
    for(i := i; i < max; i += 1;) {
      array3[i] := array2[j];
      j += 1;
    };
     
     return array3;
   }
 }

} </lang>

Objective-C

with immutable arrays: <lang objc>NSArray *arr1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],

                                         [NSNumber numberWithInt:2],
                                         [NSNumber numberWithInt:3], nil];

NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:4],

                                         [NSNumber numberWithInt:5],
                                         [NSNumber numberWithInt:6], nil];

NSArray *arr3 = [arr1 arrayByAddingObjectsFromArray:arr2];</lang>

or adding onto a mutable array: <lang objc>NSArray *arr1 = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],

                                         [NSNumber numberWithInt:2],
                                         [NSNumber numberWithInt:3], nil];

NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithInt:4],

                                         [NSNumber numberWithInt:5],
                                         [NSNumber numberWithInt:6], nil];

NSMutableArray *arr3 = [NSMutableArray arrayWithArray:arr1]; [arr3 addObjectsFromArray:arr2];</lang>

MATLAB

To arrays are concatenated by placing the two arrays between a pair of square brackets. A space between the two array names will concatenate them horizontally, and a semi-colon between array names will concatenate vertically. <lang MATLAB>>> a = [1 2 3]

a =

    1     2     3

>> b = [4 5 6]

b =

    4     5     6

>> concat = [a b]

concat =

    1     2     3     4     5     6

>> concat = [a;b]

concat =

    1     2     3
    4     5     6</lang> 

OCaml

It is more natural in OCaml to use lists instead of arrays: <lang ocaml># let list1 = [1; 2; 3];; val list1 : int list = [1; 2; 3]

  1. let list2 = [4; 5; 6];;

val list2 : int list = [4; 5; 6]

  1. let list1and2 = list1 @ list2;;

val list1and2 : int list = [1; 2; 3; 4; 5; 6]</lang>

If you want to use arrays: <lang ocaml># let array1 = [|1; 2; 3|];; val array1 : int array = [|1; 2; 3|]

  1. let array2 = [|4; 5; 6|];;

val array2 : int array = [|4; 5; 6|]

  1. let array1and2 = Array.append array1 array2;;

val array1and2 : int array = [|1; 2; 3; 4; 5; 6|]</lang>

Oz

List are concatenated with List.append (shortcut: Append). Tuples are concatened with Tuple.append. Arrays do exist in Oz, but are rarely used. <lang oz>%% concatenating 2 lists {Append [a b] [c d]} = [a b c d]

%% concatenating 2 tuples {Tuple.append t(1 2 3) u(4 5 6)} = u(1 2 3 4 5 6)</lang>

PARI/GP

<lang>concat(u,v)</lang>

Perl

In Perl, arrays placed into list context are flattened: <lang perl>my @arr1 = (1, 2, 3); my @arr2 = (4, 5, 6); my @arr3 = (@arr1, @arr2);</lang>

The push function appends elements onto an existing array: <lang perl>my @arr1 = (1, 2, 3); my @arr2 = (4, 5, 6); push @arr1, @arr2; print "@arr1\n"; # prints "1 2 3 4 5 6"</lang>

Perl 6

<lang perl6># the comma ',' can be used to concatenate arrays: sub concatenateArrays(@a, @b) { @a, @b }

my @a1 = (1,2,3); my @a2 = (2,3,4); concatenateArrays(@a1,@a2).join(", ").say;</lang>

PHP

<lang php>$arr1 = array(1, 2, 3); $arr2 = array(4, 5, 6); $arr3 = array_merge($arr1, $arr2);</lang>

PicoLisp

PicoLisp has no built-in array data type. Lists are used instead.

There are destructive concatenations: <lang PicoLisp>: (setq A (1 2 3) B '(a b c)) -> (a b c)

(conc A B) # Concatenate lists in 'A' and 'B'

-> (1 2 3 a b c)

A

-> (1 2 3 a b c) # Side effect: List in 'A' is modified!</lang> and non-destructive concatenations: <lang PicoLisp>: (setq A (1 2 3) B '(a b c)) -> (a b c)

(append A B) # Append lists in 'A' and 'B'

-> (1 2 3 a b c)

A

-> (1 2 3)

B

-> (a b c) # Arguments are not modified</lang>

PL/I

<lang PL/I> declare A(5) fixed initial (1, 2, 3, 4, 5); declare B(7) fixed initial (6, 7, 8, 9, 10, 11, 12); declare C(*) fixed controlled;

allocate C(hbound(A,1)+hbound(B,1));

do i = 1 to hbound(A,1); C(i) = A(i); end; do i = 1 to hbound(B,1); C(i+hbound(A,1)) = B(i); end;

put (C); </lang>

PowerShell

<lang powershell>$a = 1,2,3 $b = 4,5,6

$c = $a + $b Write-Host $c</lang>

Prolog

<lang prolog> ?- append([1,2,3],[4,5,6],R). R = [1, 2, 3, 4, 5, 6]. </lang>

PureBasic

<lang PureBasic>Procedure displayArray(Array a(1), msg.s)

 Protected i
 Print(msg + " [")
 For i = 0 To ArraySize(a())
   Print(Str(a(i)))
   If i <> ArraySize(a())
     Print(", ")
   EndIf 
 Next 
 PrintN("]")

EndProcedure

Procedure randomElements(Array a(1), lo, hi)

 Protected i
 For i = 0 To ArraySize(a())
   a(i) = random(hi - lo) + lo
 Next 

EndProcedure

Procedure arrayConcat(Array a(1), Array b(1), Array c(1))

 Protected i, newSize = ArraySize(a()) + ArraySize(b()) + 1
 Dim c(newSize)
 For i = 0 To ArraySize(a())
   c(i) = a(i)
 Next
 For i = 0 To ArraySize(b())
   c(i + ArraySize(a()) + 1) = b(i)
 Next

EndProcedure


If OpenConsole()

 Dim a(random(3) + 1)
 Dim b(random(3) + 1)
 Dim c(0) ;array will be resized by arrayConcat()
 
 randomElements(a(), -5, 5)
 randomElements(b(), -5, 5)
 displayArray(a(), "a:")
 displayArray(b(), "b:")
 arrayConcat(a(), b(), c())
 displayArray(c(), "concat of a[] + b[]:")
 
 Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
 Input()
 CloseConsole()

EndIf</lang> Sample output:

a: [5, 2, -4, -1, -2]
b: [0, -4, -1]
concat of a[] + b[]: [5, 2, -4, -1, -2, 0, -4, -1]

Python

The + operator concatenates two lists and returns a new list. The list.extend method appends elements of another list to the receiver. <lang python>arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 assert arr4 == [1, 2, 3, 4, 5, 6] arr4.extend(arr3) assert arr4 == [1, 2, 3, 4, 5, 6, 7, 8, 9]</lang>

R

<lang R> a1 <- c(1, 2, 3) a2 <- c(3, 4, 5) a3 <- c(a1, a2) </lang>

REBOL

<lang REBOL> a1: [1 2 3] a2: [4 5 6] a3: [7 8 9]

append a1 a2 ; -> [1 2 3 4 5 6]

append/only a1 a3 ; -> [1 2 3 4 5 6 [7 8 9]] </lang>

REXX

REXX doesn't have arrays as such, but it has something that looks, feels, and tastes like arrays: stemmed variables.

Simply, a stemmed array is a variable with an appended dot (.) followed by a constant (such as an integer). There is no way to preallocate a stemmed variable, REXX just assigns them as they are created.

As such, there isn't an easy way to keep track of the number of "elements" in a REXX "array".
Consider: <lang rexx> a.1=10 a.2=22.7 a.7=-12 </lang> where now we have three "elements", and they are disjointed.
There are ways to handle this in REXX however.

When assigning stemmed arrays, it is common to assign "element" zero to the number of values, assuming that the stemmed variables are sequential.

Example: <lang rexx> fact.0=8 fact.1= 1 fact.2= 2 fact.3= 6 fact.4= 24 fact.5= 120 fact.6= 720 fact.7= 5040 fact.8=40320 </lang> To concat two "arrays" in REXX, the following assumes that the stemmed variables are in order, with no gaps, and none have a "null" value. <lang rexx> p.= /*a short list of primes.*/ p.1=2; p.2=3; p.3=5; p.4=7; p.5=11; p.6=13; p.7=17; p.8=19; p.9=23 p.10=27; p.11=31; p.12=37

f.= /*a short list of Fibonacci numbers.*/ f.1=1;f.2=1;f.3=2;f.4=3;f.5=5;f.6=8;f.7=13;f.8=21;f.9=34;f.10=55

n=0

 do j=1 while p.j\==
 n=n+1
 c.n=p.j
 end
   do k=1 while f.k\==
   n=n+1
   c.n=f.k
   end

say 'n'=n

 do m=1 for n
 say 'c.'m"="c.m
 end

</lang> Output:

elements=22
c.1=2
c.2=3
c.3=5
c.4=7
c.5=11
c.6=13
c.7=17
c.8=19
c.9=23
c.10=27
c.11=31
c.12=37
c.13=1
c.14=1
c.15=2
c.16=3
c.17=5
c.18=8
c.19=13
c.20=21
c.21=34
c.22=55

RLaB

In RLaB the matrices can be appended (column-wise) or stacked (row-wise). Consider few examples: <lang RLaB> >> x = [1, 2, 3] >> y = [4, 5, 6] // appending matrix 'y' on the right from matrix 'x' is possible if the two matrices have // the same number of rows: >> z1 = [x, y] matrix columns 1 thru 6

          1             2             3             4             5             6

// stacking matrix 'y' below the matrix 'x' is possible if the two matrices have // the same number of columns: >> z2 = [x; y]

          1             2             3
          4             5             6

>> </lang>

Ruby

The Array#+ method concatenates two arrays and returns a new array. The Array#concat method appends elements of another array to the receiver. <lang ruby>arr1 = [1, 2, 3] arr2 = [4, 5, 6] arr3 = [7, 8, 9] arr4 = arr1 + arr2 # => [1, 2, 3, 4, 5, 6] arr4.concat(arr3) # => [1, 2, 3, 4, 5, 6, 7, 8, 9]</lang>

Scala

<lang Scala>val arr1 = Array( 1, 2, 3 ) val arr2 = Array( 4, 5, 6 ) val arr3 = Array( 7, 8, 9 )

Array concat ( arr1, arr2, arr3 ) // res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)</lang>

Scheme

(append list ...) returns a list consisting of the elements of the first list followed by the elements of the other lists.

Example: <lang scheme>(append '(x) '(y)) (append '(a) '(b c d)) (append '(a (b)) '((c)))</lang> Output:

(x y)
(a b c d)
(a (b) (c))

Seed7

<lang seed7>$ include "seed7_05.s7i";

var array integer: a is [] (1, 2, 3, 4); var array integer: b is [] (5, 6, 7, 8); var array integer: c is [] (9, 10);

const proc: main is func

 local
   var integer: number is 0;
 begin
   c := a & b;
   for number range c do
     write(number <& " ");
   end for;
   writeln;
 end func;</lang>

Output:

1 2 3 4 5 6 7 8

Slate

The binary operation of concatenation is made with the ; (semi-colon) from the type Sequence. It is also available for appending Sequences to WriteStreams.

<lang slate> {1. 2. 3. 4. 5} ; {6. 7. 8. 9. 10} </lang>

Smalltalk

Concatenation (appending) is made with the method , (comma), present in classes SequenceableCollection, ArrayedCollection and their subclasses (e.g. Array, String, OrderedCollection ...)

<lang smalltalk>|a b c| a := #(1 2 3 4 5). b := #(6 7 8 9 10). c := a,b. c displayNl.</lang>

SNOBOL4

Works with: Macro Spitbol
Works with: Snobol4+
Works with: CSnobol

<lang SNOBOL4>* # Concatenate 2 arrays (vectors)

       define('cat(a1,a2)i,j') :(cat_end)

cat cat = array(prototype(a1) + prototype(a2)) cat1 i = i + 1; cat = a1 :s(cat1) cat2 j = j + 1; cat = a2<j> :s(cat2)f(return) cat_end

  • # Fill arrays
       str1 = '1 2 3 4 5'; arr1 = array(5)

loop i = i + 1; str1 len(p) span('0123456789') . arr1 @p :s(loop)

       str2 = '6 7 8 9 10'; arr2 = array(5)

loop2 j = j + 1; str2 len(q) span('0123456789') . arr2<j> @q :s(loop2)

  • # Test and display
       arr3 = cat(arr1,arr2)

loop3 k = k + 1; str3 = str3 arr3<k> ' ' :s(loop3)

       output = str1
       output = str2
       output = str3

end</lang>

Output:

1 2 3 4 5
6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

Tcl

<lang tcl>set a {1 2 3} set b {4 5 6} set ab [concat $a $b]; # 1 2 3 4 5 6</lang> Note that in the Tcl language, “arrays” are hash maps of strings to variables, so the notion of concatenation doesn't really apply. What other languages (usually) call arrays are “lists” in Tcl.

TI-89 BASIC

If a and b are lists, augment(a, b) concatenates them in the usual fashion. If a and b are matrices, then augment(a, b) produces a matrix whose columns are the columns of a followed by the columns of b, i.e. an augmented matrix.

■ augment({1,2}, {3,4})
    {1,2,3,4}
■ augment([[1][2]], [[3][4]])
    [[1,3][2,4]]

That last example as displayed in pretty-printing mode:

Concatenation in the other direction may of course be done by transposition:

■ augment([[x][y]], [[z][w]])
    [[x][y][z][w]]

Trith

<lang trith>[1 2 3] [4 5 6] concat</lang>

UNIX Shell

Using proper built-in Bash arrays:

Works with: bash

<lang bash>array1=( 1 2 3 4 5 ) array2=( 6 7 8 9 10 ) botharrays=( ${array1[@]} ${array2[@]} )</lang>

Whitespace-delimited strings work in much the same way:

Works with: bash

<lang bash>array1='1 2 3 4 5' array2='6 7 8 9 10'

  1. Concatenated to a Bash array ...

botharrays_a=( $array1 $array2 )

  1. Concatenated to a string ...

botharrays_s="$array1 $array2"</lang>

Vala

<lang vala>int[] array_concat(int[]a,int[]b){ int[] c = new int[a.length + b.length]; Memory.copy(c, a, a.length * sizeof(int)); Memory.copy(&c[a.length], b, b.length * sizeof(int)); return c; } void main(){ int[] a = {1,2,3,4,5}; int[] b = {6,7,8}; int[] c = array_concat(a,b); foreach(int i in c){ stdout.printf("%d\n",i); } }</lang>

VBScript

<lang vb>Function ArrayConcat(arr1, arr2)

   ReDim ret(UBound(arr1) + UBound(arr2) + 1)
   For i = 0 To UBound(arr1)
       ret(i) = arr1(i)
   Next
   offset = Ubound(arr1) + 1
   For i = 0 To UBound(arr2)
       ret(i + offset) = arr2(i)
   Next
   ArrayConcat = ret

End Function

arr1 = array(10,20,30) arr2 = array(40,50,60) WScript.Echo "arr1 = array(" & Join(arr1,", ") & ")" WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")" arr3 = ArrayConcat(arr1, arr2) WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"</lang>

Output:

arr1 = array(10, 20, 30)
arr2 = array(40, 50, 60)
arr1 + arr2 = array(10, 20, 30, 40, 50, 60)

Yorick

<lang yorick>a = [1,2,3]; b = [4,5,6]; ab = grow(a, b);</lang>

Zsh

Concatenating arrays. <lang zsh>a=(1 2 3) b=(a b c)

c=($a $b)</lang> Pushing a single element into an array. <lang zsh>a+=4</lang> Pushing another array into an array. <lang zsh>a+=($b)</lang>