Java:
// anArray = new int[10];
int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};
anArray[0] = 100; // initialize first element
anArray[1] = 200; // initialize second element
anArray[2] = 300; // and so forth
System.out.println("Element 1 at index 0: " + anArray[0]);
System.out.println("Element 2 at index 1: " + anArray[1]);
System.out.println("Element 3 at index 2: " + anArray[2]);
Python:
#!/usr/bin/env python
# set, list, tuple, dict, deque, heapq, OrderedDict, defaultDict, Counter
x = set(["Postcard", "Radio", "Telegram"])
print(x)
# % set(['Postcard', 'Radio', 'Telegram'])
y = {"Postcard","Radio","Telegram"}
print(y)
# %
myList=[i*i for i in range(10)]
myArray=[[1,2],[3,4]]
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
print(cnt)
# % Counter({'blue': 3, 'red': 2, 'green': 1})
c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements())
# This is tuple
b = ("Bob", 19, "CS") # tuple packing
(name, age, studies) = b # tuple unpacking
def pairwise_sum (list1, list2):
result = []
for i in range (len(list1)):
result.append(list1[i] + list2[i])
return result
Perl:
# sum up two equal-sized lists of numbers and return the pairwise sum
#
sub pairwise_sum {
my ($arg1, $arg2) = @_;
my (@result) = ();
@list1 = @$arg1;
@list2 = @$arg2;
$len = @list1; # same as length(@list1)
$max_index = $#list1;
for ($i=0; $i < length(@list1); $i++) {
push (@result, $list1[$i] + $list2[$i]);
}
return (\@result);
}
Ruby:
names = Array.new(20)
puts names.size # This returns 20
puts names.length
names = Array.new(4, "mac")
puts "#{names}" # This returns "["mac", "mac", "mac", "mac"]"
nums = Array.new(10) { |e| e = e * 2 }
puts "#{nums}" # This returns "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]"
nums = Array.[](1, 2, 3, 4,5)
nums = Array[1, 2, 3, 4,5]
digits = Array(0..9)
num = digits.at(6)
JavaScript:
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var name = cars[0];
document.getElementById("demo").innerHTML = cars[0];
// This is array
var person = ["John", "Doe", 46];
// This is object
var person = {firstName:"John", lastName:"Doe", age:46};
C++:
#include <iostream>
using namespace std;
int foo [] = {16, 2, 77, 40, 12071};
int another_foo [5] = { 16, 2, 77, 40, 12071 };
int jimmy [3][5]; // is equivalent to
int jimmy [15]; // (3 * 5 = 15)
#define WIDTH 5
#define HEIGHT 3
int jimmy [HEIGHT][WIDTH];
int n,m;
int main ()
{
for (n=0; n<HEIGHT; n++)
for (m=0; m<WIDTH; m++) {
jimmy[n][m]=(n+1)*(m+1);
}
}
SystemVerilog:
- Fixed-size (multi-dimension)
- dynamic (single dimension)
- queue (single dimension)
- associative (single dimension)
typedef enum {IDLE, TEST, START} state;
Tcl/Tk:
# create array
set balloon(key) red
array set balloon {color red}
array set myArray {}
array set myArray {"name" "value"}
set myArray(name) value
array unset {this myarray}
set {this myarray(key)}
parray {this myarray}
foreach idx [array names x] {
set x($idx) {}
}
# determine if a key exists
info exists array(key)
set value1 $myArray(name)
set value2 $myArray($idx)
eval {set ${key}($item)}
puts [set ${key}($item)]
# in a procedure, use upvar to create local reference to array
upvar $key v
puts $v($item)
set v($item) $val
# not so good
set a(key) value
value
array get a
# unset the whole array
unset myArray
# use array unset to unset a subset of keys
proc incrArrayElement {var key {incr 1}} {
upvar $var a
if {[info exists a($key)]} {
incr a($key) $incr
} else {
set a($key) $incr
}
}
array set data {
foo,x ecks foo,y why foo,z zed
bar,x ECKS bar,y WHY bar,z ZED
}
set data(foo)(x) ecks; set data(foo)(y) why; set data(foo)(z) zed
set data(bar)(x) ECKS; set data(bar)(y) WHY; set data(bar)(z) ZED
# join [array names data] \n
#
set a(1,1) 0 ;# set element 1,1 to 0
set a([list $i1 $i2 $i3]) 0; # set element (i1,i2,i3) of array a to 0
set a([list 1 2 3]) 0
# above i equivalent to the following
set {a(1 2 3)} 0
# multi-dimention
array set data [list \
[list foo x] ecks [list foo y] why [list foo z] zed\
[list bar x] ECKS [list bar y] WHY [list bar z] ZED\
]
proc array_dimnames {array_var dim_index} {
upvar 1 $array_var array
set result [list]
foreach name [lsort -unique -index $dim_index [array names array]] {
lappend result [lindex $name $dim_index]
}
return $result
}
% array_dimnames data 0
bar foo
% array_dimnames data 1
x y z
proc declare_array arrayName {
upvar 1 $arrayName array
catch {unset array}
array set array {}
}
# array sort
proc array_sort {index val _foreach_sorting_array_ref foreachsorting_command} {
# _foreach_sorting_array_ref is a reference this mean equivalent to &array in C
upvar $_foreach_sorting_array_ref arrref
upvar $index i
upvar $val v
set x [list]
foreach {k vl} [array get arrref] {
lappend x [list $k $vl]
}
foreach e [lsort -integer -decreasing -index 1 $x] {
#puts "$i,$v"
set i [lindex $e 0]
set v [lindex $e 1]
# ------- FOREACH BODY ------------<
uplevel $foreachsorting_command
# ------END FOREACH BODY----------->
}
}
set name(first) "Mary"
set name(last) "Poppins"
puts "Full name: $name(first) $name(last)"
parray name
array set array1 [list {123} {Abigail Aardvark} \
{234} {Bob Baboon} \
{345} {Cathy Coyote} \
{456} {Daniel Dog} ]
if {[array exist array1]} {
puts "array1 is an array"
} else {
puts "array1 is not an array"
}
proc existence {variable} {
upvar $variable testVar
if { [info exists testVar] } {
puts "$variable Exists"
} else {
puts "$variable Does Not Exist"
}
}
# Create an array
for {set i 0} {$i < 5} {incr i} { set a($i) test }
existence a(0)
set mylist {}
lappend mylist a
lappend mylist b
lappend mylist c
lappend mylist d
foreach elem $mylist {
puts $elem
}
// or if you really want to use for
for {set i 0} {$i < [length $mylist]} {incr i} {
puts "${i}=[lindex $mylist $i]"
}
set myarr(chicken) animal
set myarr(cows) animal
set myarr(rock) mineral
set myarr(pea) vegetable
foreach key [array names myarr] {
puts "${key}=$myarr($key)"
}
foreach {index content} [array get date] {
put $index: $content
}
# use $array($key) or $array("abc") to access
# multi dimension, use
# set a(1,1) 0
# set a(1,2) 1