Creating an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(revert spam)
Line 1: Line 1:
{{task}}
[http://puli.org.cn/web/michel-pfeifer/ michel pfeifer] [http://nibko.info/data/div-codec.htm div3 codec] [http://nibko.info/data/marcosignori-gervasio.htm marcosignori gervasio] [http://zodip.info/description/per-cani.htm per cani perdita pelo] [http://zodip.info/description/will-smth.htm will smth] [http://italnet.net.cn/img/come-with/ come with me puff daddy] [http://nibko.info/data/fran-reyes.htm fran reyes] [http://puli.org.cn/web/sisoft-sandra/ sisoft sandra lite] [http://italnet.net.cn/img/tumori/ tumori] [http://hangzhau.cn/html/mais-que/ mais que nada] [http://puli.org.cn/web/telok-anson/ telok anson] [http://puli.org.cn/web/golf-v/ golf 2.8v6 4motion] [http://nibko.info/data/packard-bell.htm packard bell - store play hard disk] [http://hangzhau.cn/html/www-urdughar/ www urdughar it] [http://hangzhau.cn/html/www-ferrovienord/ www ferrovienord it] [http://hangzhau.cn/html/il-gigante/ il gigante di metropolis] [http://nibko.info/data/creare-mappa.htm creare mappa concettuale maturita] [http://puli.org.cn/web/canciones-de/ canciones de arequipa] [http://nibko.info/data/stampante-scanner.htm stampante scanner fotocopiatrice epson] [http://italnet.net.cn/img/rx-v/ rx v4600 yamaha] [http://zodip.info/description/tommyknocker.htm tommyknocker] [http://zodip.info/description/marcela-bbb.htm marcela bbb4] [http://puli.org.cn/web/tonight-i/ tonight i m dreaming fifty fifty] [http://italnet.net.cn/img/searchin-my/ searchin my soul] [http://puli.org.cn/web/codici-di/ codici di sblocco e616v] [http://nibko.info/data/moondance-bubble.htm moondance bubble] [http://nibko.info/data/file-sega.htm file sega] [http://italnet.net.cn/img/compagnia-aerea/ compagnia aerea iberia] [http://italnet.net.cn/img/f-/ f 828 sony] [http://hangzhau.cn/html/casalinghe-tettone/ casalinghe tettone] [http://hangzhau.cn/html/cantrel/ cantrel] [http://nibko.info/data/maxtor-onetouch.htm maxtor onetouch 250] [http://puli.org.cn/web/pagine-binche/ pagine binche] [http://italnet.net.cn/img/good-night/ good night] [http://italnet.net.cn/img/dlla-luccio/ dlla luccio] [http://italnet.net.cn/img/gimme-hope/ gimme hope johanna] [http://nibko.info/data/luke-perry.htm luke perry] [http://nibko.info/data/bridge-across.htm bridge across forever] [http://puli.org.cn/web/combat-flight/ combat flight simulator] [http://puli.org.cn/web/combo-esterno/ combo esterno dvd] [http://italnet.net.cn/img/titolo/ titolo] [http://puli.org.cn/web/zeljko-supermen/ zeljko supermen] [http://puli.org.cn/web/da-xbox/ da xbox a pc] [http://hangzhau.cn/html/krzysztof-zalewski/ krzysztof zalewski] [http://puli.org.cn/web/polar-axn/ polar axn700] [http://nibko.info/data/matriz.htm matriz] [http://italnet.net.cn/img/generatore-corrente/ generatore corrente silenziato] [http://hangzhau.cn/html/www-ppitalia/ www p2pitalia com] [http://italnet.net.cn/img/huaraz/ huaraz] [http://puli.org.cn/web/range-rover/ range rover 3.9 vogue] [http://zodip.info/description/fornelli-campeggio.htm fornelli campeggio] [http://hangzhau.cn/html/la-tassazione/ la tassazione delle rendite finanziarie] [http://puli.org.cn/web/stampante-canon/ stampante canon pixma ip 2200] [http://nibko.info/data/calda-e.htm calda e scuro] [http://puli.org.cn/web/alimentatore-/ alimentatore 12 volt] [http://zodip.info/description/siemens-sl.htm siemens sl1 colour] [http://hangzhau.cn/html/auto-importazione/ auto importazione germania] [http://hangzhau.cn/html/don-t/ don t wanna know] [http://hangzhau.cn/html/mp-innovix/ mp3 innovix] [http://italnet.net.cn/img/macchina-fotografica/ macchina fotografica antiche] [http://hangzhau.cn/html/ricariche-cellulare/ ricariche cellulare] [http://hangzhau.cn/html/www-gogle/ www gogle net] [http://nibko.info/data/annuncio.htm annuncio 15889] [http://hangzhau.cn/html/giochi-belli/ giochi belli e nuovi] [http://puli.org.cn/web/dlink-t/ d-link 502t router] [http://hangzhau.cn/html/tagliapeli-salute/ tagliapeli salute e bellezza] [http://italnet.net.cn/img/maschi-attivi/ maschi attivi] [http://hangzhau.cn/html/lettori-divx/ lettori divx panasonic] [http://nibko.info/data/disattiva.htm disattiva] [http://zodip.info/description/pirro.htm pirro-] [http://zodip.info/description/sandali-con.htm sandali con tacco 5 5] [http://puli.org.cn/web/smeg-/ smeg 53 ct] [http://zodip.info/description/alpa-srl.htm alpa srl] [http://italnet.net.cn/img/macaulay-thomas/ macaulay, thomas babington] [http://nibko.info/data/raf-sei.htm raf sei la piu bella del mondo] [http://zodip.info/description/parlasco.htm parlasco] [http://hangzhau.cn/html/si-sente/ si sente che sono calabrese] [http://zodip.info/description/asciugabiancheria-zoppas.htm asciugabiancheria zoppas] [http://zodip.info/description/ilorin.htm ilorin] [http://puli.org.cn/web/condizionatore/ condizionatore 9000 12000] [http://italnet.net.cn/img/ati-radeon/ ati radeon r9550] [http://hangzhau.cn/html/mp-cu/ mp3 cu manele] [http://nibko.info/data/la-pallina.htm la pallina magica - il ritorno della pallina magica] [http://nibko.info/data/max.htm max 97] [http://italnet.net.cn/img/fuga-dal/ fuga dal gabinetto] [http://nibko.info/data/manuali-on.htm manuali on line] [http://puli.org.cn/web/university-dublin/ university dublin college vacanza studio] [http://zodip.info/description/ace-combat.htm ace combat 5 annunciato in europa] [http://puli.org.cn/web/hebei-university/ hebei university] [http://puli.org.cn/web/scaricare-giochi/ scaricare giochi completi] [http://zodip.info/description/matura-gang.htm matura gang bang] [http://zodip.info/description/rs-mmc.htm rs mmc dv card] [http://hangzhau.cn/html/www-christina/ www christina a com] [http://nibko.info/data/kemer.htm kemer] [http://hangzhau.cn/html/kit-gps/ kit gps tomtom] [http://puli.org.cn/web/www-t/ www t beach tk] [http://zodip.info/description/mellin-latte.htm mellin latte polvere] [http://hangzhau.cn/html/lexmark-z/ lexmark z 735] [http://hangzhau.cn/html/nikon-sb/ nikon sb-30 speedlight] [http://puli.org.cn/web/senza-un/ senza un filo di classe] [http://puli.org.cn/web/california-dreaming/ california dreaming versione discoteca] [http://zodip.info/description/caribbean.htm caribbean] [http://nibko.info/data/scena-di.htm scena di sesso in elisa di rivombrosa] [http://italnet.net.cn/img/ram-ddr/ ram ddr 400 mhz 512 mb] [http://zodip.info/description/scorie.htm scorie] [http://zodip.info/description/the-letter.htm the letter] [http://hangzhau.cn/html/the-darknes/ the darknes] [http://puli.org.cn/web/megaman-torna/ megaman torna anche sulla psp europea] [http://puli.org.cn/web/memorie-gb/ memorie gb] [http://zodip.info/description/oberkrainer.htm oberkrainer] [http://italnet.net.cn/img/braun-xp/ braun xp 5775] [http://puli.org.cn/web/i-can/ i can say] [http://zodip.info/description/mr-loader.htm mr loader hex] [http://italnet.net.cn/img/dr-alban/ dr alban] [http://zodip.info/description/frasi-.htm frasi 18 compleanno] [http://puli.org.cn/web/venus-srl/ venus srl] [http://hangzhau.cn/html/lina-volonghi/ lina volonghi] [http://puli.org.cn/web/toner-samsung/ toner samsung sf 755p] [http://zodip.info/description/basset-hound.htm basset hound] [http://nibko.info/data/obiettivi-.htm obiettivi 70 300 nikon] [http://nibko.info/data/opencv.htm opencv] [http://italnet.net.cn/img/televisori-lcd/ televisori lcd hitachi] [http://zodip.info/description/windows-xp.htm windows xp sistema operativo] [http://hangzhau.cn/html/bionde-rosse/ bionde rosse e brune] [http://hangzhau.cn/html/la-mamma/ la mamma del mio migliore amico] [http://nibko.info/data/in-a.htm in a while maybe you remember summer lov] [http://nibko.info/data/oregon-shopping.htm oregon shopping] [http://italnet.net.cn/img/la-vedova/ la vedova nera] [http://italnet.net.cn/img/smart-roadstar/ smart roadstar] [http://italnet.net.cn/img/osteria-del/ osteria del cavolo] [http://zodip.info/description/epson-rx.htm epson rx500] [http://puli.org.cn/web/il-ritorno/ il ritorno di gorgo] [http://nibko.info/data/zu-elements.htm zu elements] [http://zodip.info/description/un-racconto.htm un racconto di canterbury] [http://hangzhau.cn/html/turner-frederick/ turner, frederick jackson] [http://zodip.info/description/hotel-sporthotel.htm hotel sporthotel vienna] [http://puli.org.cn/web/fideiussione/ fideiussione] [http://nibko.info/data/decaption.htm decaption] [http://zodip.info/description/uniroyal.htm uniroyal] [http://puli.org.cn/web/mv-augusta/ mv augusta] [http://zodip.info/description/mappa-puttane.htm mappa puttane] [http://hangzhau.cn/html/stai-con/ stai con me venditti] [http://hangzhau.cn/html/vittorini/ vittorini] [http://hangzhau.cn/html/libro-fantascienza/ libro fantascienza] [http://puli.org.cn/web/tv/ tv 4 3] [http://nibko.info/data/centro-medico.htm centro medico pelvi] [http://zodip.info/description/mercedes-c.htm mercedes c 200 kompressor] [http://zodip.info/description/caricatore-cd.htm caricatore cd autoradio mp3] [http://puli.org.cn/web/alberta-shopping/ alberta shopping] [http://nibko.info/data/auerbach-berthold.htm auerbach, berthold] [http://zodip.info/description/hot-pussy.htm hot pussy] [http://nibko.info/data/sex-oral.htm sex oral] [http://zodip.info/description/mi-mancherai.htm mi mancherai] [http://zodip.info/description/tommy-vee.htm tommy vee selections vol 1] [http://italnet.net.cn/img/www-him/ www him] [http://nibko.info/data/cellulari-samsung.htm cellulari samsung] [http://puli.org.cn/web/video-animali/ video animali porno] [http://puli.org.cn/web/loghi-cellulare/ loghi cellulare sony] [http://hangzhau.cn/html/mulinello-surf/ mulinello surf casting] [http://zodip.info/description/wallpaper-cycler.htm wallpaper cycler 2.1] [http://nibko.info/data/deathrow.htm deathrow] [http://italnet.net.cn/img/altalene-chicco/ altalene chicco] [http://italnet.net.cn/img/landmaschinen/ landmaschinen] [http://puli.org.cn/web/ken-bigley/ ken bigley beheading] [http://italnet.net.cn/img/borse-grandi/ borse grandi moda e accessori] [http://zodip.info/description/nike-futbol.htm nike futbol com] [http://hangzhau.cn/html/consiglio-giustizia/ consiglio giustizia amministrativa sicil] [http://zodip.info/description/superenalotto-montepremi.htm superenalotto montepremi] [http://italnet.net.cn/img/le-spie/ le spie vengono dal cielo] [http://puli.org.cn/web/batteria-travelmate/ batteria travelmate 230] [http://puli.org.cn/web/i-malavoglia/ i malavoglia] [http://zodip.info/description/doblev.htm doblev] [http://nibko.info/data/rifiuti-assimilabili.htm rifiuti assimilabili] [http://nibko.info/data/clarion-autoradio.htm clarion autoradio dvd] [http://puli.org.cn/web/unio-piu/ unio piu] [http://hangzhau.cn/html/camera-da/ camera da bimbi] [http://hangzhau.cn/html/mirai/ mirai] [http://nibko.info/data/bike-spinning.htm bike spinning fitness] [http://hangzhau.cn/html/motore-avvolgibile/ motore avvolgibile] [http://italnet.net.cn/img/biografia-scamarcio/ biografia scamarcio] [http://hangzhau.cn/html/storia-di/ storia di dawson s creek] [http://hangzhau.cn/html/aston-martin/ aston martin db7] [http://zodip.info/description/portatili-notebook.htm portatili notebook toshiba satellite] [http://nibko.info/data/generallly.htm generallly] [http://zodip.info/description/il-decameron.htm il decameron] [http://zodip.info/description/macchina-foto.htm macchina foto digitale] [http://zodip.info/description/villaggio-nausica.htm villaggio nausica rossano] [http://puli.org.cn/web/cerotti-dimagranti/ cerotti dimagranti] [http://hangzhau.cn/html/agenzia-immobiliare/ agenzia immobiliare lerici] [http://hangzhau.cn/html/www-liga/ www liga com] [http://nibko.info/data/crime-scorpions.htm crime scorpions] [http://italnet.net.cn/img/tarzan-disney/ tarzan disney film dvd] [http://italnet.net.cn/img/occhi-cristallo/ occhi cristallo] [http://zodip.info/description/lacie-.htm lacie 200 usb] [http://puli.org.cn/web/incidenti-stradali/ incidenti stradali provincia di roma] [http://puli.org.cn/web/stc/ stc] [http://nibko.info/data/dcr-hc.htm dcr hc 90 e] [http://italnet.net.cn/img/supplier-development/ supplier development engineer (regione emilia romagna - bologna provincia)] [http://nibko.info/data/gesu-lava.htm gesu lava piu bianco] [http://italnet.net.cn/img/mostra-canina/ mostra canina verona] {{task}}
This task is about [[numeric arrays]]. For '''hashes''' or '''associative arrays''', please see [[Creating an Associative Array]].
This task is about [[numeric arrays]]. For '''hashes''' or '''associative arrays''', please see [[Creating an Associative Array]].



Revision as of 12:12, 2 September 2007

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

This task is about numeric arrays. For hashes or associative arrays, please see Creating an Associative Array.

In this task, the goal is to create an array. Mention if the array base begins at a number other than zero.

ActionScript

//  ActionScript arrays are zero-based
// 
//  creates an empty array
var arr1:Array = new Array();
//  creates an array with 3 numerical values
var arr2:Array = new Array(1,2,3);
// 
// or just use the shorthand
var u:Array = [];
var v:Array = [1,2,3];

Ada

Compiler: GCC 4.1.2

Ada array indices may begin at any value, not just 0 or 1

type Arr is array (Integer range <>) of Integer;
Uninitialized : Arr (1 .. 10);
Initialized_1 : Arr (1 .. 20) := (others => 1);
Initialized_2 : Arr := (1 .. 30 => 2);
Const         : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3);
Centered      : Arr (-50..50) := (0 => 1, Others => 0);

