Create a two-dimensional array at runtime

From Rosetta Code
Revision as of 01:13, 26 August 2007 by rosettacode>ZawUjj

calendario nuda suonerie gratis da scaricare polisex sexywomen foto e video disesso siti erotici tv terrestre analogico donne nude sexuality ginnasta nuda videos gratis de sexo racconti di orgasmi pullman, george mortimer giochini gratis myfirstsexteacher com britney spears porno gay palestrati il sesso degli angeli www sexool com sexy jeans hard porno donkey sexs film pornografici nudo uomo www wordlsex www sexycoppie it george, pierre hentai flash non scherzare con le donne - i galli del mare shakira total mente desnuda teen sex videos filmati gratis porno donne belissime duncan nudo sophie ellis bextor nuda www bolognaeros com psycho girl donne 47enne kragujevac porno le brave donne di bangkok suonerie gratis sfondi gratis motorola pamela anderson calendario margot sikabonyi nuda lola ponce nuda aria giovanni foto porno girlie nite out giochi java gratis anna la rosa nuda transex con telefono musica classica gratis disegni gratis burro programmazione settimanale atletica legg midi file sequenze da scaricare gratis talia desnuda katia gf4 sexy videos pono xxx de acceso facil invio gratis sms fuckyou gun shy - un revolver in analisi nudo pitt integrale posizioni x fare sesso angela finocchiaro nuda video porno britney spears xena tutta nuda foto donne porche over 50 videos gratis de orgasmos femeninos sfondo gratis pc giochi da scaricare gratis xxx eamon fuck it video canaletta ghisa guanti donne donne venezuelane a napoli web cam live show erotic gratis sex girls vree saint george analisi web peliculas prono gratis spycam in bagni e hotel gratis ragazze oslo porno market free mpeg fuck in pantyhose partituras gratis playboy foto gay cam galleria video porno di oggi celebrita a piedi nudi porno video free mess gratis showgirl italiana j m video clip sex sabrina ferilli completamente nuda previsioni lotto gratis good girl uomini nudi col pisello soca girlz fotos mujer desnuda free somali sexy girl sexy older women girls flashing video gratis pompini annunci per adulti flash porno foto nudo maschile pamela anderson video hard download grat due cazzi e una pornostar giochi di uomini nudi www aboutgay com pornostar over 40 lucia y el sexo versione integrale valentina gioia nuda incontro eros tette nere www tutto gratis it audio analogue maestro cd ghiochi porno demi moore nuda prestazioni occasionali sesso mexicali gay suoneria da scaricare gratis pamela prati pornostar i don t want to miss a thing aerosmith prostitute gratis archivio sexy copertina cd eros ramazzotti donne cercano singoli pamela anderson lee pomino foto gratis ragazze col cazzo le migliori moto naked niki karimi sex photo filmati pornogratis tiziana foschi nuda siti gratuiti porno tv digitale e analogica schede pamela sex xxx com www nose de sexo com foto belle ragazze donne in hotel film eva henger da scaricare gratis tette e latte gps 20 canali bluetooth video porno da vedere su internet videosex pamela anderson jorge la suerte vanessa incontrada sexy sexi escort xxxhardcore videoeros foto di mariah carey nuda video pornoo fran drescher porno donne inculate da cavalli jorge amado giochi di carte gratis video porno gratis eva hengher pornostar movies donne mature video gratis robbie williams naked foto gratis bocchini scaricare video porno gratis fuck it don t want to back donne sole foto bubble girl filmati mpg porno notiziario sexy sexul anal sex pistols com videoo manga porno fotos de britney spears desnuda siti di immagini di nudisti in spiaggia donne mature sesso animale gratis video hentai completi porno movie aepyceros ragazze del bagaglino donne x sesso supercazzi gay cheeky girls fumetti adulti intimo maschile sexy foto o video hard gratis sistemi per il gioco del lotto gratis dragon baal porno gun shy un revolver in analisi messaggi ragazze piacenza giochi sexy gratis gioco di avventura porno porno coppie vaginas close up www livesexlist com sesso nei wc fotosgratis de mujeres desnudas video gratis eva henger donne sexi over 50 anni pescara gay chastellain, georges flavia vento nuda usher sex

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