This commit is contained in:
Ingy döt Net 2013-04-10 16:57:12 -07:00
parent 518da4a923
commit 764da6cbbb
6144 changed files with 83610 additions and 11 deletions

View file

@ -0,0 +1,2 @@
{{data structure}}
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 output that element. Finally destroy the array if not done by the language itself.

View file

@ -0,0 +1,2 @@
---
note: Basic language learning

View file

@ -0,0 +1,6 @@
main:(
print("Input two positive whole numbers separated by space and press newline:");
[read int,read int] INT array;
array[1,1]:=42;
print (array[1,1])
)

View file

@ -0,0 +1,7 @@
arraym n 0 ⍝ array of zeros with shape of m by n.
array[1;1]73 ⍝ assign a value to location 1;1.
array[1;1] ⍝ read the value back out
⎕ex 'array' ⍝ erase the array

View file

@ -0,0 +1,13 @@
/[0-9]+ [0-9]+/ {
for(i=0; i < $1; i++) {
for(j=0; j < $2; j++) {
arr[i, j] = i*j
}
}
# how to scan "multidim" array as explained in the GNU AWK manual
for (comb in arr) {
split(comb, idx, SUBSEP)
print idx[1] "," idx[2] "->" arr[idx[1], idx[2]]
}
}

View file

@ -0,0 +1,21 @@
with Ada.Text_Io;
with Ada.Float_Text_Io;
with 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
Ada.Integer_Text_Io.Get(Item => Dim_1);
Ada.Integer_Text_Io.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;
Ada.Float_Text_Io.Put(Item => Matrix(1, Dim_2), Fore => 1, Aft => 5, Exp => 0);
Ada.Text_Io.New_Line;
end;
-- The variable Matrix is popped off the stack automatically
end Two_Dimensional_Arrays;

View file