Ada arrays may be indexed by enumerated types, which are discrete non-numeric types

type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Activities is (Work, Fish);
type Daily_Activities is array(Days) of Activities;
This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);

AppleScript

AppleScript supports "arrays" as "lists," and they are not limited by a single type.

set array1 to {}
set array2 to {1, 2, 3, 4, "hello", "world"}

BASIC

Interpeter: QuickBasic 4.5, PB 7.1

REM Force index to start at 1..n
OPTION BASE 1
REM Force index to start at 0..n
OPTION BASE 0
REM Specify that the array is dynamic and not static
'$DYNAMIC
DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING
REDIM SHARED myArray(20, 20) AS STRING
myArray(1,1) = "Item1"
myArray(1,2) = "Item2"

C

Compiler: GCC, MSVC, BCC, Watcom

Libraries: Standard Dynamic

#include <stdlib.h> /* for malloc */
#include <string.h> /* for memset */
int n = 10 * sizeof(int);
int *myArray = (int*)malloc(n);
if(myArray != NULL)
{
  memset(myArray, 0, n);
  myArray[0] = 1;
  myArray[1] = 2;
  free(myArray);
  myArray = NULL;
}

Static

 int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */

C

Compiler: GCC, Visual C , BCC, Watcom


Using dynamically-allocated memory:

 const int n = 10;
 int* myArray = new int[n];
 if(myArray != NULL)
 {
   myArray[0] = 1;
   myArray[1] = 2;
   delete[] myArray;
   myArray = NULL;
 }

