Create a two-dimensional array at runtime: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
No edit summary
Line 1: Line 1:
{{task}}
[http://blog.rigour.info/web/renata-vigano/ renata vigano] [http://dir.rigour.info/www-webank/ www webank it] [http://down.rigour.info/blog/over-the.htm over the raimbow download] [http://pagina.rigour.info/oakley-a/ oakley a frame black] [http://it.rigour.info/topic/nintendo-gameboy/ nintendo gameboy advance] [http://pagina.rigour.info/zucconi-vittorio/ zucconi vittorio] [http://milano.rigour.info/hp-ca.htm hp c6657a] [http://up.rigour.info/description/lib/acer-navigatore.htm acer navigatore] [http://pagina.rigour.info/concorsi-per/ concorsi per call center] [http://here.rigour.info/blog/ati-.htm ati 9800 pro 128 mb agp] [http://gratis.rigour.info/content/view/mo-vol.htm m2o vol5] [http://blog.rigour.info/web/lg-lcd/ lg lcd 19 flatron] [http://paga.rigour.info/appendici-carrelli/ appendici carrelli] [http://online.rigour.info/hp-all/ hp all in one 1610] [http://online.rigour.info/felicita-albano/ felicita albano e romina power] [http://uve.rigour.info/blog/prima-station.htm prima station wagon] [http://online.rigour.info/stampanti-c/ stampanti c86] [http://down.rigour.info/blog/crno-i.htm crno i zlatno] [http://guest.rigour.info/library/html/fiori-di/ fiori di bach come sceglierli] [http://online.rigour.info/civitanova-marche/ civitanova marche ristorante la staffa] [http://blog.rigour.info/web/monitor-per/ monitor per pc] [http://dir.rigour.info/pime-milano/ pime milano] [http://here.rigour.info/blog/sony-lettore.htm sony lettore dvd divx portatile] [http://online.rigour.info/configurazione-wap/ configurazione wap] [http://up.rigour.info/description/lib/www-samsung.htm www samsung hi fi com] [http://online.rigour.info/lollipop-you/ lollipop you] [http://blog.rigour.info/web/caricatore-cd/ caricatore cd clarion] [http://all.rigour.info/incontrare-donna/ incontrare donna russa] [http://italy.rigour.info/blog/michel-iett.htm michel iett] [http://dir.rigour.info/www-telemarket/ www telemarket it] [http://italy.rigour.info/blog/grandpa.htm grandpa] [http://up.rigour.info/description/lib/albergo-economico.htm albergo economico avignone] [http://load.rigour.info/view/new/hp-colorado.htm hp colorado] [http://up.rigour.info/description/lib/takvi-kao.htm takvi kao ti] [http://guest.rigour.info/library/html/del-axim/ del axim x50 gps] [http://all.rigour.info/cherry-liquore/ cherry liquore] [http://speed.rigour.info/lene.htm lene] [http://italy.rigour.info/blog/que-lloro.htm que lloro de sin bandera] [http://gratis.rigour.info/content/view/kit-casse.htm kit casse sony] [http://italy.rigour.info/blog/isola-dei.htm isola dei famosi2] [http://it.rigour.info/topic/modelli-pettinature/ modelli pettinature] [http://dir.rigour.info/leo/ leo84] [http://all.rigour.info/mazda-mx/ mazda mx 5 twins] [http://here.rigour.info/blog/who-wants.htm who wants to live forever] [http://italy.rigour.info/blog/enter-the.htm enter the matrix vende bene anche in italia] [http://guest.rigour.info/library/html/profil/ profil] [http://italy.rigour.info/blog/shuffle-.htm shuffle 1 gb] [http://all.rigour.info/piedi-donne/ piedi donne] [http://content.rigour.info/html/video-esecuzioni/ video esecuzioni in irak] [http://italy.rigour.info/blog/davinia.htm davinia] [http://milano.rigour.info/monitor-lcd.htm monitor lcd 17 per pc] [http://it.rigour.info/topic/swet/ swet] [http://dir.rigour.info/clarima-banca/ clarima banca] [http://down.rigour.info/blog/salsa-corso.htm salsa corso] [http://dir.rigour.info/dymo-labelwriter/ dymo labelwriter 400 turbo] [http://web.rigour.info/toophat/ toophat] [http://here.rigour.info/blog/stazione-orbitale.htm stazione orbitale] [http://load.rigour.info/view/new/www-rossoalice.htm www rossoalice com] [http://speed.rigour.info/blus-brothers.htm blus brothers soundtrack] [http://up.rigour.info/description/lib/unifi-it.htm unifi it] [http://paga.rigour.info/de-rosa/ de rosa bici] [http://italy.rigour.info/blog/dj-tommy.htm dj tommy vee stay] [http://dir.rigour.info/palmare-ipaq/ palmare ipaq] [http://speed.rigour.info/wireless-home.htm wireless home theater samsung] [http://note.rigour.info/content/view/edward-burns.htm edward burns] [http://note.rigour.info/content/view/w-w.htm w w w studenti it] [http://guest.rigour.info/library/html/immagini-piedi/ immagini piedi] [http://down.rigour.info/blog/divx-dvd.htm divx dvd onkyo lettori] [http://italy.rigour.info/blog/giochi-avventurosi.htm giochi avventurosi] [http://gratis.rigour.info/content/view/i-film.htm i film proiettati oggi a catania] [http://guest.rigour.info/library/html/griglia-pietra/ griglia pietra] [http://content.rigour.info/html/celebrita-femminili/ celebrita femminili] [http://down.rigour.info/blog/dvd-recorder.htm dvd recorder - r] [http://content.rigour.info/html/marica-giannini/ marica giannini] [http://dir.rigour.info/hard-disk/ hard disk mobile freecom] [http://down.rigour.info/blog/lo-sceriffo.htm lo sceriffo senza pistola] [http://gratis.rigour.info/content/view/tispy.htm tispy] [http://dir.rigour.info/inculate-foto/ inculate foto amatoriali] [http://here.rigour.info/blog/copertina-dvd.htm copertina dvd thirteen] [http://italy.rigour.info/blog/un-gao.htm un gao] [http://pagina.rigour.info/sono-nato/ sono nato ma...] [http://dir.rigour.info/dvd-moana/ dvd moana pozzi] [http://gratis.rigour.info/content/view/crack-nerovision.htm crack nerovision] [http://it.rigour.info/topic/ciber-mice/ ciber mice] [http://pagina.rigour.info/illuminazione-a/ illuminazione a dinamo] [http://load.rigour.info/view/new/bmw-td.htm bmw 320td compact city] [http://gratis.rigour.info/content/view/kingston-rsmmc.htm kingston rs-mmc mobile 512] [http://here.rigour.info/blog/olympus-camedia.htm olympus camedia fe-5500] [http://online.rigour.info/annunci-con/ annunci con cell] [http://web.rigour.info/antivir-personal/ antivir personal edition] [http://down.rigour.info/blog/vorrei-vorrei.htm vorrei vorrei] [http://italy.rigour.info/blog/note-book.htm note book nuovi] [http://speed.rigour.info/trans-piedi.htm trans piedi] [http://gratis.rigour.info/content/view/tetta-gigante.htm tetta gigante] [http://pagina.rigour.info/canon-mini/ canon mini dv] [http://web.rigour.info/ristorazione-scolastica/ ristorazione scolastica del comune di ve] [http://guest.rigour.info/library/html/ducci-giovanni/ ducci giovanni] [http://content.rigour.info/html/yensid/ yensid] [http://up.rigour.info/description/lib/auto-con.htm auto con motore a scoppio] [http://up.rigour.info/description/lib/cartoon-festivalu.htm cartoon festivalu] [http://load.rigour.info/view/new/scarpe-donne.htm scarpe donne] [http://speed.rigour.info/lettori-mp.htm lettori mp3 ogg vorbis] [http://here.rigour.info/blog/motomondiale-gp.htm motomondiale gp] [http://paga.rigour.info/ariston-avtl/ ariston avtl 62] [http://paga.rigour.info/lop/ lop] [http://guest.rigour.info/library/html/panasonic-dp/ panasonic dp 1520p] [http://all.rigour.info/telecom-cordless/ telecom cordless voice] [http://all.rigour.info/hp/ hp 3745] [http://paga.rigour.info/prestito-sesto/ prestito sesto fiorentino] [http://speed.rigour.info/volo-bologna.htm volo bologna praga] [http://paga.rigour.info/rape-porno/ rape porno] [http://all.rigour.info/calma-e/ calma e sangue freddo di luca dirisio] [http://speed.rigour.info/sapphire-x.htm sapphire x600 pro aiw] [http://online.rigour.info/la-segunda/ la segunda independencia] [http://dir.rigour.info/psp-italia/ psp italia] [http://pagina.rigour.info/dp/ dp 470] [http://content.rigour.info/html/grimaudo/ grimaudo] [http://italy.rigour.info/blog/gino-vannelli.htm gino vannelli] [http://paga.rigour.info/baclofene/ baclofene] [http://down.rigour.info/blog/brunello-biondi.htm brunello biondi santi 1997] [http://up.rigour.info/description/lib/inserzioni-gratuite.htm inserzioni gratuite] [http://all.rigour.info/evanescente/ evanescente] [http://here.rigour.info/blog/www-i.htm www i r a terrorismo] [http://load.rigour.info/view/new/dvd-nemo.htm dvd nemo] [http://content.rigour.info/html/chat-meneguzzi/ chat meneguzzi] [http://guest.rigour.info/library/html/tiziano-ferro/ tiziano ferro] [http://down.rigour.info/blog/saggio-breve.htm saggio breve amicizia letteratura] [http://web.rigour.info/imposte-indirette/ imposte indirette] [http://guest.rigour.info/library/html/foto-di/ foto di ragazzi drogati] [http://gratis.rigour.info/content/view/video-amatoriali.htm video amatoriali] [http://milano.rigour.info/walking.htm walking] [http://italy.rigour.info/blog/pfalzen.htm pfalzen] [http://it.rigour.info/topic/msc-com/ msc com] [http://pagina.rigour.info/manutenzioni-idrauliche/ manutenzioni idrauliche] [http://dir.rigour.info/trama-nozze/ trama nozze di figaro] [http://all.rigour.info/turtles/ turtles] [http://load.rigour.info/view/new/jesolo-vacanza.htm jesolo vacanza] [http://paga.rigour.info/e-pace/ e pace intima gen rosso] [http://it.rigour.info/topic/modem-lan/ modem lan dsl] [http://pagina.rigour.info/luscita/ luscita] [http://all.rigour.info/il-malessere/ il malessere giovanile e la scuola] [http://load.rigour.info/view/new/pantyhose-tights.htm pantyhose tights] [http://content.rigour.info/html/sound-blaster/ sound blaster pci] [http://paga.rigour.info/sex-pistol/ sex pistol] [http://load.rigour.info/view/new/maribel-guardia.htm maribel guardia] [http://blog.rigour.info/web/consigli-per/ consigli per truccarsi] [http://it.rigour.info/topic/joss-stone/ joss stone mind body and soul 03 you] [http://note.rigour.info/content/view/www-duncanjames.htm www duncanjames it] [http://load.rigour.info/view/new/formen.htm formen] [http://online.rigour.info/ibm-t/ ibm t43] [http://all.rigour.info/immagini-gandi/ immagini gandi] [http://paga.rigour.info/palmare-occasione/ palmare occasione] [http://web.rigour.info/peugeot/ peugeot 306 1995] [http://blog.rigour.info/web/compositore-di/ compositore di il tuo mondo] [http://blog.rigour.info/web/uahex/ uahex] [http://web.rigour.info/giocgi/ giocgi] [http://pagina.rigour.info/reinas-del/ reinas del mediodia] [http://paga.rigour.info/l-oceano/ l oceano del silenzio] [http://content.rigour.info/html/davon-girl/ davon girl pic] [http://up.rigour.info/description/lib/tradestation.htm tradestation] [http://here.rigour.info/blog/racchetta-prestige.htm racchetta prestige] [http://speed.rigour.info/phonocar.htm phonocar] [http://here.rigour.info/blog/km-lancia.htm km0 lancia ypsilon] [http://milano.rigour.info/paulownia.htm paulownia] [http://content.rigour.info/html/seka-aleksic/ seka aleksic sex fotos] [http://down.rigour.info/blog/stampante-fotografica.htm stampante fotografica compatta hp] [http://all.rigour.info/circolari-persomil/ circolari persomil] [http://up.rigour.info/description/lib/canton-movie.htm canton movie cd 1] [http://uve.rigour.info/blog/philips-dvd.htm philips dvd cinema] [http://load.rigour.info/view/new/nefertiti.htm nefertiti] [http://gratis.rigour.info/content/view/hotel-.htm hotel 3 stelle trieste] [http://dir.rigour.info/balconcino-imbottito/ balconcino imbottito] [http://paga.rigour.info/www-roten/ www roten com] [http://gratis.rigour.info/content/view/fig-gare.htm fig gare] [http://uve.rigour.info/blog/sony-axp.htm sony a497xp] [http://gratis.rigour.info/content/view/mutuo-calcolo.htm mutuo calcolo] [http://all.rigour.info/dont-come/ dont come easy] [http://gratis.rigour.info/content/view/karate-kid.htm karate kid collection] [http://speed.rigour.info/chassis.htm chassis] [http://all.rigour.info/laser-s/ laser s1855] [http://pagina.rigour.info/egittologia/ egittologia] [http://dir.rigour.info/triboniano/ triboniano] [http://web.rigour.info/office-microsoft/ office microsoft] [http://all.rigour.info/pietre/ pietre] [http://up.rigour.info/description/lib/exe.htm exe] [http://note.rigour.info/content/view/albergo-gardaland.htm albergo gardaland] [http://content.rigour.info/html/giochi-da/ giochi da vestire] [http://dir.rigour.info/lo-scandalo/ lo scandalo] [http://uve.rigour.info/blog/isole-di.htm isole di capoverde] [http://here.rigour.info/blog/toner-cexv.htm toner c-exv5 ir 1600 2000] [http://uve.rigour.info/blog/treppiede-peso.htm treppiede peso max] [http://online.rigour.info/immagini-ragazze/ immagini ragazze nude gratis] [http://gratis.rigour.info/content/view/broadway-danny.htm broadway danny rose] [http://load.rigour.info/view/new/mobili-antichi.htm mobili antichi] [http://note.rigour.info/content/view/polifoniche.htm polifoniche] [http://load.rigour.info/view/new/strudel.htm strudel] [http://guest.rigour.info/library/html/macchina-elettrica/ macchina elettrica per pasta] [http://online.rigour.info/un/ un] [http://guest.rigour.info/library/html/milan/ milan] [http://blog.rigour.info/web/matix/ matix] {{task}}
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself.
Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself.


Line 27: Line 27:




==[[C plus plus|C ]]==
==[[C plus plus|C++]]==
[[Category:C plus plus]]
[[Category:C plus plus]]
With language built-in facilities:
With language built-in facilities:
Line 44: Line 44:
double* array_data = new double[dim1*dim2];
double* array_data = new double[dim1*dim2];
double** array = new double*[dim1];
double** array = new double*[dim1];
for (int i = 0; i < dim1; i)
for (int i = 0; i < dim1; ++i)
array[i] = array_data dim2*i;
array[i] = array_data + dim2*i;
// write element
// write element
Line 115: Line 115:
: cell-matrix
: cell-matrix
create ( width height "name" ) over , * cells allot
create ( width height "name" ) over , * cells allot
does> ( x y -- addr ) dup cell >r @ * cells r> ;
does> ( x y -- addr ) dup cell+ >r @ * + cells r> + ;
5 5 cell-matrix test
5 5 cell-matrix test
Line 137: Line 137:
Double[][] array = new Double[nbr1][nbr2];
Double[][] array = new Double[nbr1][nbr2];
array[0][0] = 42.0;
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " array[0][0]);
System.out.println("The number at place [0 0] is " + array[0][0]);
} catch(IOException e) { }
} catch(IOException e) { }
Line 152: Line 152:
sub make_array($ $){
sub make_array($ $){
# get array sizes from provided params, but force numeric value
# get array sizes from provided params, but force numeric value
my $x = ($_[0] =~ /^\d $/) ? shift : 0;
my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
my $y = ($_[0] =~ /^\d $/) ? shift : 0;
my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
# define array, then add multi-dimensional elements
# define array, then add multi-dimensional elements

Revision as of 15:57, 21 August 2007

Task
Create a two-dimensional array at runtime
You are encouraged to solve this task according to the task description, using any language you may know.

Get two integers from the user, then create a two-dimensional array where the two dimensions have the sizes given by those numbers, and which can be accessed in the most natural way possible. Write some element of that array, and then oputput that element. Finally destroy the array if not done by the language itself.

Ada

with Ada.Text_Io; use Ada.Text_Io;
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Integer_Text_Io; use Ada.Integer_Text_Io;

procedure Two_Dimensional_Arrays is
   type Matrix_Type is array(Positive range <>, Positive range <>) of Float;
   Dim_1 : Positive;
   Dim_2 : Positive;
begin
   Get(Item => Dim_1);
   Get(Item => Dim_2);
   -- Create an inner block with the correctly sized array
   declare
      Matrix : Matrix_Type(1..Dim_1, 1..Dim_2);
   begin
      Matrix(1, Dim_2) := 3.14159;
      Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
      New_Line;
   end;
   -- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;


C++

With language built-in facilities:

#include <iostream>
#include <istream>
#include <ostream>

int main()
{
  // read values
  int dim1, dim2;
  std::cin >> dim1 >> dim2;

  // create array
  double* array_data = new double[dim1*dim2];
  double** array = new double*[dim1];
  for (int i = 0; i < dim1; ++i)
    array[i] = array_data + dim2*i;

  // write element
  array[0][0] = 3.5;

  // output element
  std::cout << array[0][0] << std::endl;

  // get rid of array
  delete[] array;
  delete[] array_data;
}

Using std::vector from the standard library:

#include <iostream>
#include <istream>
#include <ostream>
#include <vector>

int main()
{
  // read values
  int dim1, dim2;
  std::cin >> dim1 >> dim2;

  // create array
  std::vector<std::vector<double> > array(dim1, std::vector<double>(dim2));

  // write element
  array[0][0] = 3.5;

  // output element
  std::cout << array[0][0] << std::endl;

  // the array is automatically freed at the end of main()
}

Clean

import StdEnv

Start :: *World -> { {Real} }
Start world
    # (console, world) = stdio world
      (_, dim1, console) = freadi console
      (_, dim2, console) = freadi console
    = createArray dim1 (createArray dim2 1.0)

Common Lisp

(let ((d1 (read))
      (d2 (read)))
  (assert (and (typep d1 '(integer 1)) 
               (typep d2 '(integer 1))) 
          (d1 d2))
  (let ((array (make-array (list d1 d2) :initial-element nil))
        (p1 0)
        (p2 (floor d2 2)))
    (setf (aref array p1 p2) t)
    (print (aref array p1 p2))))

The assert will allow the user to reenter the dimensions if they are not positive integers.

Forth

: cell-matrix
  create ( width height "name" ) over ,  * cells allot
  does> ( x y -- addr ) dup cell+ >r  @ * + cells r> + ;

5 5 cell-matrix test

36 0 0 test !
0 0 test @ .  \ 36

Java

import java.io.*;

public class twoDimArray {
  public static void main(String[] args) {
     try {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        
        int nbr1 = Integer.parseInt(in.readLine());
        int nbr2 = Integer.parseInt(in.readLine());
        
        Double[][] array = new Double[nbr1][nbr2];
        array[0][0] = 42.0;
        System.out.println("The number at place [0 0] is " + array[0][0]);
        
     } catch(IOException e) { }
  }
} 


Perl

Interpreter: Perl 5.x

Predefining an array (or multi-dimension array) size is unnecessary, Perl dynamically resizes the array to meet the requirements. Of course I'm assuming that the user is entering array size 0 based.

sub make_array($ $){
  # get array sizes from provided params, but force numeric value
  my $x = ($_[0] =~ /^\d+$/) ? shift : 0;
  my $y = ($_[0] =~ /^\d+$/) ? shift : 0;
  
  # define array, then add multi-dimensional elements
  my @array;
  $array[0][0] = 'X '; # first by first element
  $array[5][7] = 'X ' if (5 <= $y and 7 <= $x); # sixth by eighth element, if the max size is big enough
  $array[12][15] = 'X ' if (12 <= $y and 15 <= $x); # thirteeth by sixteenth element, if the max size is big enough
  
  # loop through the elements expected to exist base on input, and display the elements contents in a grid
  foreach my $dy (0 .. $y){
    foreach my $dx (0 .. $x){
      (defined $array[$dy][$dx]) ? (print $array[$dy][$dx]) : (print '. ');
    }
    print "\n";
  }
}

Pop11

vars itemrep;
incharitem(charin) -> itemrep;
;;; Read sizes
vars n1 = itemrep(), n2= itemrep();
;;; Create 0 based array
vars ar = newarray([0 ^(n1 - 1) 0 ^(n2 - 1)], 0);
;;; Set element value
15 -> ar(0, 0);
;;; Print element value
ar(0,0) =>
;;; Make sure array is unreferenced
0 -> ar;

Pop11 is garbage colleted so there is no need to destroy array. However, the array is live as long as variable ar references it. The last assignment makes sure that we loose all our references to the array turning it into garbage.

Pop11 arrays may have arbitrary lower bounds, since we are given only size we create 0 based array.

Python

Interpreter: Python 2.5

 width = int(raw_input("Width of array: "))
 height = int(raw_input("Height of Array: "))
 array = [[0] * width for i in range(height)]
 array[0][0] = 3.5

Note: Some people may instinctively try to write array as [[0] * with] * height, but the * operator creates n references to [[0] * width]

IDL

The following is only for demonstration. No real program should just assume that the user input is valid, integer, large enough etc.

read, x, prompt='Enter x size:'
read, y, prompt='Enter y size:'
d = fltarr(x,y) 

d[3,4] = 5.6
print,d[3,4]
;==> outputs  5.6

delvar, d

Toka

Toka has no direct support for 2D arrays, but they can be created and operated on in a manner similar to normal arrays using the following functions.

[ ( x y -- address )
  cells malloc >r
  dup cells >r
  [ r> r> r> 2dup >r >r swap malloc swap i swap array.put >r ] iterate
r> r> nip
] is 2D-array

[ ( a b address -- value )
  array.get array.get
] is 2D-get-element

[ ( value a b address -- )
  array.get array.put
] is 2D-put-element

And a short test:

5 5 2D-array >r             #! Create an array and save the pointer to it
10 2 3 r@ 2D-put-element    #! Set element 2,3 to 10
2 3 r@ 2D-get-element       #! Get the element at 2,3
r> drop                     #! Discard the pointer to the array