Array Initialization: Difference between revisions

(→‎AWK: Also looks to be covered)
 
(12 intermediate revisions by 3 users not shown)
Line 1:
{{DeprecatedTask}}
'''Examples here should be migrated to [[Creating an Array]] or [[Creating an Associative Array]] and removed from here. If similar code already exists there, simply remove it from here. After it has been removed, mark it on the [[Talk:Array Initialization#Bump|the talk page]].'''
'''Examples here should be migrated to [[Arrays]] or [[Creating an Associative Array]] and removed from here. If similar code already exists there, simply remove it from here.'''
 
 
Line 25 ⟶ 26:
</lang>
Note that the array bounds, when unconstrained as in these examples can be either determined by the aggregate, like the initialization of X shows. Or else they can be specified as a constraint, like for example in the initialization of Y. In this case '''others''' choice can be used to specify all unmentioned elements. But in any case, the compiler verifies that all array elements are initialized by the aggregate. Single dimensional arrays of characters can be initialized by character strings, as the variable S shows. Of course, array aggregates can participate in array expressions and these expressions can be used to initialize arrays. The variable B is initialized by an aggregate inversed by the operation '''not'''.
==[[AutoHotkey]]==
AutoHotkey does not have arrays yet.
However, variables can be set to arbitrary size and pointer operations can be used, simulating arrays. Just without the syntactic sugar of '[]'.
Initialization is as follows:
<lang AutoHotkey>
size = 1000
value = 0
VarSetCapacity(arrayVar, size, value)
</lang>
 
==[[C++]]==
 
Simple arrays in C++ have no bounds-checking. In order to safely modify the array's contents, you must know in advance both the number of dimensions in the array and the range for each dimension. In C++, all arrays are zero-indexed, meaning the first element in the array is at index 0.
 
To assign a single value to an array, one uses the [] operator.
<lang cpp>
// Assign the value 7 to the first element of myArray.
myArray[0] = 7;
</lang>
If '''myArray''' has ten elements, one can use a loop to fill it.
<lang cpp>
// Assign the sequence 1..10 to myArray
for(int i = 0; i < 10; ++i)
myArray[i] = i + 1;
</lang>
If '''myArray''' has two dimensions, you can use nested loops.
<lang cpp>
// Create a multiplication table
for(int y = 0; y < 10; ++y)
for(int x = 0; x < 10; ++x)
myArray[x][y] = (x+1) * (y+1);
</lang>
 
===STL===
{{libheader|STL}}STL provides '''std::vector''', which behaves as a dynamically-resizable array. When an element is added, its value must be set immediately.
Line 99 ⟶ 68:
std::vector v4 = v3; // v4 is a copy of v3
</lang>
 
==[[Fortran]]==
{{works with|Fortran|95 and later}}
 
Arrays can be initialized using a robust set of array constructors and array intrinsic functions.
<lang fortran> program arrays
real :: a(100) = 0 ! entire array initialized to ZERO
real :: b(9) = (/ 1,2,3,4,5,6,7,8,9 /) ! array constructor
real :: c(10) = (/ (2**i, i=1, 10) /) ! array constructor with "implied do loop"
! An array constructor is a literal definition of a ONE-DIMENSIONAL array only.
! In order to initialize multidimensional arrays, you need to use the RESHAPE instrinsic
! function:
real :: d(2, 5) = reshape( (/ (2**i,i=1,10) /), (/ 2, 5 /) )
! ^^^^^^^^^^^^^^^^^^^source array ^^^^^^^^^^ dimension shape
! Fills the array in COLUMN MAJOR order. That is, traverse the first dimension first,
! second dimension second, etc.
! In order to fill a matrix in ROW MAJOR order, merely specify as before,
! but TRANSPOSE the result
real :: e(4, 4) = transpose( reshape( &
(/ 1, 2, 3, 4, &
5, 6, 7, 8, &
9, 10, 11, 12, &
13, 14, 15, 16 /), (/ 4, 4 /) ) )
print *, b
print *
print *, c
print *
print '(5F7.0)', d(1,:) ! print row 1
print '(5F7.0)', d(2,:) ! print row 2
print *
do i = 1, 4
print '(4F7.0)', e(i,:) ! print row I
end do
end program arrays</lang>
 