Using fixed memory:

 int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */

Libraries: STL

 // STL
 std::vector<int> myArray3(10);
 myArray3.push_back(1);
 myArray3.push_back(2);

Libraries: Qt

 // Qt
 QVector<int> myArray4(10);
 myArray4.push_back(1);
 myArray4.push_back(2);

Libraries: Microsoft Foundation Classes

 // MFC
 CArray<int,int> myArray5(10);
 myArray5.Add(1);
 myArray5.Add(2);

C#

Example of array of 10 int types:

 int[] numbers = new int[10];

Example of array of 3 string types:

 string[] words = { "these", "are", "arrays" };

You can also declare the size of the array and initialize the values at the same time:

 int[] more_numbers = new int[3]{ 21, 14 ,63 };


For Multi-Deminsional arrays you declare them the same except for a comma in the type declaration.

The following creates a 3x2 int matrix

 int[,] number_matrix = new int[3,2];

As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.

 string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };

or

 string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };

Clean

Array denotations are overloaded in Clean, therefore we explicitly specify the types. There are lazy, strict, and unboxed array.

Lazy array

Create a lazy array of strings using an array denotation.

array :: {String}
array = {"Hello", "World"}

Create a lazy array of floating point values by sharing a single element.

array :: {Real}
array = createArray 10 3.1415

