Create a two-dimensional array at runtime

From Rosetta Code
Revision as of 04:24, 5 May 2007 by 219.103.187.19 (talk)

soma online cheap hgh ambien online free nextel ringtones xenical online order norco tramadol online cheap vicodin verizon ringtones alltel ringtones free music ringtones soma online funny ringtones free funny ringtones cialis tracfone ringtones tramadol online xanax online but vigrx samsung ringtones fioricet online paxil online cheap ambien free sprint ringtones mp3 ringtones fioricet online cheap lipitor cheap ultracet cheap tenuate soma online phentermine online cheap vicodin cheap ortho cheap vicodin cheap levitra adipex online free motorola ringtones cheap adipex nextel ringtones ultram online free nokia ringtones free funny ringtones buy carisoprodol buy phentermine valium online free qwest ringtones tenuate online free sonyericsson ringtones motorola ringtones cheap cyclobenzaprine cheap norco lortab online flexeril online free tracfone ringtones carisoprodol online paxil qwest ringtones tramadol online levitra online didrex online free punk ringtones online ultracet buy hydrocodone buy xenical nokia ringtones free sprint ringtones buy diethylpropion adipex polyphonic ringtones cialis online ultram online cheap clomid free sagem ringtones free nextel ringtones alprazolam online cheap ultram cheap alprazolam free samsung ringtones cheap viagra free motorola ringtones viagra online order phentermine cheap ultram cheap diazepam rivotril online ativan online clonazepam online cheap tramadol carisoprodol online cheap meridia cheap valium cheap zoloft cyclobenzaprine online free sonyericsson ringtones flexeril online xanax free nokia ringtones valium online cheap wellbutrin sildenafil zoloft online valium online free midi ringtones cialis online qwest ringtones free real ringtones real ringtones free polyphonic ringtones tracfone ringtones cheap ultracet norco online free polyphonic ringtones buy levitra ambien online sildenafil online prozac online xanax online ortho online free funny ringtones cheap vicodin cheap phentermine cheap norco buy lortab hydrocodone online cheap ativan buy paxil free mono ringtones valium online cheap tramadol zoloft online online hydrocodone cheap viagra cheap albuterol rivotril online free verizon ringtones lorazepam online viagra online order didrex order phentermine free cingular ringtones ericsson ringtones sony ericsson ringtones free motorola ringtones buy zanaflex cheap flexeril samsung ringtones nokia ringtones cheap diazepam sonyericsson ringtones buy lorazepam real ringtones but rivotril ambien online albuterol online buy cialis buy ambien free sagem ringtones norco online meridia online nexium online free mono ringtones cheap hgh ultram online order ativan wellbutrin online free ringtones diazepam online free sprint ringtones lortab online buy carisoprodol free verizon ringtones clomid online cheap xenical xanax online free free ringtones cheap wellbutrin carisoprodol online free tracfone ringtones sharp ringtones ativan online buy norco free sony ericsson ringtones free tracfone ringtones sonyericsson ringtones cheap soma meridia online zyban online clonazepam free music ringtones cheap cyclobenzaprine ativan online cheap paxil cheap ativan but nexium mp3 ringtones cheap hgh buy propecia free samsung ringtones online ortho but zyban adipex online motorola ringtones adipex online free nextel ringtones ultram online nokia ringtones free funny ringtones carisoprodol online buy phentermine valium online free qwest ringtones cheap tenuate free sonyericsson ringtones motorola ringtones cyclobenzaprine online order norco lortab online flexeril online tracfone ringtones cheap carisoprodol online paxil qwest ringtones buy tramadol buy levitra cheap didrex punk ringtones ultracet buy hydrocodone buy xenical nokia ringtones free sprint ringtones diethylpropion online adipex online free polyphonic ringtones cheap cialis ultram online clomid online free sagem ringtones nextel ringtones alprazolam online ultram online alprazolam online free samsung ringtones cheap viagra motorola ringtones cheap viagra phentermine online ultram online cheap diazepam cheap rivotril cheap ativan order clonazepam tramadol online carisoprodol online meridia online cheap valium cheap zoloft cyclobenzaprine online free sonyericsson ringtones flexeril online xanax free nokia ringtones valium online cheap wellbutrin sildenafil order zoloft cheap valium free midi ringtones cialis online free qwest ringtones free real ringtones free real ringtones free polyphonic ringtones free tracfone ringtones cheap ultracet norco online polyphonic ringtones buy levitra ambien online cheap sildenafil prozac online xanax cheap ortho funny ringtones vicodin online phentermine online norco online buy lortab hydrocodone online cheap ativan buy paxil mono ringtones valium tramadol online cheap zoloft online hydrocodone cheap viagra albuterol cheap rivotril verizon ringtones online lorazepam order viagra didrex online phentermine online free cingular ringtones ericsson ringtones sony ericsson ringtones free motorola ringtones zanaflex online flexeril online samsung ringtones nokia ringtones cheap diazepam free sonyericsson ringtones lorazepam online free real ringtones but rivotril buy ambien albuterol online cialis online ambien online sagem ringtones cheap norco meridia online nexium online free mono ringtones hgh online cheap ultram ativan online buy wellbutrin free free ringtones diazepam online free sprint ringtones lortab online carisoprodol online verizon ringtones clomid online xenical online xanax online free free ringtones cheap wellbutrin carisoprodol online tracfone ringtones free sharp ringtones buy ativan norco online free sony ericsson ringtones tracfone ringtones free sonyericsson ringtones soma online meridia online buy zyban clonazepam free music ringtones cheap cyclobenzaprine cheap ativan paxil online ativan online but nexium free mp3 ringtones hgh online propecia online free samsung ringtones ortho online zyban free punk ringtones lipitor online free mtv ringtones vigrx online cheap lorazepam fioricet online lorazepam online cool ringtones free qwest ringtones cheap diazepam tenuate online clonazepam online fioricet online ativan online clonazepam online propecia online free mp3 ringtones hydrocodone online cheap carisoprodol cheap didrex levitra nextel ringtones zyban online free mp3 ringtones levitra buy celexa tracfone ringtones adipex online free free ringtones free music ringtones free nextel ringtones free nokia ringtones cheap levitra free free ringtones cheap propecia

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.

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";
  }
}

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