Array concatenation
From Rosetta Code
array1 + array2, so be it.
[edit] 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]
[edit] Ada
In Ada arrays are concatenated using the operation &. It works with any one dimensioned array:
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)
[edit] 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:
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
);
# Append #
OP +:= = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;
OP PLUSAB = (REF ARGLIST lhs, ARGLIST rhs)ARGLIST: lhs := lhs + rhs;
# 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))
a + b +1 +2 +3 +4 +5 a +:= b +1 +2 +3 +4 +5 a +=: b +1 +2 +3 +4 +5 +3 +4 +5
[edit] C
A way to concatenate two C arrays when you know their size (and usually so it is)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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;
}
[edit] C++
#include <vector>
#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";
}
[edit] C#
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());
}
}
}
}
Alternatively, using LINQ extension methods:
Works with: C# version 3
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();
}
}
[edit] Clojure
(concat [1 2 3] [4 5 6])
The inputs can be any collection, including Java arrays, and returns a lazy sequence of the elements.
[edit] Common Lisp
(append '(x y) '(x z))
[edit] 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);
}
[edit] E
? [1,2] + [3,4]
# value: [1, 2, 3, 4]
[edit] Efene
using the ++ operator and the lists.append function
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])
}
[edit] F#
Array concatenation.
let a = [|1; 2; 3|]
let b = [|4; 5; 6;|]
let c = Array.append a b
List concatenation (@ and List.append are equivalent).
let x = [1; 2; 3]
let y = [4; 5; 6]
let z1 = a @ b
let z2 = List.append x y
[edit] Factor
append
Example:
( scratchpad ) USE: sequences
( scratchpad ) { 1 2 } { 3 4 } append .
{ 1 2 3 4 }
[edit] Fortran
Works with: Fortran version 90 and later
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
[edit] 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 ++:
(++) :: [a] -> [a] -> [a]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.
[edit] 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".
[edit] Ioke
iik> [1,2,3] + [3,2,1]
[1,2,3] + [3,2,1]
+> [1, 2, 3, 3, 2, 1]
[edit] J
Solution: ,
Example:
array1 =: 1 2 3
array2 =: 4 5 6
array1 , array2
1 2 3 4 5 6
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.
]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
[edit] Java
From [1]:
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;
}
Or with Collections simply call addAll:
Collection list1, list2, list1And2;
//...list1 and list2 are instantiated...
list1And2 = new ArrayList(list1); //or any other Collection you want
list1And2.addAll(list2);
[edit] JavaScript
The Array.concat() method returns a new array comprised of this array joined with other array(s) and/or value(s).
var a = [1,2,3];
var b = [4,5,6];
var c = a.concat(b); // [1,2,3,4,5,6]
[edit] Logo
COMBINE is used to combine lists or words. SENTENCE is used to combine lists and words into a single list.
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}
[edit] 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
[edit] Mathematica
Join[{1,2,3}, {4,5,6}]
-> {1, 2, 3, 4, 5, 6}
[edit] Objective-C
with immutable arrays:
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];
or adding onto a mutable array:
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];
[edit] OCaml
It is more natural in OCaml to use lists instead of arrays:
# let list1 = [1; 2; 3];;
val list1 : int list = [1; 2; 3]
# let list2 = [4; 5; 6];;
val list2 : int list = [4; 5; 6]
# let list1and2 = list1 @ list2;;
val list1and2 : int list = [1; 2; 3; 4; 5; 6]
If you want to use arrays:
# let array1 = [|1; 2; 3|];;
val array1 : int array = [|1; 2; 3|]
# let array2 = [|4; 5; 6|];;
val array2 : int array = [|4; 5; 6|]
# let array1and2 = Array.append array1 array2;;
val array1and2 : int array = [|1; 2; 3; 4; 5; 6|]
[edit] Oz
List are concatenated with List.append (shortcut: Append). Tuples are concatened with Tuple.append. Arrays do exist in Oz, but are rarely used.
%% 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)
[edit] Perl
In Perl, arrays placed into list context are flattened:
my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
my @arr3 = (@arr1, @arr2);
The push function appends elements onto an existing array:
my @arr1 = (1, 2, 3);
my @arr2 = (4, 5, 6);
push @arr1, @arr2;
print "@arr1\n"; # prints "1 2 3 4 5 6"
[edit] PHP
$arr1 = array(1, 2, 3);
$arr2 = array(4, 5, 6);
$arr3 = array_merge($arr1, $arr2);
[edit] PicoLisp
PicoLisp has no built-in array data type. Lists are used instead.
There are destructive concatenations:
: (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!
and non-destructive concatenations:
: (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
[edit] 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);
[edit] PowerShell
$a = 1,2,3
$b = 4,5,6
$c = $a + $b
Write-Host $c
[edit] Python
The + operator concatenates two lists and returns a new list. The list.extend method appends elements of another list to the receiver.
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]
[edit] R
a1 <- c(1, 2, 3)
a2 <- c(3, 4, 5)
a3 <- c(a1, a2)
[edit] 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]]
[edit] Ruby
The Array#+ method concatenates two arrays and returns a new array. The Array#concat method appends elements of another array to the receiver.
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]
[edit] 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)
[edit] Scheme
(append list ...) returns a list consisting of the elements of the first list followed by the elements of the other lists.
Example:
(append '(x) '(y))
(append '(a) '(b c d))
(append '(a (b)) '((c)))
Output:
(x y) (a b c d) (a (b) (c))
[edit] Smalltalk
Concatenation (appending) is made with the method , (comma), present in classes SequenceableCollection, ArrayedCollection and their subclasses (e.g. Array, String, OrderedCollection ...)
|a b c|
a := #(1 2 3 4 5).
b := #(6 7 8 9 10).
c := a,b.
c displayNl.
[edit] Tcl
set a {1 2 3}
set b {4 5 6}
set ab [concat $a $b]; # 1 2 3 4 5 6
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.
[edit] 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]]
[edit] 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.
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, ", ")
Output:
1, 2, 3, 4, 5, 6







