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

From Rosetta Code
Content added Content deleted
mNo edit summary
Line 1: Line 1:
{{task}}
[http://lcd-b.firethro.info lcd b o 32] [http://tampa-san.monbrenno.info tampa san petersburg cose fare] [http://maglioni-liu.giantlau.info maglioni liu jo] [http://laortiz.airsofthost.com/view/new/fp/ fp 940] [http://vannucci-atto.cleric4u.info vannucci atto] [http://frigorifero-.cleric4u.info frigorifero 188 cm] [http://lejenny.airsofthost.com/library/html/bedandbreakfast-sardegna.htm bedandbreakfast sardegna] [http://sverginata.giantlau.info sverginata] [http://hdurian.airsofthost.com/view/new/concerti-.htm concerti 2004 raf] [http://remayfuy.airsofthost.com/images/small/qosmio-double/ qosmio double layer toshiba portatili] [http://dect-gap.monbrenno.info dect gap telecom] [http://venire-dentro.otrev4ro.info venire dentro] [http://gloria-cacharel.monbrenno.info gloria cacharel] [http://maheinze.airsofthost.com/data/sony-.htm sony dcr dvd403e] [http://centro-commerciale.monbrenno.info centro commerciale i portali] [http://hdurian.airsofthost.com/view/new/unipd.htm unipd] [http://latino-americano.firethro.info latino americano carnival] [http://ragazze-di.firethro.info ragazze di napoli] [http://d-p.monbrenno.info d p r 459 96] [http://angel-devil.monbrenno.info angel devil] [http://splucind.airsofthost.com/content/view/totocalcio/ totocalcio 2004] [http://laortiz.airsofthost.com/view/new/sms-it/ sms it] [http://gabbiano-infelice.otrev4ro.info gabbiano infelice] [http://laortiz.airsofthost.com/view/new/per-amore/ per amore per magia] [http://salone-francesca.otrev4ro.info salone francesca] [http://rumote.airsofthost.com/lib/statistica-sito.htm statistica sito web] [http://foto-amatoriali.giantlau.info foto amatoriali di donne spogliate] [http://come-un.monbrenno.info come un gelato all equatore] [http://filmato-bulgari.cleric4u.info filmato bulgari conte] [http://splucind.airsofthost.com/content/view/mp-cem/ mp3 cem karaca] [http://remayfuy.airsofthost.com/images/small/download-nero/ download nero6 retail] [http://lionel-richi.firethro.info lionel richi] [http://ml-oki.otrev4ro.info ml oki stampanti] [http://frgrossm.airsofthost.com/topic/eva-hanger/ eva hanger] [http://maheinze.airsofthost.com/data/video-player.htm video player] [http://alpaddy.airsofthost.com/img/styles/staffa-a/ staffa a muro universale] [http://accessori-mio.giantlau.info accessori mio 168] [http://on-regionale.giantlau.info on regionale amendola] [http://frgrossm.airsofthost.com/topic/il-billiardo/ il billiardo] [http://nokia-.monbrenno.info nokia 6230 live] [http://remayfuy.airsofthost.com/images/small/handycam-dcrhce/ handycam dcrhc17e] [http://false-bay.monbrenno.info false bay] [http://hdurian.airsofthost.com/view/new/pioneer-dcs.htm pioneer dcs 525] [http://lejenny.airsofthost.com/library/html/laws-on.htm laws on spy cams] [http://banzlees.airsofthost.com/description/lib/geforce-.htm geforce 6600 128 mb] [http://sms-gratuiti.firethro.info sms gratuiti cellulare] [http://laortiz.airsofthost.com/view/new/cabernet-sauvignon/ cabernet sauvignon emilia] [http://connerie.giantlau.info connerie] [http://csi-vicenza.firethro.info csi vicenza] [http://hdurian.airsofthost.com/view/new/benvenuti.htm benvenuti] [http://nuova-carens.monbrenno.info nuova carens kia] [http://hard-usb.firethro.info hard usb2] [http://splucind.airsofthost.com/content/view/dispositivo-gps/ dispositivo gps] [http://xxxporn.monbrenno.info xxxporn] [http://rumote.airsofthost.com/lib/fotos-karen.htm fotos karen dejo] [http://bl-c.monbrenno.info bl 4c] [http://hdurian.airsofthost.com/view/new/heidi-novgorod.htm heidi novgorod] [http://traduzione-shut.firethro.info traduzione shut up] [http://splucind.airsofthost.com/content/view/nuovi-giochi/ nuovi giochi da non scaricare e non con] [http://laortiz.airsofthost.com/view/new/kodak-easyshare/ kodak easyshare cx7525 7525] [http://test-d.firethro.info test d ingresso scuola media inferiore] [http://remayfuy.airsofthost.com/images/small/macgyver/ macgyver] [http://maheinze.airsofthost.com/data/finestre.htm finestre] [http://alpaddy.airsofthost.com/img/styles/chris-benoit/ chris benoit] [http://frgrossm.airsofthost.com/topic/testi-canzoni/ testi canzoni hilary duff] [http://rumote.airsofthost.com/lib/tv-plasma.htm tv plasma wxga] [http://laortiz.airsofthost.com/view/new/dj-raff/ dj raff] [http://frgrossm.airsofthost.com/topic/riassunto-giara/ riassunto giara pirandello] [http://splucind.airsofthost.com/content/view/renault-megane/ renault megane 1 5 luxe dinamique] [http://frisina.cleric4u.info frisina] [http://computorgirl.giantlau.info computorgirl] [http://banzlees.airsofthost.com/description/lib/dvd-r.htm dvd r70 philips] [http://frgrossm.airsofthost.com/topic/alcatel-all/ alcatel all be4] [http://laortiz.airsofthost.com/view/new/donne-proibite/ donne proibite] [http://alpaddy.airsofthost.com/img/styles/destroy-all/ destroy all humans game] [http://telecamera-sony.otrev4ro.info telecamera sony pc 6] [http://remayfuy.airsofthost.com/images/small/foppapedretti-fasciatoi/ foppapedretti fasciatoi] [http://felicity-huffman.monbrenno.info felicity huffman] [http://alpaddy.airsofthost.com/img/styles/traduzione-in/ traduzione in cinese] [http://rumote.airsofthost.com/lib/portoferraio.htm portoferraio] [http://frgrossm.airsofthost.com/topic/video-porno/ video porno da vedere gratuitamente] [http://lavatrici-carica.giantlau.info lavatrici carica alto profondita 40] [http://e-non.firethro.info e non ho te] [http://lejenny.airsofthost.com/library/html/grand-hotel.htm grand hotel olympic aurum] [http://frgrossm.airsofthost.com/topic/uno-strano/ uno strano percorso 883] [http://laortiz.airsofthost.com/view/new/lady-susan/ lady susan] [http://immagini-cbr.giantlau.info immagini cbr] [http://grl.cleric4u.info grl] [http://frgrossm.airsofthost.com/topic/assistenza-tecnica/ assistenza tecnica acer bari] [http://sabarkantha.firethro.info sabarkantha] [http://adamo-giovanni.firethro.info adamo giovanni] [http://remayfuy.airsofthost.com/images/small/irene-curie/ irene curie] [http://remayfuy.airsofthost.com/images/small/musica-zero/ musica zero] [http://lejenny.airsofthost.com/library/html/satellite-televisione.htm satellite televisione] [http://banzlees.airsofthost.com/description/lib/microsoft-publisher.htm microsoft publisher download gratuito] [http://frgrossm.airsofthost.com/topic/kit-home/ kit home teather] [http://scuola-di.otrev4ro.info scuola di liuteria] [http://lorenz-orologi.cleric4u.info lorenz orologi donna] [http://rumote.airsofthost.com/lib/sennheiser.htm sennheiser 150] [http://laortiz.airsofthost.com/view/new/sexsexsex/ sexsexsex] [http://hdurian.airsofthost.com/view/new/profumi-rochas.htm profumi rochas] [http://the-essential.firethro.info the essential leonard cohen] [http://samsung-batteria.otrev4ro.info samsung batteria videocamera] [http://maheinze.airsofthost.com/data/un-inglese.htm un inglese allestero] [http://elaborazione-progetti.otrev4ro.info elaborazione progetti per i mass media] [http://wharfedale-.monbrenno.info wharfedale 9 2 diamond] [http://laortiz.airsofthost.com/view/new/vlad/ vlad] [http://sigma-mm.firethro.info sigma 2470mm f2 8 ex dg] [http://el-embraje.giantlau.info el embraje] [http://remayfuy.airsofthost.com/images/small/dual-processors/ dual processors schede madri] [http://rumote.airsofthost.com/lib/uccisione-soldato.htm uccisione soldato americano] [http://remayfuy.airsofthost.com/images/small/insufficienza-venosa/ insufficienza venosa agli arti inferiori] [http://hdurian.airsofthost.com/view/new/fornelli-.htm fornelli 5 fuochi] [http://les-copains.giantlau.info les copains] [http://lejenny.airsofthost.com/library/html/calahorra.htm calahorra] [http://www-canzoni.monbrenno.info www canzoni testo it] [http://rumote.airsofthost.com/lib/canzone-di.htm canzone di nando] [http://remayfuy.airsofthost.com/images/small/universita-di/ universita di perugia] [http://splucind.airsofthost.com/content/view/canon-batteria/ canon batteria nb] [http://leva-gioielli.monbrenno.info leva gioielli srl] [http://laortiz.airsofthost.com/view/new/tramitanet/ tramitanet] [http://napster.monbrenno.info napster] [http://fisolofia.giantlau.info fisolofia] [http://banzlees.airsofthost.com/description/lib/gioco-arcade.htm gioco arcade bambino 5 8 anno] [http://laortiz.airsofthost.com/view/new/toshiba-a/ toshiba a4] [http://banzlees.airsofthost.com/description/lib/micra-diesel.htm micra diesel] [http://caffe-retro.giantlau.info caffe retro] [http://cartine-dei.cleric4u.info cartine dei paesi del salernitano] [http://lejenny.airsofthost.com/library/html/la-notte.htm la notte delle beffe] [http://frgrossm.airsofthost.com/topic/sexo-de/ sexo de argentina] [http://remayfuy.airsofthost.com/images/small/foto-porno/ foto porno gratuite da scaricare] [http://testo-in.giantlau.info testo in italiano i don t want you back] [http://www-disneyland.otrev4ro.info www disneyland it] [http://alpaddy.airsofthost.com/img/styles/jvc-vhs/ jvc vhs] [http://ram-.cleric4u.info ram 266 512 ddr] [http://maheinze.airsofthost.com/data/pantaloni-sportivi.htm pantaloni sportivi nike uomo] [http://maheinze.airsofthost.com/data/camelot-ginevra.htm camelot ginevra] [http://frgrossm.airsofthost.com/topic/aereo-napoli/ aereo napoli] [http://www-seno.monbrenno.info www seno] [http://alpaddy.airsofthost.com/img/styles/silent-bomber/ silent bomber] [http://frgrossm.airsofthost.com/topic/samsung-vp/ samsung vp m110] [http://remayfuy.airsofthost.com/images/small/albergo-belgio/ albergo belgio] [http://alpaddy.airsofthost.com/img/styles/joe-cocker/ joe cocker across from midnight tour live in berlin] [http://toner-olivetti.firethro.info toner olivetti dcopia 15] [http://perec-georges.otrev4ro.info perec georges] [http://seat-leon.cleric4u.info seat leon tdi 150 cv] [http://incontri-borgomanero.cleric4u.info incontri borgomanero] [http://mac-a.otrev4ro.info mac a3 inkjet hp stampanti] [http://lejenny.airsofthost.com/library/html/dscp-memory.htm dscp200 memory] [http://remayfuy.airsofthost.com/images/small/de-felice/ de felice giuffrida giuseppe] [http://lejenny.airsofthost.com/library/html/emmanuelle-dvd.htm emmanuelle dvd] [http://laortiz.airsofthost.com/view/new/monitor-tv/ monitor tv lcd 19] [http://banzlees.airsofthost.com/description/lib/una-pillola.htm una pillola per eva] [http://alpaddy.airsofthost.com/img/styles/ritapavone/ ritapavone] [http://alpaddy.airsofthost.com/img/styles/seconda-prova/ seconda prova scritta matematica 2004] [http://giochi-soluzioni.otrev4ro.info giochi soluzioni] [http://banzlees.airsofthost.com/description/lib/renato-marinella.htm renato marinella] [http://laortiz.airsofthost.com/view/new/pensioni-gallipoli/ pensioni gallipoli alberghi] [http://maheinze.airsofthost.com/data/sexicam.htm sexicam] [http://lejenny.airsofthost.com/library/html/calendario-blue.htm calendario blue cantanti] [http://con-tu.firethro.info con tu amor] [http://frgrossm.airsofthost.com/topic/motivi-aggiunti/ motivi aggiunti] [http://rumote.airsofthost.com/lib/tirrenica.htm tirrenica] [http://mu-sica.firethro.info mu sica] [http://remayfuy.airsofthost.com/images/small/hercules/ hercules 2] [http://splucind.airsofthost.com/content/view/ujung-pandang/ ujung pandang] [http://frgrossm.airsofthost.com/topic/mitrache/ mitrache] [http://alpaddy.airsofthost.com/img/styles/aol-instant/ aol instant messenger] [http://frgrossm.airsofthost.com/topic/questione-donore/ questione donore] [http://lejenny.airsofthost.com/library/html/diari-per.htm diari per la scuola] [http://lejenny.airsofthost.com/library/html/cretino.htm cretino] [http://alpaddy.airsofthost.com/img/styles/mutandine-bagnate/ mutandine bagnate] [http://frgrossm.airsofthost.com/topic/tesina-chimica/ tesina chimica] [http://alpaddy.airsofthost.com/img/styles/baila-morena/ baila morena video] [http://il-fabbricante.monbrenno.info il fabbricante di sogni] [http://immagini-sulla.giantlau.info immagini sulla pesca d acqua dolce] [http://olympus-flash.giantlau.info olympus flash] [http://ubuntu.monbrenno.info ubuntu] [http://rumote.airsofthost.com/lib/logitech-momo.htm logitech momo racing] [http://lejenny.airsofthost.com/library/html/frasi-romantica.htm frasi romantica inglese] [http://hdurian.airsofthost.com/view/new/sms-gratis.htm sms gratis sunrise] [http://laortiz.airsofthost.com/view/new/febbre-destate/ febbre destate] [http://rumote.airsofthost.com/lib/bluetooth-stampanti.htm bluetooth stampanti wireless] [http://rumote.airsofthost.com/lib/pgd-premium.htm p5gd2 premium asus] [http://lejenny.airsofthost.com/library/html/descrizione-di.htm descrizione di un attimo] [http://frgrossm.airsofthost.com/topic/bulgaro-decapitado/ bulgaro decapitado] [http://thien.firethro.info thien] [http://laortiz.airsofthost.com/view/new/atleti-uomo/ atleti uomo nudi] [http://rumote.airsofthost.com/lib/universo-proibito.htm universo proibito] [http://hdurian.airsofthost.com/view/new/goods-of.htm goods of metal] [http://alpaddy.airsofthost.com/img/styles/porsche/ porsche 911 997] [http://rumote.airsofthost.com/lib/rt-.htm rt 57 eatg] [http://alpaddy.airsofthost.com/img/styles/windows-xp/ windows xp media center] [http://frgrossm.airsofthost.com/topic/bmw-/ bmw 320 nero berlina] [http://gioco-di.giantlau.info gioco di enigmi] [http://siamo-fuori.firethro.info siamo fuori dal tunnell] [http://rumote.airsofthost.com/lib/systemworks-.htm systemworks 2005 premiere] [http://lejenny.airsofthost.com/library/html/dissipatori-cpu.htm dissipatori cpu k7] [http://bella-figliola.otrev4ro.info bella figliola] [http://laortiz.airsofthost.com/view/new/iva-su/ iva su gas metano uso domestico] {{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 21:10, 30 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