Output:
1. 2. 3. 4. 5. 6. 7. 8. 9.
2. 4. 8. 16. 32. 64. 128. 256. 512. 1024.
2. 8. 32. 128. 512.
4. 16. 64. 256. 1024.
1. 2. 3. 4.
5. 6. 7. 8.
9. 10. 11. 12.
13. 14. 15. 16.
 
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
<lang fortran> module matrixUtil
contains
function identity(n)
integer, intent(in) :: n
integer :: i, j
real, pointer :: identity(:,:)
allocate(identity(n,n))
! the MERGE intrinsic is like a C ternary (if-then-else) operator, except that the logical condition
! comes at the end, it is a logical ARRAY, and the function result is an array of the same size and shape
identity = merge (1.0, 0.0, reshape( (/ ( (i==j, i=1,n), j=1,n) /), (/ n, n /) ) )
! ^^^ if-TRUE-value ^^^ if-FALSE-value ^^<-NxN logical array, true only on the diagonal->^^
! The TVALUE and FVALUE must be "conformable" to the logical array, meaning that each is either:
! -- an array of the same size and shape as the logical array
! -- a scalar
end function identity
end module matrixUtil</lang>
 
<lang fortran> program muTest
use matrixUtil
integer :: n
real, pointer :: i(:,:)
read (*,*) n
i => identity(n)
do j=1, size(i,1)
print *, i(j,:)
end do
deallocate(i)
end program muTest</lang>
 
Example run:
$ <span style="color: blue;">g95 -o mu matrixUtil.f95 muTest.f95</span>
$ <span style="color: blue;">./mu</span>
<span style="color: red;">15</span>
1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0.
0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.
$
 
==[[F_Sharp|F#]]==
Line 207 ⟶ 74:
let c = [| for n = 1 to 10 do yield n |] // lazy array
let d = [| "hello"; "world" |] // array of strings
 
==[[Groovy]]==
Follows the pattern of the fascinating Fortran example above:
 
Arrays and lists are synonymous in Groovy. They can be initialized with a wide range of operations and Groovy enhancements to the Collection and List classes.
<lang groovy>def aa = [ 1, 25, 31, -3 ] // list
def a = [0] * 100 // list of 100 zeroes
def b = 1..9 // range notation
def c = (1..10).collect { 2.0**it } // each output element is 2**(corresponding invoking list element)
 
// There are no true "multi-dimensional" arrays in Groovy (as in most C-derived languages).
// Use lists of lists in natural ("row major") order as a stand in.
def d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } }
def e = [ [ 1.0, 2.0, 3.0, 4.0 ],
[ 5.0, 6.0, 7.0, 8.0 ],
[ 9.0, 10.0, 11.0, 12.0 ],
[ 13.0, 14.0, 15.0, 16.0 ] ]
 
println aa
println b
println c
println()
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }</lang>
 
Output:
<pre>[1, 25, 31, -3]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]
 
[ 2.0 4.0 8.0 16.0 32.0 ]
[ 64.0 128.0 256.0 512.0 1024.0 ]
 
[ 1.0 2.0 3.0 4.0 ]
[ 5.0 6.0 7.0 8.0 ]
[ 9.0 10.0 11.0 12.0 ]
[ 13.0 14.0 15.0 16.0 ]</pre>
 
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
<lang groovy>def identity = { n ->
(1..n).collect { i -> (1..n).collect { j -> i==j ? 1.0 : 0.0 } }
}</lang>
 
Test program:
<lang groovy>def i2 = identity(2)
def i15 = identity(15)
 
 
i2.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }
println()
i15.each { print "["; it.each { elt -> printf "%4.1f ", elt }; println "]" }</lang>
 