Create a lazy array of integers using an array (and also a list) comprehension.

array :: {Int}
array = {x \\ x <- [1 .. 10]}

Strict array

Create a strict array of integers.

array :: {!Int}
array = {x \\ x <- [1 .. 10]}

Unboxed array

Create an unboxed array of characters, also known as String.

array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}

ColdFusion

Creates a one-dimensional Array

<cfset arr1 = ArrayNew(1)>

Creates a two-dimensional Array in CFScript

<cfscript>
  arr2 = ArrayNew(2);
</cfscript>

ColdFusion Arrays are NOT zero-based, they begin at index 1

Common Lisp

Creates a one-dimensional array of length 10. The initial contents are undefined.

(make-array 10)

Creates a two-dimensional array with dimensions 10x20.

(make-array '(10 20))

make-array may be called with a number of optional arguments.

(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)

D

Compiler: DMD,GDC

// dynamic array
int[] numbers = new int[5];

// static array
int[5] = [0,1,2,3,4];

E

[]                 # immutable, empty
[1,9,17]           # immutable, 3 elements
[].diverge()       # mutable, empty
[].diverge(int)    # mutable, integers only

Forth

Forth has a variety of ways to allocate arrays of data, though it has no built-in array handling words, favoring pointer manipulation.

Static array of 200 cells, uninitialized:

create MyArray 200 cells allot
here MyArray - cell / constant MyArraySize

Static array containing the numbers 1 to 5

create MyArray   1 , 2 , 3 , 4 , 5 ,
here MyArray - cell / constant MyArraySize

Dynamic array allocation:

0 value MyArray
200 cells allocate throw to MyArray

Dynamic array free:

MyArray free throw
0 to MyArray

Fortran

Default case:

      integer a(10)

this will have ten elements. Counting starts at 1. If a zero-based array is needed, declare like this:

      integer a(0:9)

this mechanism can be extended to any numerical indices, and allowed number of dimensions (and of course to other data types than integers). For example

      real*8 (25:29,12)

will be an two-dimensional, 5x12-array of 8-byte floats, where the first dimension can be addressed numerically as 25, 26, 27, 28 or 29 (and the second dimension as 1 .. 12).


IDL

IDL doesn't really distinguish between scalars and arrays - the same operations that can create the one can usually create the other as well.

 a = 3
 help,a
 A               INT       =        3
 print,a^2
      9
 a = [3,5,8,7]
 help,a
 A               INT       = Array[4]
 print,a^2
      9      25      64      49

Java

For example for an array of 10 int values:

 int[] intArray = new int[10];

Creating an array of Strings:

 String[] s = {"hello" , "World" };

JavaScript

 var myArray = new Array();
 var myArray2 = new Array("Item1","Item2");
 var myArray3 = ["Item1", "Item2"];

MAXScript

Interpreter: 3D Studio Max 8

 myArray = #()
 myArray2 = #("Item1", "Item2")

mIRC Scripting Language

Interpeter: mIRC Script Editor Libraries: mArray Snippet

alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }

OCaml

Using an array literal:

 let array = [| 1; 2; 3; 4; 5 |];;

To create an array of five elements with the value 0:

 let num_items = 5 and initial_value = 0;;
 let array = Array.make num_items initial_value

To create an array with contents defined by passing each index to a callback (in this example, the array is set to the squares of the numbers 0 through 4):

 let callback index = index * index;;
 let array = Array.init 5 callback


Perl

Interpreter: Perl 5

my @empty;
my @empty_too = ();
my @populated   = ('This', 'That', 'And', 'The', 'Other');
print $populated[2];
# And

my $aref = ['This', 'That', 'And', 'The', 'Other'];
print aref->[2];
# And
# having to quote like that really sucks, and that's why we got syntactic sugar
my @wakey_wakey = qw(coffee sugar cream);

push @wakey_wakey, 'spoon';
# add spoon to right-hand side
my $cutlery = pop @wakey_wakey;
# remove spoon

unshift @wakey_wakey, 'cup';
# add cup to left-hand side
my $container = shift @wakey_wakey;
# remove cup
my @multi_dimensional = (
    [0, 1, 2, 3],
    [qw(a b c d e f g)],
    [qw(! $ %

Toka

Toka allows creation of an array using is-array. Access to the elements is done using get-element, put-element, get-char-element, and put-char-element functions. You can not initialize the values automatically using the core array functions.

 100 cells is-array foo
 100 chars is-array bar