# Array concatenation

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.

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


## 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

<lang lisp>(append '(x y) '(x z))</lang>

## D

<lang d>import std.stdio; // for writefln void main() {

   uint[] a = [0, 1, 2, 3, 4];
uint[] b = [5, 6, 7, 8, 9];
uint[] cat = a ~ b; // concat a and b into cat

   writefln(a, " ~ ", b, " = ", cat);


}</lang>

## 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>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>

## 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 :: a(3) = (/ 1, 2, 3 /)
integer :: b(3) = (/ 4, 5, 6 /)
integer, 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>

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.

## 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:

> 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


Then they can be concatenated "at the ends":

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


or "at the sides":

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


Note that this requires that the arrays have the same size at the side at which they are concatenated:

> 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$


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".

## 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 the left-argument array 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

## 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>

## 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>

## 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 ﬁrst 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))


## 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>

## 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:

${\displaystyle \operatorname{augment} \left(\begin{bmatrix}1 \\ 2\end{bmatrix}, \begin{bmatrix}3 \\ 4\end{bmatrix}\right)}$

${\displaystyle \begin{bmatrix} 1 & 3 \\ 2 & 4 \end{bmatrix}}$

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

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

${\displaystyle \left(\operatorname{augment} \left(\begin{bmatrix}x \\ y\end{bmatrix}^\mathrm T, \begin{bmatrix}z \\ w\end{bmatrix}^\mathrm T\right)\right)^\mathrm T}$

${\displaystyle \begin{bmatrix} x \\ y \\ z \\ w\end{bmatrix}}$

## VBScript

I hope someone corrects me on this, but joining two arrays would seem to be achieved by joining both by some unique separator and then splitting. It doesn't thrill me lots. <lang vb>dim a,b a = array(1,2,3) b = array(4,5,6)

dim c c = split( join( a, vbNullChar ) & vbNullChar & join( b, vbNullChar ), vbNullChar )

wscript.echo join(c, ", ") </lang>

Output:

<lang vb>1, 2, 3, 4, 5, 6</lang>