@ -0,0 +1,24 @@
set R to text returned of (display dialog "Enter number of rows:" default answer 2) as integer
set c to text returned of (display dialog "Enter number of columns:" default answer 2) as integer
set array to {}
repeat with i from 1 to R
set temp to {}
repeat with j from 1 to c
set temp's end to 0
end repeat
set array's end to temp
end repeat
-- Address the first column of the first row:
set array's item 1's item 1 to -10
-- Negative index values can be used to address from the end:
set array's item -1's item -1 to 10
-- Access an item (row 2 column 1):
set x to array's item 2's item 1
return array
-- Destroy array (typically unnecessary since it'll automatically be destroyed once script ends).
set array to {}

View file

@ -0,0 +1,5 @@
Array := []
InputBox, data,, Enter two integers separated by a Space:`n(ex. 5 7)
StringSplit, i, data, %A_Space%
Array[i1,i2] := "that element"
MsgBox, % "Array[" i1 "," i2 "] = " Array[i1,i2]

View file

@ -0,0 +1,12 @@
; == get dimensions from user input
$sInput = InputBox('2D Array Creation', 'Input comma separated count of rows and columns, i.e. "5,3"')
$aDimension = StringSplit($sInput, ',', 2)
; == create array
Dim $a2D[ $aDimension[0] ][ $aDimension[1] ]
; == write value to last row/last column
$a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] = 'test string'
; == output this value to MsgBox
MsgBox(0, 'Output', 'row[' & UBound($a2D) -1 & '], col[' & UBound($a2D, 2) -1 & ']' & @CRLF & '= ' & $a2D[ UBound($a2D) -1 ][ UBound($a2D, 2) -1 ] )

View file

@ -0,0 +1,5 @@
INPUT "Enter array dimensions separated by a comma: " a%, b%
DIM array(a%, b%)
array(1, 1) = PI
PRINT array(1, 1)

View file

@ -0,0 +1,26 @@
#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;
}

View file

@ -0,0 +1,22 @@
#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()
}

View file

@ -0,0 +1,20 @@
#include <iostream>
#include "boost/multi_array.hpp"
typedef boost::multi_array<double, 2> two_d_array_type;
int main()
{
// read values
int dim1, dim2;
std::cin >> dim1 >> dim2;
// create array
two_d_array_type A(boost::extents[dim1][dim2]);
// write elements
A[0][0] = 3.1415;
// read elements
std::cout << A[0][0] << std::endl;
}

View file

@ -0,0 +1,13 @@
#include <stdio.h>
int main(int argc, char **argv) {
int user1 = 0, user2 = 0;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
int array[user1][user2];
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}

View file

@ -0,0 +1,20 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int user1 = 0, user2 = 0;
int *a1, **array, row;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
a1 = malloc(user1*user2*sizeof(int));
array = malloc(user2*sizeof(int*));
for (row=0; row<user1; row++) array[row]=a1+row*user2;
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
free(array);
free(a1);
return 0;
}

View file

@ -0,0 +1,28 @@
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int user1 = 0;
int space_needed;
int *a1, **array;
int row, col;
printf("Enter size of array: ");
scanf("%d",&user1);
space_needed = (user1+1)*user1/2;
a1 = malloc(space_needed);
array = malloc(user1*sizeof(int*));
for (row=0,offset=0; row<user1; offset+=(user1-row), row++) {
array[row]=a1+offset-row;
for (col=row; col<user1; col++)
array[row][col] = 1+col-row;
}
for (row=0; row<user1; row++)
printf("%d ", array[row][user1-1]);
printf("\n");
free(array);
free(a1);
return 0;
}

View file

@ -0,0 +1,18 @@
#include <stdio.h>
#include <alloca.h>
int main(int argc, char **argv)
{
int user1 = 0, user2 = 0;
int *a1, **array, row;
printf("Enter two integers. Space delimited, please: ");
scanf("%d %d",&user1, &user2);
a1 = alloca(user1*user2*sizeof(int));
array = alloca(user1*sizeof(int*));
for (row=0; row<user1; row++) array[row]=a1+row*user2;
array[user1/2][user2/2] = user1 + user2;
printf("array[%d][%d] is %d\n",user1/2,user2/2,array[user1/2][user2/2]);
return 0;
}

View file

@ -0,0 +1,8 @@
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)

View file

@ -0,0 +1,5 @@
(let [rows (Integer/parseInt (read-line))
cols (Integer/parseInt (read-line))
a (to-array-2d (repeat rows (repeat cols nil)))]
(aset a 0 0 12)
(println "Element at 0,0:" (aget a 0 0)))

View file

@ -0,0 +1,10 @@
(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))))

View file

@ -0,0 +1,18 @@
MODULE TestArray;
(* Implemented in BlackBox Component Builder *)
IMPORT Out;
(* Open array *)
PROCEDURE DoTwoDim*;
VAR d: POINTER TO ARRAY OF ARRAY OF INTEGER;
BEGIN
NEW(d, 5, 4); (* allocating array in memory *)
d[1, 2] := 100; (* second row, third column element *)
d[4, 3] := -100; (* fifth row, fourth column element *)
Out.Int(d[1, 2], 0); Out.Ln;
Out.Int(d[4, 3], 0); Out.Ln;
END DoTwoDim;
END TestArray.

View file

@ -0,0 +1,25 @@
import std.stdio, std.conv, std.string;
void main() {
int nRow, nCol;
write("Give me the numer of rows: ");
try {
nRow = readln().strip().to!int();
} catch (StdioException e) {
nRow = 3;
writeln();
}
write("Give me the numer of columns: ");
try {
nCol = to!int(readln().strip());
} catch (StdioException e) {
nCol = 5;
writeln();
}
auto array = new float[][](nRow, nCol);
array[0][0] = 3.5;
writeln("The number at place [0, 0] is ", array[0][0]);
}

View file

@ -0,0 +1,28 @@
program Project1;
{$APPTYPE CONSOLE}
uses
SysUtils;
var
matrix:array of array of Byte;
i,j:Integer;
begin
Randomize;
//Finalization is not required in this case, but you have to do
//so when reusing the variable in scope
Finalize(matrix);
//Init first dimension with random size from 1..10
//Remember dynamic arrays are indexed from 0
SetLength(matrix,Random(10) + 1);
//Init 2nd dimension with random sizes too
for i := Low(matrix) to High(matrix) do
SetLength(matrix[i],Random(10) + 1);
//End of code, the following part is just output
Writeln(Format('Total amount of columns = %.2d',[Length(matrix)]));
for i := Low(matrix) to High(matrix) do
Writeln(Format('Column %.2d = %.2d rows',[i,Length(matrix[i])]));
Readln;
end.

View file

@ -0,0 +1,15 @@
include get.e
sequence array
integer height,width,i,j
height = floor(prompt_number("Enter height: ",{}))
width = floor(prompt_number("Enter width: ",{}))
array = repeat(repeat(0,width),height)
i = floor(height/2+0.5)
j = floor(width/2+0.5)
array[i][j] = height + width
printf(1,"array[%d][%d] is %d\n", {i,j,array[i][j]})

View file

@ -0,0 +1,8 @@
: 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

View file

@ -0,0 +1,7 @@
INTEGER DMATRIX my-matrix{{
& my-matrix{{ 8 9 }}malloc
8 my-matrix{{ 3 4 }} !
my-matrix{{ 3 4 }} @ .
& my-matrix{{ }}free

View file

@ -0,0 +1,20 @@
PROGRAM Example
IMPLICIT NONE
INTEGER :: rows, columns, errcheck
INTEGER, ALLOCATABLE :: array(:,:)
WRITE(*,*) "Enter number of rows"
READ(*,*) rows
WRITE(*,*) "Enter number of columns"
READ(*,*) columns
ALLOCATE (array(rows,columns), STAT=errcheck) ! STAT is optional and is used for error checking
array(1,1) = 42
WRITE(*,*) array(1,1)
DEALLOCATE (array, STAT=errcheck)
END PROGRAM Example

View file

@ -0,0 +1,28 @@
package main
import "fmt"
func main() {
var row, col int
fmt.Print("enter rows cols: ")
fmt.Scan(&row, &col)
// allocate composed 2d array
a := make([][]int, row)
for i := range a {
a[i] = make([]int, col)
}
// array elements initialized to 0
fmt.Println("a[0][0] =", a[0][0])
// assign
a[row-1][col-1] = 7
// retrieve
fmt.Printf("a[%d][%d] = %d\n", row-1, col-1, a[row-1][col-1])
// remove only reference
a = nil
// memory allocated earlier with make can now be garbage collected.
}

View file

@ -0,0 +1,6 @@
// allocate composed 2d array
a := make([][]int, row)
e := make([]int, row * col)
for i := range a {
a[i] = e[i*col:(i+1)*col]
}

View file

@ -0,0 +1,3 @@
func get(r, c int) int {
return e[r*cols+c]
}

View file

@ -0,0 +1 @@
doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]

View file

@ -0,0 +1,14 @@
import java.util.Scanner;
public class twoDimArray {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int nbr1 = in.nextInt();
int nbr2 = in.nextInt();
double[][] array = new double[nbr1][nbr2];
array[0][0] = 42.0;
System.out.println("The number at place [0 0] is " + array[0][0]);
}
}

View file

@ -0,0 +1,28 @@
var w = parseInt( get_input("Enter a width:") );
var w = parseInt( get_input("Enter a height:") );
// create the 2-D array
var a = new Array(h);
for (var i = 0; i < h; i++)
a[i] = new Array(w);
a[0][0] = 'foo';
WScript.Echo('a[0][0] = ' + a[0][0]);
a = null;
function get_input(prompt) {
output(prompt);
try {
return WScript.StdIn.readLine();
} catch(e) {
return readline();
}
}
function output(prompt) {
try {
return WScript.echo(prompt);
} catch(e) {
return print(prompt);
}
}

View file

@ -0,0 +1,7 @@
function multiply(n, a, b) if a <= b then return n, multiply(n, a + 1, b) end end
a, b = io.read() + 0, io.read() + 0
matrix = {multiply({multiply(1, 1, b)}, 1, a)}
matrix[a][b] = 5
print(matrix[a][b])
print(matrix[1][1])

View file

@ -0,0 +1,10 @@
width = input('Array Width: ');
height = input('Array Height: ');
array = zeros(width,height);
array(1,1) = 12;
disp(['Array element (1,1) = ' num2str(array(1,1))]);
clear array; % de-allocate (remove) array from workspace

View file

@ -0,0 +1,3 @@
Array Width: 18
Array Height: 12
Array element (1,1) = 12

View file

@ -0,0 +1,19 @@
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); # thirteenth 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";
}
}

View file

@ -0,0 +1,19 @@
sub array {
my ($x, $y) = @_;
map {[ (0) x $x ]} 1 .. $y
}
my @square = array 3, 3;
# everything above this line is mostly redundant in perl,
# since perl would have created the array automatically when used.
# however, the above function initializes the array elements to 0,
# while perl would have used undef
#
# $cube[3][4][5] = 60 # this is valid even if @cube was previously undefined
$square[1][1] = 1;
print "@$_\n" for @square;
> 0 0 0
> 0 1 0
> 0 0 0

View file

@ -0,0 +1,7 @@
(de 2dimTest (DX DY)
(let A (make (do DX (link (need DY))))
(set (nth A 3 3) 999) # Set A[3][3] to 999
(mapc println A) # Print all
(get A 3 3) ) ) # Return A[3][3]
(2dimTest 5 5)

View file

@ -0,0 +1,5 @@
width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
myarray = [[0] * width for i in xrange(height)]
myarray[0][0] = 3.5
print myarray[0][0]

View file

@ -0,0 +1,4 @@
myarray = {(w,h): 0 for w in range(width) for h in range(height)}
# or, in pre 2.7 versions of Python: myarray = dict(((w,h), 0) for w in range(width) for h in range(height))
myarray[(0,0)] = 3.5
print myarray[(0,0)]

View file

@ -0,0 +1,7 @@
input <- readline("Enter two integers. Space delimited, please: ")
dims <- as.numeric(strsplit(input, " ")[[1]])
arr <- array(dim=dims)
ii <- ceiling(dims[1]/2)
jj <- ceiling(dims[2]/2)
arr[ii, jj] <- sum(dims)
cat("array[", ii, ",", jj, "] is ", arr[ii, jj], "\n", sep="")

View file

@ -0,0 +1,39 @@
/*REXX program to allocate/populate/display a two-dimensional array. */
call bloat
/*no more array named A. at this point.*/
exit /*stick a fork in it, we're all done. */
/*─────────────────────────BLOAT subroutine─────────────────────────────*/
bloat: procedure; say
say 'Enter two positive integers (a 2-dimensional array will be created).'
pull n m . /*there is no way to pre-allocate an array,*/
/*REXX will allocate each element when it's*/
/*assigned. */
a.='~' /*default value for all elements so far. */
/*this ensures every element has a value. */
do j =1 for n
do k=1 for m
if random()//7==0 then a.j.k=j'_'k /*populate every 7th random*/
end /*k*/
end /*j*/
do r=1 for n /*display array to the console (row,col). */
_=
do c=1 for m
_=_ right(a.r.c,4) /*display one row at a time, align the vals*/
end /*kk*/
say _
end /*jj*/
/*when the RETURN is executed (from a */
/*PROCEDURE in this case), the array A. is*/
/*"de-allocated", that is, it's no longer */
/*defined, and the memory that the array */
/*has is now free for other REXX variables.*/
/*If the BLOAT subroutine didn't have */
/*a "PROCEDURE" on that statement, the */
/*array "a." would be left intact. */
/*The same effect is performed by a DROP. */
drop a. /*because of the PROCEDURE statement, */
return /* the DROP statement is superfluous. */

View file

@ -0,0 +1,5 @@
puts 'Enter width and height: '
w=gets.to_i
arr = Array.new(gets.to_i){Array.new(w)}
arr[1][3] = 5
p arr[1][3]

View file

@ -0,0 +1,10 @@
object Array2D{
def main(args: Array[String]): Unit = {
val x = Console.readInt
val y = Console.readInt
val a=Array.fill(x, y)(0)
a(0)(0)=42
println("The number at (0, 0) is "+a(0)(0))
}
}

View file

@ -0,0 +1,11 @@
m := (FillInTheBlankMorph request: 'Number of rows?') asNumber.
n := (FillInTheBlankMorph request: 'Number of columns?') asNumber.
aMatrix := Matrix rows: m columns: n.
aMatrix
at: (aMatrix rowCount // 2)
at: (aMatrix columnCount // 2)
put: 3.4.
e := aMatrix
at: (aMatrix rowCount // 2)
at: (aMatrix columnCount // 2).
Transcript show: 'Entry is', e printString.

View file

@ -0,0 +1,17 @@
|num1 num2 arr|
num1 := stdin nextLine asInteger.
num2 := stdin nextLine asInteger.
arr := MultidimensionalArray new: { num1. num2 }.
1 to: num1 do: [ :i |
1 to: num2 do: [ :j |
arr at: { i. j } put: (i*j)
]
].
1 to: num1 do: [ :i |
1 to: num2 do: [ :j |
(arr at: {i. j}) displayNl
]
].

View file

@ -0,0 +1,26 @@
Object subclass: BidimensionalArray [
|biArr|
<comment: 'bidim array'>
].
BidimensionalArray class extend [
new: biDim [ |r|
r := super new.
r init: biDim.
^ r
]
].
BidimensionalArray extend [
init: biDim [
biArr := Array new: (biDim at: 1).
1 to: (biDim at: 1) do: [ :i |
biArr at: i put: (Array new: (biDim at: 2))
].
^ self
]
at: biDim [
^ (biArr at: (biDim at: 1)) at: (biDim at: 2)
]
at: biDim put: val [
^ (biArr at: (biDim at: 1)) at: (biDim at: 2) put: val
]
].

View file

@ -0,0 +1,20 @@
|num1 num2 pseudoArr|
num1 := stdin nextLine asInteger.
num2 := stdin nextLine asInteger.
"we can 'suggest' an initial value for the number
of ''slot'' the table can hold; anyway, if we use
more than these, the table automatically grows"
pseudoArr := LookupTable new: (num1 * num2).
1 to: num1 do: [ :i |
1 to: num2 do: [ :j |
pseudoArr at: {i. j} put: (i * j).
]
].
1 to: num1 do: [ :i |
1 to: num2 do: [ :j |
(pseudoArr at: {i. j}) displayNl.
]
].

View file

@ -0,0 +1,17 @@
package require Tcl 8.5
puts "enter X dimension:"
set dim2 [gets stdin]
puts "enter Y dimension:"
set dim1 [gets stdin]
# Make the "array"; we'll keep it in row-major form
set l [lrepeat $dim1 [lrepeat $dim2 {}]]
# Select a point at around the middle of the "array"
set y [expr {$dim1>>1}]
set x [expr {$dim2>>1}]
# Set the value at that point
lset l $y $x aValue
# Read the value at that point
puts [lindex $l $y $x]
# Delete the "array"
unset l