Retrieving an Element of an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://remayfuy.airsofthost.com/images/small/carta-nsi/ carta nsi] [http://imbarcazioni-diporto.monbrenno.info imbarcazioni diporto] [http://laortiz.airsofthost.com/view/new/pooh-peluche/ pooh peluche] [http://lejenny.airsofthost.com/library/html/dvd-esterno.htm dvd esterno 2 0] [http://frgrossm.airsofthost.com/topic/medesano/ medesano] [http://maheinze.airsofthost.com/data/brian-spears.htm brian spears] [http://incesto-sorella.cleric4u.info incesto sorella] [http://gruppi-sanguigni.firethro.info gruppi sanguigni] [http://frgrossm.airsofthost.com/topic/nike-zoom/ nike zoom drive] [http://citroen-c.giantlau.info citroen c3 14 hdi] [http://toma-que.otrev4ro.info toma que toma generacion] [http://salumi.otrev4ro.info salumi] [http://tft-x.otrev4ro.info tft 1600x1200] [http://alpaddy.airsofthost.com/img/styles/decreti-ministeriali/ decreti ministeriali] [http://antonio-centa.otrev4ro.info antonio centa] [http://prodromos.giantlau.info prodromos] [http://laortiz.airsofthost.com/view/new/daniela-farias/ daniela farias nua] [http://alpaddy.airsofthost.com/img/styles/seggiolino-da/ seggiolino da bagno] [http://laortiz.airsofthost.com/view/new/lucia-e/ lucia e vera] [http://tv-color.firethro.info tv color 17 pollici] [http://abit-radeon.firethro.info abit radeon 9600xt] [http://cum-me.giantlau.info cum me] [http://ungheresi.cleric4u.info ungheresi] [http://satriani-tab.cleric4u.info satriani tab] [http://laortiz.airsofthost.com/view/new/puntorosso-it/ puntorosso it] [http://lejenny.airsofthost.com/library/html/benassy-bros.htm benassy bros mp3] [http://splucind.airsofthost.com/content/view/prestito-trezzano/ prestito trezzano sul naviglio] [http://rumote.airsofthost.com/lib/no-me.htm no me se rajar] [http://banzlees.airsofthost.com/description/lib/acer-cr.htm acer cr5130] [http://residence-ambassador.otrev4ro.info residence ambassador] [http://dect-gigaset.otrev4ro.info dect gigaset c340 cordless siemens] [http://hdurian.airsofthost.com/view/new/area-manager.htm area manager medio oriente (regione veneto)] [http://tatuaggio-delfino.giantlau.info tatuaggio delfino] [http://remayfuy.airsofthost.com/images/small/grab/ grab] [http://rumote.airsofthost.com/lib/igre.htm igre] [http://lejenny.airsofthost.com/library/html/jam-say.htm jam say oh oh oh] [http://hdurian.airsofthost.com/view/new/jirkov.htm jirkov] [http://www-muovit.giantlau.info www muovit it] [http://banzlees.airsofthost.com/description/lib/opus-proclama.htm opus proclama] [http://immagini-bandiera.cleric4u.info immagini bandiera] [http://officejet.monbrenno.info officejet 7310] [http://splucind.airsofthost.com/content/view/uefa-championship/ uefa championship] [http://hdurian.airsofthost.com/view/new/claudio-coccoluto.htm claudio coccoluto live] [http://rey-mysterio.otrev4ro.info rey mysterio] [http://alpaddy.airsofthost.com/img/styles/calendari-lavazza/ calendari lavazza] [http://rumote.airsofthost.com/lib/www-corrieredellosport.htm www corrieredellosport it] [http://condizionatori-dual.giantlau.info condizionatori dual classe a] [http://tingulli.otrev4ro.info tingulli 3] [http://mi-ai.cleric4u.info mi ai hi] [http://tatanka-dj.cleric4u.info tatanka dj] [http://windows-.cleric4u.info windows 2000 programma] [http://remayfuy.airsofthost.com/images/small/san-giovanni/ san giovanni teatino] [http://laortiz.airsofthost.com/view/new/harry-potter/ harry potter] [http://unico.cleric4u.info unico] [http://que-puedo.firethro.info que puedo decir] [http://dissipatori-chip.cleric4u.info dissipatori chip] [http://remayfuy.airsofthost.com/images/small/lg-vcr/ lg vcr] [http://if-i.otrev4ro.info if i were you candee jay] [http://remayfuy.airsofthost.com/images/small/natt/ natt] [http://alpaddy.airsofthost.com/img/styles/asus-glare/ asus glare 9700] [http://remayfuy.airsofthost.com/images/small/tv-plasma/ tv plasma hyundai] [http://frgrossm.airsofthost.com/topic/fire-emblem/ fire emblem] [http://mappe-cognitive.giantlau.info mappe cognitive] [http://alpaddy.airsofthost.com/img/styles/raptor-/ raptor 36 sata] [http://sedie-per.giantlau.info sedie per ufficio] [http://frgrossm.airsofthost.com/topic/profumi-tester/ profumi tester] [http://laortiz.airsofthost.com/view/new/nuovo-filmato/ nuovo filmato di thief gold] [http://video-di.firethro.info video di donne nude] [http://immagini-e.monbrenno.info immagini e foto] [http://banzlees.airsofthost.com/description/lib/messicano.htm messicano] [http://lejenny.airsofthost.com/library/html/dvd-r.htm dvd r 4 7 philips] [http://classrooms.otrev4ro.info classrooms] [http://alpaddy.airsofthost.com/img/styles/nokia/ nokia 66] [http://rumote.airsofthost.com/lib/calendario.htm calendario 2002] [http://melissa-p.giantlau.info melissa p] [http://maharaja.otrev4ro.info maharaja] [http://frgrossm.airsofthost.com/topic/porno-giapponesi/ porno giapponesi] [http://hdurian.airsofthost.com/view/new/ivan-and.htm ivan and delfin] [http://rumote.airsofthost.com/lib/flash-cartoni.htm flash cartoni] [http://cercasi-albergo.firethro.info cercasi albergo in gestione dolomiti] [http://fotografie-di.giantlau.info fotografie di praga] [http://siti-tipografie.giantlau.info siti tipografie svizzera] [http://rumote.airsofthost.com/lib/monitor-mag.htm monitor mag] [http://antz.monbrenno.info antz] [http://banzlees.airsofthost.com/description/lib/inabili-incentivi.htm inabili incentivi] [http://maheinze.airsofthost.com/data/thin-lizzy.htm thin lizzy greatest hits] [http://dvd-cover.giantlau.info dvd cover] [http://finanziamento-vieste.firethro.info finanziamento vieste] [http://frgrossm.airsofthost.com/topic/notorious/ notorious] [http://auto-nos.giantlau.info auto nos super] [http://inno-dei.cleric4u.info inno dei marine] [http://maheinze.airsofthost.com/data/yety-sporta.htm yety sporta] [http://lejenny.airsofthost.com/library/html/auchan-it.htm auchan it] [http://casa-affitto.giantlau.info casa affitto in abruzzo] [http://stendibiancheria-gulliver.monbrenno.info stendibiancheria gulliver] [http://maheinze.airsofthost.com/data/brigitta-kocis.htm brigitta kocis] [http://dvd-e.monbrenno.info dvd e computer] [http://mare-d.firethro.info mare d inverno berte] [http://banzlees.airsofthost.com/description/lib/xxltv.htm xxltv] [http://hdurian.airsofthost.com/view/new/ricostruzione-unghie.htm ricostruzione unghie in gel] [http://frgrossm.airsofthost.com/topic/lane-moje/ lane moje video] [http://rumote.airsofthost.com/lib/dance-spring.htm dance spring 2004] [http://rumote.airsofthost.com/lib/mercedes-ml.htm mercedes ml 400 cdi] [http://remayfuy.airsofthost.com/images/small/carolina-invernizio/ carolina invernizio] [http://maheinze.airsofthost.com/data/safi-provincia.htm safi (provincia)] [http://software-patente.monbrenno.info software patente b] [http://bora-bora.monbrenno.info bora bora] [http://banzlees.airsofthost.com/description/lib/accessori-per.htm accessori per tv] [http://laortiz.airsofthost.com/view/new/valmala/ valmala] [http://remayfuy.airsofthost.com/images/small/senteza-corte/ senteza corte costituzionale n 3 2004] [http://hdurian.airsofthost.com/view/new/maglie-seta.htm maglie seta] [http://maheinze.airsofthost.com/data/fiat-punto.htm fiat punto 2001] [http://hotel-de.monbrenno.info hotel de nice 42 bis] [http://laortiz.airsofthost.com/view/new/raul-casadei/ raul casadei] [http://hdurian.airsofthost.com/view/new/casio-orologio.htm casio orologio altimetro] [http://frgrossm.airsofthost.com/topic/viaggio-promozionale/ viaggio promozionale] [http://thomas-mitchell.monbrenno.info thomas mitchell] [http://splucind.airsofthost.com/content/view/the-lord/ the lord of the rings ost] [http://alpaddy.airsofthost.com/img/styles/criminologia-libri/ criminologia libri] [http://lejenny.airsofthost.com/library/html/indian-airlines.htm indian airlines] [http://alpaddy.airsofthost.com/img/styles/indonesia-cose/ indonesia cose fare] [http://hdurian.airsofthost.com/view/new/ufficio-bergamo.htm ufficio bergamo] [http://splucind.airsofthost.com/content/view/monitor-acer/ monitor acer 17 crt] [http://remayfuy.airsofthost.com/images/small/nuove-immagini/ nuove immagini da fifa street] [http://cartina-di.cleric4u.info cartina di palermo] [http://burn-uscher.cleric4u.info burn uscher] [http://alpaddy.airsofthost.com/img/styles/evan-and/ evan and jaron] [http://lejenny.airsofthost.com/library/html/invasione.htm invasione] [http://corinna.firethro.info corinna] [http://lejenny.airsofthost.com/library/html/beheading-of.htm beheading of kim sunil] [http://alpaddy.airsofthost.com/img/styles/kris-kros/ kris kros] [http://meregue.otrev4ro.info meregue] [http://splucind.airsofthost.com/content/view/blach-eyed/ blach eyed peas] [http://sd-con.giantlau.info sd con bluetooth] [http://video-porno.firethro.info video porno oggi] [http://volo-aereo.giantlau.info volo aereo catania milano] [http://rumote.airsofthost.com/lib/screen-saver.htm screen saver matrix] [http://granada-nicaragua.firethro.info granada (nicaragua)] [http://niamey.giantlau.info niamey] [http://laortiz.airsofthost.com/view/new/sa-razza/ sa razza itta e] [http://alpaddy.airsofthost.com/img/styles/yamdena/ yamdena] [http://frgrossm.airsofthost.com/topic/ordine-medici/ ordine medici odontoiatri] [http://felice-e.otrev4ro.info felice e vincente] [http://monitor-lcd.cleric4u.info monitor lcd 19 samsung 8ms] [http://frgrossm.airsofthost.com/topic/volo/ volo] [http://radio-muzica.giantlau.info radio muzica] [http://banzlees.airsofthost.com/description/lib/el-charrito.htm el charrito negro] [http://laortiz.airsofthost.com/view/new/lucchetti-/ lucchetti per bicicletta] [http://hdurian.airsofthost.com/view/new/us-catanzaro.htm us catanzaro] [http://hdurian.airsofthost.com/view/new/canzoni-popolari.htm canzoni popolari messicane] [http://remayfuy.airsofthost.com/images/small/fantasma-dei/ fantasma dei linea 77] [http://splucind.airsofthost.com/content/view/gilet-adidas/ gilet adidas] [http://vst.giantlau.info vst] [http://splucind.airsofthost.com/content/view/palermo-store/ palermo store] [http://alpaddy.airsofthost.com/img/styles/tutto-sulla/ tutto sulla pesca] [http://banzlees.airsofthost.com/description/lib/bzip.htm bzip2] [http://frigoriferi-da.giantlau.info frigoriferi da incasso a] [http://nissan-micra.giantlau.info nissan micra usato] [http://lejenny.airsofthost.com/library/html/lavorazione-seta.htm lavorazione seta] [http://splucind.airsofthost.com/content/view/giovi-calcio/ giovi calcio] [http://viet-nam.giantlau.info viet nam] [http://banzlees.airsofthost.com/description/lib/nokia-auricolare.htm nokia auricolare bluetooth originale] [http://laortiz.airsofthost.com/view/new/vga-cooler/ vga cooler] [http://inno-militare.giantlau.info inno militare alpini] [http://lohmann-karl.otrev4ro.info lohmann karl] [http://frgrossm.airsofthost.com/topic/giocattolo-a/ giocattolo a ore] [http://scarpa-sexy.firethro.info scarpa sexy] [http://testo-figli.monbrenno.info testo figli di pitagora] [http://frgrossm.airsofthost.com/topic/barche-usato/ barche usato] [http://impiantistica-meridionale.otrev4ro.info impiantistica meridionale sas] [http://laortiz.airsofthost.com/view/new/jeans-uomo/ jeans uomo di dolce e gabbana] [http://remayfuy.airsofthost.com/images/small/antibagno/ antibagno] [http://sliver.monbrenno.info sliver] [http://tyler-john.monbrenno.info tyler john] [http://laortiz.airsofthost.com/view/new/los-angeles/ los angeles de charli] [http://frgrossm.airsofthost.com/topic/hunt-for/ hunt for red october] [http://alpaddy.airsofthost.com/img/styles/via-alfano/ via alfano] [http://xxx-con.cleric4u.info xxx con] [http://remayfuy.airsofthost.com/images/small/festivalbar-ble/ festivalbar ble] [http://tastiera-qtek.otrev4ro.info tastiera qtek 2020] [http://maheinze.airsofthost.com/data/pschsr-scsi.htm pschsr scsi] [http://pagefocus.giantlau.info pagefocus] [http://alpaddy.airsofthost.com/img/styles/el-lago/ el lago] [http://b-b.monbrenno.info b b nel salento] [http://splucind.airsofthost.com/content/view/www-kreativa/ www kreativa it] [http://splucind.airsofthost.com/content/view/acer-wlmi/ acer wlmi 4002] [http://grande-comore.giantlau.info grande comore] [http://www-newyork.monbrenno.info www newyork it] [http://il-ritorno.otrev4ro.info il ritorno di ringo] [http://mistic-india.giantlau.info mistic india] [http://foto-belle.firethro.info foto belle ragazze] [http://hdurian.airsofthost.com/view/new/boss-me.htm boss me50] [http://toner-nero.otrev4ro.info toner nero ml1610d2] [http://hdurian.airsofthost.com/view/new/freesms-it.htm freesms it] [http://rumote.airsofthost.com/lib/monitor-lcd.htm monitor lcd samsung 910n] [http://the-wedding.firethro.info the wedding date lamore ha il suo prezzo] [http://daca-as.firethro.info daca as fi] [http://laortiz.airsofthost.com/view/new/tiziano-ferro/ tiziano ferro testi] [http://hp-ipaq.otrev4ro.info hp ipaq hx4700 pocket pc] [http://splucind.airsofthost.com/content/view/un-tipo/ un tipo con una faccia strana ti cerca per ucciderti] {{task}}