Output:
<pre>[ 1.0 0.0 ]
[ 0.0 1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 89:
array ((0,0),(5,5)) [((0,0),0),((0,1),0),((0,2),0),((0,3),0),((0,4),0),((0,5),0),((1,0),0),((1,1),0),((1,2),0),((1,3),0),((1,4),0),((1,5),0),((2,0),0),((2,1),0),((2,2),0),((2,3),0),((2,4),0),((2,5),0),((3,0),0),((3,1),0),((3,2),0),((3,3),0),((3,4),0),((3,5),0),((4,0),0),((4,1),0),((4,2),0),((4,3),0),((4,4),0),((4,5),0),((5,0),0),((5,1),0),((5,2),0),((5,3),0),((5,4),0),((5,5),0)]
</lang>
=={{header|Scala}}==
<lang Scala>// immutable maps
var map = Map(1 -> 2, 3 -> 4, 5 -> 6)
map(3) // 4
map = map + (44 -> 99) // maps are immutable, so we have to assign the result of adding elements
map.isDefinedAt(33) // false
map.isDefinedAt(44) // true</lang>
 
<lang scala>// mutable maps (HashSets)
==[[Mathematica]]==
import scala.collection.mutable.HashMap
Creating an array is just done by using Set and giving a symbol and a list. A list can contain ''anything'', and of any type. Elements don't have to be of the same type.
val hash = new HashMap[Int, Int]
<lang Mathematica>
hash(1) = 2
a={1,3,3,7};
hash += (1 -> 2) // same as hash(1) = 2
b={"L","ee","t"};
hash += (3 -> 4, 5 -> 6, 44 -> 99)
c={1,Pi,"L",a};
hash(44) // 99
</lang>
hash.contains(33) // false
 
hash.isDefinedAt(33) // same as contains
==[[MAXScript]]==
hash.contains(44) // true</lang>
Collect method:
<pre>arr = for i in 1 to 100 collect 0</pre>
Append method:
<pre>arr = #()
for i in 1 to 100 do append arr 0</pre>
Assign and dynamically grow method:
<pre>arr = #()
for i in 1 to 100 do arr[i] = 0</pre>
 
==[[Modula-3]]==
The usual module and import code is omitted.
<lang modula3>VAR arr := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
VAR arr1 := ARRAY [1..10] OF INTEGER {1, ..} (* Initialize all elements to 1. *)</lang>
Array initialization doesn't have to be used in the array declaration.
<lang modula3>TYPE Vector: ARRAY OF INTEGER;
VAR arr: Vector;
arr := Vector{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};</lang>
 
== [[Perl]]==
Perl only has three types: Scalar, Array, Hash Array
 
<lang perl>
use strict;
use warnings;
my @intArray = ( 1, 2, 3, 4, 5, 6, 7 );
$intArray[0] = 1;
my @strArray = qw( aaa bbb ccc ddd eee );
$strArray[1]= "bbb";
my @matrix = ([qw( 00 01 12)], [qw(10 11 12)], [qw(20 21 22)]);
$matrix[1][2]= "12";
my %hashArray = ("key1", "value1", "key2", "value2", "key3", "value3");
my %hashArray2 = ("key1"=>"value1", "key2"=>"value2", "key3"=>"value3");
$hashArray2 {"key2"}="value2";
</lang>
 
==[[Python]]==
 
Python lists are dynamically resizeable. A simple, single dimensional, array can be initialized thus:
 
<lang python>
myArray = [0] * size
</lang>
 
However this will not work as intended if one tries to generalize from the syntax:
 
<lang python>
myArray = [[0]* width] * height] # DOES NOT WORK AS INTENDED!!!
</lang>
 
This creates a list of "height" number of references to one list object ... which is a list of width instances of the number zero. Due to the differing semantics of mutables (strings, numbers) and immutables (dictionaries, lists), a change to any one of the "rows" will affect the values in all of them. Thus we need to ensure that we initialize each row with a newly generated list.
 
To initialize a list of lists one could use a pair of nested list comprehensions like so:
 
<lang python>
myArray = [[0 for x in range(width)] for y in range(height)]
</lang>
 
That is equivalent to:
 
<lang python>
myArray = list()
for x in range(height):
myArray.append([0] * width)
</lang>
 
==[[Slate]]==
<lang slate>
{1. 'hello'. $c. 4 factorial} "evaluates each argument and makes an array"
#(1 b 34) "is quoted... array at: 1 will return #b"
</lang>
 
==[[Smalltalk]]==
<lang smalltalk>|array|
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
 
<lang scala>// iterate over key/value
"Access the first element of the array"
hash.foreach {e => println("key "+e._1+" value "+e._2)} // e is a 2 element Tuple
elem := array at: 1.
// same with for syntax
for((k,v) <- hash) println("key " + k + " value " + v)</lang>
 
<lang scala>// items in map where the key is greater than 3
"Replace apple with orange"
map.filter {k => k._1 > 3} // Map(5 -> 6, 44 -> 99)
array at: 2 put: 'orange'.</lang>
// same with for syntax
for((k, v) <- map; if k > 3) yield (k,v)</lang>
Anonymous user