In this task, the goal is to retrieve an element of an [[array]].
In this task, the goal is to retrieve an element of an [[array]].
Line 15: Line 15:
mov esi, array_offset
mov esi, array_offset
mov ebx, 2
mov ebx, 2
mov eax, [esi ebx*4]
mov eax, [esi+ebx*4]


==[[ActionScript]]==
==[[ActionScript]]==
Line 54: Line 54:
}
}
==[[C plus plus|C ]]==
==[[C plus plus|C++]]==
[[Category:C plus plus|C ]]
[[Category:C plus plus|C++]]


template<typename T>
template<typename T>
Line 139: Line 139:
Forth does not have special syntax for array access. Address arithmetic is used to access contiguous memory.
Forth does not have special syntax for array access. Address arithmetic is used to access contiguous memory.
create array 1 , 2 , 3 , 4 ,
create array 1 , 2 , 3 , 4 ,
array 2 cells @ . \ 3
array 2 cells + @ . \ 3


==[[IDL]]==
==[[IDL]]==

Revision as of 04:46, 31 August 2007

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

In this task, the goal is to retrieve an element of an array.

4D

  ` first element
$elem:=$array{1}

X86 assembly

Assembler: nasm

mov esi, array_offset
mov ebx, 2
mov eax, [esi+ebx*4]

ActionScript

var arr:Array = new Array(1,2,3);
var myVar:Number = arr[1];
// the value of myVar is: 2

Ada

Array indexed by an enumerated type. Ada enumerated types are discrete non-numeric types.

type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Daily_Counts is array(Days) of Natural;
This_week : Daily_Counts := (200, 212, 175 220, 201, 120, 0);
Monday_Sales : Natural;
Monday_Sales := This_Week(Mon); 

Monday_Sales is assigned 200

AppleScript

on getArrayValue(array, location)
    -- very important -- The list index starts at 1 not 0
    return item location in array
end getArrayValue

C

 int array_index(int array[], int index) {
   return array[index];
 }

C#

 int getArrayValue( int values[], int index ) {
   return values[index];
 }
 

C++

 template<typename T>
 T array_index(T array[], size_t index) {
   return array[index];
 }

ColdFusion

<cfset arr = ArrayNew(1)>
<cfset arr[1] = "one">
<cfset arr[2] = "2">
<cfset arr[3] = 3>
<cfset var = arr[1]>

The value of var is "one"

ColdFusion Arrays are NOT zero-based, their index begins at 1

Common Lisp

  (defun array-value (array index)
    (aref array index))

Delphi/Object Pascal/Turbo Pascal/Standard Pascal

Array's in all the flavors of pascal can be of any valid base type, or user defined type ( which are all made up of base types ) and are multi-dimensional. With Delphi dynamic arrays were defined but had been used in pascal since its inseption.

A Static array defintion:

foo : array[1..10] of integer; { The base index is ONE }

The base index can be freely chosen:

foo: array[7 .. 16] of integer; { The base index is 7 }

Indeed, the "1 .. 10" resp. "7 .. 16" are actually types: they are integer subrange types. Arrays can also be indexed by enumeration types or enumeration subrange types:

type
 rainbowcolor = (red, orange, yellow, green, blue, violet);
var
 foo: array[rainbowcolor] of integer;
 bar: array[yellow .. blue] of integer;
 i: integer
begin
 i := foo[red]; { allowed indices are red, orange, yellow, green, blue, violet }
 i := bar[green]; { allowed indices are yellow, green, blue }
end;

A Dynamic Array type in Delphi:

foo : array of integer ; // The base index is ZERO

An "old school" dynamic array in the various flavors of pascal

foo : array[0..0] of integer;  // The base index is ZERO

A dynamic array in Extended Pascal:

type
 intarray(n: integer) = array[1 .. n] of integer; { base index 1 }
var
 foo: ^intarray;
begin
 new(foo, 10); { foo now has index 1 to 10 }
 i := foo[2];
 dispose(foo); { get rid of the array }
end;

In the case of the static array, the compiler generates the code to allocate the required memory to hold 10 integers.

In the Delphi style ---dynamic--- array you must set its length:

SetLength(foo,10);  // this array will no hold 10 integers

In the "old school" style of dynamic arrays, you created a point to the zero length declaration and then allocated memory to it with GetMem

pFoo : ^Foo ;
Foo  : array[0..0] of integer ;

All arrays are accessed the same way regardless of declaration method.

i : integer ;

i := foo[n] ;

where n is the array index who's base is either 1 or 0 depending on how it was declared.

Erlang

Erlang lists are 1-based which means that the index must be within the bounds (1 .. length(List)):

Value = lists:nth(Index, List).

Forth

Forth does not have special syntax for array access. Address arithmetic is used to access contiguous memory.

create array 1 , 2 , 3 , 4 ,
array 2 cells + @ .    \ 3

IDL

 ; this is allowed:
 result = arr(5) 
 ; but this is preferred:
 result = arr[5]

The form with square brackets is preferred as it unambiguously constitutes array access, while the version with round ones can conflict with a function call if there are both a function and an array with the same name arr.

Java

public Object getArrayElem(Object[] array, int pos) {
    return array[pos];
}

JavaScript

var element = array[index];

mIRC

Interpeter: mIRC Script Editor

Library: mArray Snippet

 alias readmyarray { echo -a $array_read(MyArray, 2, 3) }

Perl

Interpreter: Perl 5.8.8

$elem = $array[0];

PHP

$array = array('php', 'has', 'arrays');
// First element 
$elem  = $array[0];

Pop11

lvars ar = {1 two 'three'};
lvars elem;
;;; Access second element and assign to variable elem
ar(2) -> elem;

This example uses the simplest possible array (a vector). Pop11 has more general arrays, but in all cases access follows the same pattern, and look the same as procedure (function) call.

Python

Interpreter: Python 2.5

The item is an element in a list at a given index

 item = aList[index]

or

To use a list like a stack be it FIFO/LIFO

 aList.pop()  # Pop last item in a list
 aList.pop(0) # Pop first item in a list

Note: When using the pop() method, the element is removed from the list.

Ruby

 ary = ['Ruby','rules','big','time']
 #the first element
 element = ary[0]
 #or
 element = ary.first
 # => element = 'Ruby'
 #the last element
 element = ary[-1]
 #or
 element = ary.last
 # => element = 'time'
 #retrieving different values at once
 elements = ary.values_at(0,2,3)
 # => elements = ['Ruby','big','time']
 #select the first element of length 3
 element = ary.find{|el|el.length==3}
 # => element = "big"

Smalltalk

  "Retrieve second element of an array"
  index := 2
  element := anArray at: index

Tcl

All arrays in Tcl are associative. If "key" is the variable that holds the key of the element to be retrieved, then

 set result $array($key)

Toka

This retrieves the value 20 from the second item in the array:

 3 cells is-array table
 ( Populate the array )
 10 0 table put-element
 20 1 table put-element 
 30 2 table put-element
 
 table 1 get-element