Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,3 @@
---
from: http://rosettacode.org/wiki/Create_a_two-dimensional_array_at_runtime
note: Basic language learning

View file

@ -0,0 +1,3 @@
{{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,4 @@
V width = 3
V height = 5
V myarray = [[0] * width] * height
print(myarray[height-1][width-1])

View file

@ -0,0 +1,87 @@
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Array setup
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Create_2D_Array:
ARRAY_2D equ $100000
ARRAY_POINTER_VARIABLE equ $200000
; input: D0 = width, D1 = height
; assume the input is byte length and unsigned, ranging from 1 to FF.
AND.L #$000000FF,D0
AND.L #$000000FF,D1 ;sanitize the input to byte length.
LEA ARRAY_2D,A0 ;get base array address.
;The array's size will be measured in bytes, as this is how memory offsetting is measured.
;For this example the elements will all be 32-bit.
;Therefore, the dimensions need to be multiplied by the byte count of each element.
LSL.W #2,D0 ;four bytes per element = multiply by 4
LSL.W #2,D1
;Next, these values are multiplied to get the array's size.
MOVE.L D0,D2
MULU D1,D2
;D2 is the array's size (measured in bytes) and will be placed at the beginning.
;This does not count as an element of the array for the purposes of row/column indexing.
;The array's base address will be offset by 4 bytes prior to any indexing.
MOVE.L D2,(A0)+ ;store D2 in A0, add 4 to A0
MOVEA.L A0,[ARRAY_POINTER_VARIABLE]
;the brackets are optional, they show that this is a memory address label.
;this is still a move to a memory address with or without the brackets.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Storing a value in the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
LEA ARRAY_POINTER_VARIABLE,A1 ;load the address where the array's base address is stored.
MOVE.L (A1),A1 ;dereference the pointer and get ARRAY_2D+4 into A1.
; for this example the arbitrary row/column indices (2,5) will be used.
MOVE.L #2,D4
MULU D0,D4 ;there are D0 entries per row, multiply row index by elements per row.
MOVE.L #5,D5
MOVE.L #$00112233,D7 ;determine the value we want to store in the array.
; The bytes per element was factored into D0 when the array was created. So D4 is already where it should be.
LSL.L #2,D5 ;column index still needs to be scaled by the bytes per element.
LEA (A1,D4),A1 ;select the desired row.
;68000 doesn't allow you to use more than 1 data register at a time to offset. So we have to offset separately.
;Despite the use of parentheses this is NOT a dereference like it would be with "MOVE.L (A1),D7". D4 is merely added to the address in A1.
MOVE.L D7,(A1,D5) ;store #$00112233 in row 2, column 5 of the array.
;Loading a value is the same as storing it, except the operands in the last instruction are reversed, and MOVE.L #$00112233,D7
;is omitted.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Destroying the array
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; The array is destroyed by storing something else in its location. If you really want to reset it to zero, you can
; do so with the following:
LEA ARRAY_POINTER_VARIABLE,A1
MOVE.L (A1),A1
MOVE.L -(A1),D7
;get the array size into D7. Remember that the array's size was stored just before its data.
This value is potentially too large for a single DBRA, but it can be split up.
SWAP D7
MOVE.W D7,D6 ;get the top half of D7 into D6. D6 will be the outer loop's DBRA value.
SWAP D7
SUBQ.L #1,D7 ;D7 needs to be decremented by 1. D6 is fine the way it is.
MOVE.L (A0)+,D0 ;dummy move to increment the pointer back to the array base.
MOVEQ #0,D0 ;faster than MOVE.L #0,D0
loop_destroyArray:
MOVE.L D0,(A0)+
DBRA D7,loop_destroyArray ;loop using bottom 2 bytes of the array size as a loop counter
DBRA D6,loop_destroyArray ;decrement this, D7 is $FFFF each time execution gets here so this acts as a "carry" of sorts.
;if this value was 0 prior to the loop, the loop ends immediately.

View file

@ -0,0 +1,206 @@
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program createarray264.s */
/************************************/
/* Constantes */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ BUFFERSIZE, 64
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRead1: .asciz "Input size level 1 : "
szMessRead2: .asciz "Input size level 2 : "
szMessIndice1: .asciz "Indice 1 ="
szMessIndice2: .asciz " Indice 2 ="
szMessResult: .asciz " Item = "
szMessStart: .asciz "Program 64 bits start.\n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip BUFFERSIZE // conversion buffer
sZoneConv1: .skip BUFFERSIZE // conversion buffer
sZoneConv2: .skip BUFFERSIZE // conversion buffer
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessStart
bl affichageMess
ldr x0,qAdrszMessRead1
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,READ
svc 0 // call system
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD
mov x9,x0
ldr x0,qAdrszMessRead2
bl affichageMess
mov x0,#STDIN // Linux input console
ldr x1,qAdrsBuffer // buffer address
mov x2,#BUFFERSIZE // buffer size
mov x8,READ
svc 0 // call system
ldr x0,qAdrsBuffer // buffer address
bl conversionAtoD
mov x10,x0
// create array
lsl x12,x10,#3 // compute size level 2
mul x8,x12,x9 // compute size array
tst x8,0xF // multiple of 16 ?
add x11,x8,8 // if no add 8 octets
csel x8,x8,x11,eq // the stack must always be aligned on 16 bytes
// in 64 assembly arm
sub sp,sp,x8 // reserve place on stack
mov fp,sp // save array address
mov x0,#0 // init all items array
1: // begin loop1
mov x1,#0
2: // begin loop2
mul x2,x0,x12
add x2,x2,x1, lsl #3
str x2,[fp,x2] // store shift in array item
add x1,x1,#1
cmp x1,x10
blt 2b
add x0,x0,#1
cmp x0,x9
blt 1b
mov x0,fp
mov x1,#1 // second indice level 1
mov x2,#0 // first indice level 2
mov x3,x12 // level 2 size
bl displayItem
mov x0,fp
sub x1,x9,#1 // last level 1
sub x2,x10,#1 // last level 2
mov x3,x12 // level 2 size
bl displayItem
add sp,sp,x8 // release space on stack
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrsZoneConv1: .quad sZoneConv1
qAdrsZoneConv2: .quad sZoneConv2
qAdrszMessRead1: .quad szMessRead1
qAdrszMessRead2: .quad szMessRead2
qAdrsBuffer: .quad sBuffer
qAdrszMessResult: .quad szMessResult
qAdrszMessStart: .quad szMessStart
qAdrszMessIndice1: .quad szMessIndice1
qAdrszMessIndice2: .quad szMessIndice2
/***************************************************/
/* display array item */
/***************************************************/
/* x0 array address */
/* x1 indice 1 */
/* x2 indice 2 */
/* x3 level 2 size */
displayItem:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,fp,[sp,-16]! // save registers
mov x5,x0
mov x6,x1
mov x0,x6
ldr x1,qAdrsZoneConv
bl conversion10 // conversion indice 1
mov x0,x2
ldr x1,qAdrsZoneConv1
bl conversion10 // conversion indice 2
mul x4,x6,x3 // multiply indice level 1 by level 2 size
add x4,x4,x2, lsl #3 // add indice level 2 * 8 (8 bytes)
ldr x0,[x5,x4] // load array item
ldr x1,qAdrsZoneConv2
bl conversion10
mov x0,#7 // string number to display
ldr x1,qAdrszMessIndice1
ldr x2,qAdrsZoneConv // insert conversion in message
ldr x3,qAdrszMessIndice2
ldr x4,qAdrsZoneConv1 // insert conversion in message
ldr x5,qAdrszMessResult
ldr x6,qAdrsZoneConv2 // insert conversion in message
ldr x7,qAdrszCarriageReturn
bl displayStrings // display message
100:
ldp x6,fp,[sp],16 // restaur registers
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* display multi strings */
/* new version 24/05/2023 */
/***************************************************/
/* x0 contains number strings address */
/* x1 address string1 */
/* x2 address string2 */
/* x3 address string3 */
/* x4 address string4 */
/* x5 address string5 */
/* x6 address string5 */
/* x7 address string6 */
displayStrings: // INFO: displayStrings
stp x8,lr,[sp,-16]! // save registers
stp x2,fp,[sp,-16]! // save registers
add fp,sp,#32 // save paraméters address (4 registers saved * 8 bytes)
mov x8,x0 // save strings number
cmp x8,#0 // 0 string -> end
ble 100f
mov x0,x1 // string 1
bl affichageMess
cmp x8,#1 // number > 1
ble 100f
mov x0,x2
bl affichageMess
cmp x8,#2
ble 100f
mov x0,x3
bl affichageMess
cmp x8,#3
ble 100f
mov x0,x4
bl affichageMess
cmp x8,#4
ble 100f
mov x0,x5
bl affichageMess
cmp x8,#5
ble 100f
mov x0,x6
bl affichageMess
cmp x8,#6
ble 100f
mov x0,x7
bl affichageMess
100:
ldp x2,fp,[sp],16 // restaur registers
ldp x8,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"

View file

@ -0,0 +1,13 @@
begin
comment Create a two-dimensional array at runtime - Algol 60;
integer n,m;
ininteger(0,m);
ininteger(0,n);
begin
integer array a[1:m,1:n];
a[m,n] := 99;
outinteger(1,a[m,n]);
outstring(1,"\n")
end;
comment array a : out of scope;
end

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,22 @@
begin
integer dimension1UpperBound, dimension2UpperBound;
write( "upper bound for dimension 1: " );
read( dimension1UpperBound );
write( "upper bound for dimension 2: " );
read( dimension2UpperBound );
begin
% we start a new block because declarations must precede statements %
% and variables in array bounds must be from outside the block %
integer array matrix ( 1 :: dimension1UpperBound
, 1 :: dimension2UpperBound
);
% set the first element - the program will crash if the user input %
% upper bounds less than 1 %
matrix( 1, 1 ) := 3;
% write it %
write( matrix( 1, 1 ) );
% the array is automatically deleted when the block ends %
end
end.

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,193 @@
/* ARM assembly Raspberry PI */
/* program createarray2.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ STDIN, 0 @ Linux input console
.equ READ, 3 @ Linux syscall
.equ BUFFERSIZE, 64
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRead1: .asciz "Input size level 1 : "
szMessRead2: .asciz "Input size level 2 : "
szMessIndice1: .asciz "Indice 1 ="
szMessIndice2: .asciz "Indice 2 ="
szMessResult: .asciz "Item = "
szMessStart: .asciz "Program 32 bits start.\n"
szCarriageReturn: .asciz "\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip BUFFERSIZE // conversion buffer
sZoneConv1: .skip BUFFERSIZE // conversion buffer
sZoneConv2: .skip BUFFERSIZE // conversion buffer
sBuffer: .skip BUFFERSIZE
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessStart
bl affichageMess
ldr r0,iAdrszMessRead1
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ request to read datas
svc 0 @ call system
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD
mov r9,r0
ldr r0,iAdrszMessRead2
bl affichageMess
mov r0,#STDIN @ Linux input console
ldr r1,iAdrsBuffer @ buffer address
mov r2,#BUFFERSIZE @ buffer size
mov r7,#READ @ request to read datas
svc 0 @ call system
ldr r0,iAdrsBuffer @ buffer address
bl conversionAtoD
mov r10,r0
@ create array
lsl r12,r10,#2 @ compute size level 2
mul r8,r12,r9 @ compute size array
sub sp,sp,r8 @ reserve place on stack
mov fp,sp
mov r0,#0 @ init all items array
1: @ begin loop1
mov r1,#0
2: @ begin loop2
mul r2,r0,r12
add r2,r2,r1, lsl #2
str r2,[fp,r2] @ store shift in array item
add r1,r1,#1
cmp r1,r10
blt 2b
add r0,r0,#1
cmp r0,r9
blt 1b
mov r0,fp
mov r1,#1 @ second indice level 1
mov r2,#0 @ first indice level 2
mov r3,r12 @ level 2 size
bl displayItem
mov r0,fp
sub r1,r9,#1 @ last level 1
sub r2,r10,#1 @ last level 2
mov r3,r12 @ level 2 size
bl displayItem
add sp,sp,r8 @ release space on stack
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrsZoneConv1: .int sZoneConv1
iAdrsZoneConv2: .int sZoneConv2
iAdrszMessRead1: .int szMessRead1
iAdrszMessRead2: .int szMessRead2
iAdrsBuffer: .int sBuffer
iAdrszMessResult: .int szMessResult
iAdrszMessStart: .int szMessStart
iAdrszMessIndice1: .int szMessIndice1
iAdrszMessIndice2: .int szMessIndice2
/***************************************************/
/* display array item */
/***************************************************/
/* r0 array address */
/* r1 indice 1 */
/* r2 indice 2 */
/* r3 level 2 size */
displayItem:
push {r1-r6,lr} @ save des registres
mov r5,r0
mov r6,r1
mov r0,r6
ldr r1,iAdrsZoneConv
bl conversion10 @ conversion indice 1
mov r0,r2
ldr r1,iAdrsZoneConv1
bl conversion10 @ conversion indice 2
mul r4,r6,r3 @ multiply indice level 1 by level 2 size
add r4,r4,r2, lsl #2 @ add indice level 2 * 4 (4 bytes)
ldr r0,[r5,r4] @ load array item
ldr r1,iAdrsZoneConv2
bl conversion10
mov r0,#7 @ string number to display
ldr r1,iAdrszMessIndice1
ldr r2,iAdrsZoneConv @ insert conversion in message
ldr r3,iAdrszMessIndice2
ldr r4,iAdrsZoneConv1 @ insert conversion in message
push {r4}
ldr r4,iAdrszMessResult
push {r4}
ldr r4,iAdrsZoneConv2 @ insert conversion in message
push {r4}
ldr r4,iAdrszCarriageReturn
push {r4}
bl displayStrings @ display message
add sp,sp,#16
100:
pop {r1-r6,pc}
/***************************************************/
/* display multi strings */
/***************************************************/
/* r0 contains number strings address */
/* r1 address string1 */
/* r2 address string2 */
/* r3 address string3 */
/* other address on the stack */
/* thinck to add number other address * 4 to add to the stack */
displayStrings: @ INFO: displayStrings
push {r1-r4,fp,lr} @ save des registres
add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes)
mov r4,r0 @ save strings number
cmp r4,#0 @ 0 string -> end
ble 100f
mov r0,r1 @ string 1
bl affichageMess
cmp r4,#1 @ number > 1
ble 100f
mov r0,r2
bl affichageMess
cmp r4,#2
ble 100f
mov r0,r3
bl affichageMess
cmp r4,#3
ble 100f
mov r3,#3
sub r2,r4,#4
1: @ loop extract address string on stack
ldr r0,[fp,r2,lsl #2]
bl affichageMess
subs r2,#1
bge 1b
100:
pop {r1-r4,fp,pc}
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"

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,108 @@
CARD EndProg ;required for ALLOCATE.ACT
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
DEFINE PTR="CARD"
DEFINE INT_SIZE="2"
DEFINE CARD_SIZE="2"
TYPE IntArray2D=[BYTE rows,cols PTR p]
BYTE FUNC GetNumber(CHAR ARRAY s)
BYTE n,min=[1],max=[100]
DO
PrintF("Get number of %S (%B..%B): ",s,min,max)
n=InputB()
IF n>=min AND n<=max THEN
EXIT
FI
OD
RETURN (n)
PROC Create(IntArray2D POINTER a)
PTR ARRAY rowArray
BYTE row
IF a.p#0 THEN Break() FI
rowArray=Alloc(a.rows*CARD_SIZE)
a.p=rowArray
FOR row=0 TO a.rows-1
DO
rowArray(row)=Alloc(a.cols*INT_SIZE)
OD
RETURN
PROC Destroy(IntArray2D POINTER a)
PTR ARRAY rowArray
BYTE row
IF a.p=0 THEN Break() FI
rowArray=a.p
FOR row=0 TO a.rows-1
DO
Free(rowArray(row),a.cols*INT_SIZE)
OD
Free(a.p,a.rows*CARD_SIZE)
a.p=0
RETURN
PROC SetValue(IntArray2D POINTER a BYTE row,col INT v)
PTR ARRAY rowArray
INT ARRAY colArray
IF a.p=0 OR row>=a.rows OR col>=a.cols THEN
Break()
FI
rowArray=a.p
colArray=rowArray(row)
colArray(col)=v
RETURN
INT FUNC GetValue(IntArray2D POINTER a BYTE row,col)
PTR ARRAY rowArray
INT ARRAY colArray
IF a.p=0 OR row>=a.rows OR col>=a.cols THEN
Break()
FI
rowArray=a.p
colArray=rowArray(row)
RETURN (colArray(col))
PROC TestCreate(IntArray2D POINTER a)
PrintF("Create array of %B rows and %B cols%E",a.rows,a.cols)
Create(a)
RETURN
PROC TestDestroy(IntArray2D POINTER a)
PrintF("Destroy array of %B rows and %B cols%E",a.rows,a.cols)
Destroy(a)
RETURN
PROC TestSetValue(IntArray2D POINTER a BYTE row,col INT v)
PrintF("Write %I to row %B and col %B%E",v,row,col)
SetValue(a,row,col,v)
RETURN
PROC TestGetValue(IntArray2D POINTER a BYTE row,col)
INT v
v=GetValue(a,row,col)
PrintF("Read at row %B and col %B: %I%E",row,col,v)
RETURN
PROC Main()
IntArray2D a
Put(125) PutE() ;clear screen
AllocInit(0)
a.rows=GetNumber("rows")
a.cols=GetNumber("cols")
a.p=0
TestCreate(a)
TestSetValue(a,a.rows/2,a.cols/2,6502)
TestGetValue(a,a.rows/2,a.cols/2)
TestDestroy(a)
RETURN

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,20 @@
#include <flow.h>
#import lib/input.bas.lib
#include include/flow-input.h
DEF-MAIN
CLR-SCR
MSET(nRow, nCol)
LOCATE( 2,5 ), PRN("Input size rows :")
LOC-COL( 23 ), LET( nRow := ABS(VAL(READ-NUMBER( nRow ) )))
LOCATE( 3,5 ), PRN("Input size cols :")
LOC-COL( 23 ), LET( nCol := ABS(VAL(READ-NUMBER( nCol ) )))
COND( IS-NOT-ZERO?( MUL(nRow,nCol) ) )
DIM(nRow, nCol) AS-VOID( array )
BLK-[1,1], {100} PUT(array)
PRNL("\tElement at position 1,1 : ", GET(array) )
CLEAR(array) /* destroy array */
CEND
END
SUBRUTINES

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,7 @@
10 INPUT "ENTER TWO INTEGERS:"; X%, Y%
20 DIM A%(X% - 1, Y% - 1)
30 X% = RND(1) * X%
40 Y% = RND(1) * Y%
50 A%(X%, Y%) = -32767
60 PRINT A%(X%, Y%)
70 CLEAR

View file

@ -0,0 +1,11 @@
width: to :integer input "give me the array's width: "
height: to :integer input "give me the array's height: "
arr: array.of: @[width height] 0
x: random 0 dec width
y: random 0 dec height
arr\[x]\[y]: 123
print ["item at [" x "," y "] =" arr\[x]\[y]]

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,7 @@
arraybase 1
input integer "Enter one positive integer: ", i
input integer "Enter other positive integer: ", j
dim a(i, j)
a[i, j] = i * j
print "a("; string(i); ","; string(j); ") = "; a[i, j]
end

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,14 @@
#!/usr/bin/env bqn
# Cut 𝕩 at occurrences of 𝕨, removing separators and empty segments
# (BQNcrate phrase).
Split (¬-˜×·+`»>)
# Natural number from base-10 digits (BQNcrate phrase).
Base10 10×+˜´
# Parse any number of space-separated numbers from string 𝕩.
ParseNums {Base10¨ -'0' ' ' Split 𝕩}
# •GetLine is a nonstandard CBQN extension.
•Show (×´) ParseNums •GetLine@

View file

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

View file

@ -0,0 +1,21 @@
#include <iostream>
#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()
return 0;
}

View file

@ -0,0 +1,22 @@
#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 element
A[0][0] = 3.1415;
// read element
std::cout << A[0][0] << std::endl;
return 0;
}

View file

@ -0,0 +1,18 @@
#include <cstdlib>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/io.hpp>
int main (const int argc, const char** argv) {
if (argc > 2) {
using namespace boost::numeric::ublas;
matrix<double> m(atoi(argv[1]), atoi(argv[2])); // build
for (unsigned i = 0; i < m.size1(); i++)
for (unsigned j = 0; j < m.size2(); j++)
m(i, j) = 1.0 + i + j; // fill
std::cout << m << std::endl; // print
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}

View file

@ -0,0 +1,14 @@
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter two integers. Space delimited please: ");
string s = Console.ReadLine();
int[,] myArray=new int[(int)s[0],(int)s[2]];
myArray[0, 0] = 2;
Console.WriteLine(myArray[0, 0]);
Console.ReadLine();
}
}

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,116 @@
/*
assume this file is c.c ,
compile and run on linux: cc -Wall -g -DCOMPILE_EXAMPLE c.c -lm -o c && ./c
*/
#include<stdlib.h>
#include<stdio.h>
static void error(int status, char*message) {
fprintf(stderr,"\n%s\n",message);
exit(status);
}
static void*dwlcalloc(int n,size_t bytes) {
void*rv = (void*)calloc(n,bytes);
if (NULL == rv)
error(1, "memory allocation failure");
return rv;
}
void*allocarray(size_t rank,size_t*shape,size_t itemSize) {
/*
Allocates arbitrary dimensional arrays (and inits all pointers)
with only 1 call to malloc. Lambert Electronics, USA, NY.
This is wonderful because one only need call free once to deallocate
the space. Special routines for each size array are not need for
allocation of for deallocation. Also calls to malloc might be expensive
because they might have to place operating system requests. One call
seems optimal.
*/
size_t size,i,j,dataSpace,pointerSpace,pointers,nextLevelIncrement;
char*memory,*pc,*nextpc;
if (rank < 2) {
if (rank < 0)
error(1,"invalid negative rank argument passed to allocarray");
size = rank < 1 ? 1 : *shape;
return dwlcalloc(size,itemSize);
}
pointerSpace = 0, dataSpace = 1;
for (i = 0; i < rank-1; ++i)
pointerSpace += (dataSpace *= shape[i]);
pointerSpace *= sizeof(char*);
dataSpace *= shape[i]*itemSize;
memory = pc = dwlcalloc(1,pointerSpace+dataSpace);
pointers = 1;
for (i = 0; i < rank-2; ) {
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*sizeof(char*);
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
}
nextpc = pc + (pointers *= shape[i])*sizeof(char*);
nextLevelIncrement = shape[++i]*itemSize;
for (j = 0; j < pointers; ++j)
*((char**)pc) = nextpc, pc+=sizeof(char*), nextpc += nextLevelIncrement;
return memory;
}
#ifdef COMPILE_EXAMPLE
#include<string.h>
#include<math.h>
#define Z 5
#define Y 10
#define X 39
#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L))
void p_char(void*pv) {
char s[3];
int i = 0;
s[i++] = ' ', s[i++] = *(char*)pv, s[i++] = 0;
fputs(s, stdout);
}
void display(void*a,size_t rank,size_t*shape,void(*f)(void*)) {
int i;
if (0 == rank)
(*f)(a);
else if (1 == rank) {
for (i = 0; i < *shape; ++i)
(*f)(a+i);
putchar('\n');
} else {
for (i = 0; i < *shape; ++i)
display(((void**)a)[i], rank-1, shape+1, f);
putchar('\n');
}
}
int main() { /* character cell 3D graphics. Whoot */
char***array;
float x,y,z;
size_t rank, shape[3], i, j, k;
rank = 0;
shape[rank++] = Z, shape[rank++] = Y, shape[rank++] = X;
array = allocarray(rank, shape, sizeof(char));
memset(**array, ' ', X*Y*Z*(sizeof(***array))); /* load the array with spaces */
for (i = 0; i < X; ++i) {
x = i/(float)X;
for (j = 0; j < Y; ++j) {
y = j/(float)X;
z = x*y*(4*M_PI);
z = 5.2*(0.5+(0.276765 - sin(z)*cos(z)*exp(1-z))/0.844087); /* a somewhat carefully designed silly function */
/* printf("%g %g %g\n", x, y, z); */
k = (int)z;
array[BIND(k, 0, Z-1)][j][i] = '@'; /* BIND ensures a valid index */
}
}
display(array, rank, shape, p_char);
puts("\nIt is what it is.");
free(array);
return EXIT_SUCCESS;
}
#endif

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(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]);
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, offset;
printf("Enter size of array: ");
scanf("%d",&user1);
space_needed = (user1+1)*user1/2;
a1 = malloc(space_needed * sizeof(*a1));
array = malloc(user1 * sizeof(*array));
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,30 @@
prompt = proc (s: string) returns (int)
stream$puts(stream$primary_output(), s)
return(int$parse(stream$getl(stream$primary_input())))
end prompt
start_up = proc ()
po: stream := stream$primary_output()
% Ask for width and height
width: int := prompt("Width? ")
height: int := prompt("Height? ")
% Create an array of arrays.
% In order to actually create separate arrays, rather than repeating
% a reference to the same array over and over, fill_copy must be used.
arr: array[array[int]] :=
array[array[int]]$fill_copy(1, width, array[int]$fill(1, height, 0))
% Set a value
x: int := 1+width/2
y: int := 1+height/2
arr[x][y] := 123
% Retrieve the value
stream$putl(po, "arr[" || int$unparse(x) || "][" || int$unparse(y)
|| "] = " || int$unparse(arr[x][y]))
% The array will be automatically garbage-collected once there
% are no more references to it.
end start_up

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,11 @@
10 print chr$(147);chr$(14);
15 print "Size of array:"
20 print "Columns (1-20)";:input x%
25 if x%<1 or x%>20 then print "Try again.":goto 20
30 print "Rows (1-20)";:input y%
35 if y%<1 or y%>20 then print "Try again.":goto 30
40 x%=x%-1:y%=y%-1:dim a$(x%,y%)
50 nx=int(rnd(1)*x%):ny=int(rnd(1)*y%)
60 a$(nx,ny)="X"
70 print "Element";nx;",";ny;"= '";a$(nx,ny);"'"
80 clr:rem clear variables from ram

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,14 @@
require "random"
first = gets.not_nil!.to_i32
second = gets.not_nil!.to_i32
arr = Array(Array(Int32)).new(first, Array(Int32).new second, 0)
random = Random.new
first = random.rand 0..(first - 1)
second = random.rand 0..(second - 1)
arr[first][second] = random.next_int
puts arr[first][second]

View file

@ -0,0 +1,24 @@
void main() {
import std.stdio, std.conv, std.string;
int nRow, nCol;
write("Give me the numer of rows: ");
try {
nRow = readln.strip.to!int;
} catch (StdioException) {
nRow = 3;
writeln;
}
write("Give me the numer of columns: ");
try {
nCol = readln.strip.to!int;
} catch (StdioException) {
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,12 @@
PROGRAM DYNAMIC
!$DYNAMIC
DIM A%[0,0]
BEGIN
PRINT(CHR$(12);) !CLS
INPUT("Subscripts",R%,C%)
!$DIM A%[R%,C%]
A%[2,3]=6
PRINT("Value in row";2;"and col";3;"is";A%[2,3])
END PROGRAM

View file

@ -0,0 +1,16 @@
import extensions;
public program()
{
var n := new Integer();
var m := new Integer();
console.write:"Enter two space delimited integers:";
console.loadLine(n,m);
var myArray := class Matrix<int>.allocate(n,m);
myArray.setAt(0,0,2);
console.printLine(myArray.at(0, 0))
}

View file

@ -0,0 +1,18 @@
import system'routines;
import extensions;
public program()
{
auto n := new Integer();
auto m := new Integer();
console.write:"Enter two space delimited integers:";
console.loadLine(n,m);
auto myArray2 := new object[][](n.Value).populate:(int i => (new object[](m.Value)) );
myArray2[0][0] := 2;
myArray2[1][0] := "Hello";
console.printLine(myArray2[0][0]);
console.printLine(myArray2[1][0]);
}

View file

@ -0,0 +1,29 @@
defmodule TwoDimArray do
def create(w, h) do
List.duplicate(0, w)
|> List.duplicate(h)
end
def set(arr, x, y, value) do
List.replace_at(arr, x,
List.replace_at(Enum.at(arr, x), y, value)
)
end
def get(arr, x, y) do
arr |> Enum.at(x) |> Enum.at(y)
end
end
width = IO.gets "Enter Array Width: "
w = width |> String.trim() |> String.to_integer()
height = IO.gets "Enter Array Height: "
h = height |> String.trim() |> String.to_integer()
arr = TwoDimArray.create(w, h)
arr = TwoDimArray.set(arr,2,0,42)
IO.puts(TwoDimArray.get(arr,2,0))

View file

@ -0,0 +1,18 @@
-module( two_dimensional_array ).
-export( [create/2, get/3, set/4, task/0] ).
create( X, Y ) -> array:new( [{size, X}, {default, array:new( [{size, Y}] )}] ).
get( X, Y, Array ) -> array:get( Y, array:get(X, Array) ).
set( X, Y, Value, Array ) ->
Y_array = array:get( X, Array ),
New_y_array = array:set( Y, Value, Y_array ),
array:set( X, New_y_array, Array ).
task() ->
{ok, [X, Y]} = io:fread( "Input two integers. Space delimited, please: ", "~d ~d" ),
Array = create( X, Y ),
New_array = set( X - 1, Y - 1, X * Y, Array ),
io:fwrite( "In position ~p ~p we have ~p~n", [X - 1, Y - 1, get( X - 1, Y - 1, New_array)] ).

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,7 @@
open System
let width = int( Console.ReadLine() )
let height = int( Console.ReadLine() )
let arr = Array2D.create width height 0
arr.[0,0] <- 42
printfn "%d" arr.[0,0]

View file

@ -0,0 +1,14 @@
USING: io kernel math.matrices math.parser prettyprint
sequences ;
IN: rosettacode.runtime2darray
: set-Mi,j ( elt {i,j} matrix -- )
[ first2 swap ] dip nth set-nth ;
: Mi,j ( {i,j} matrix -- elt )
[ first2 swap ] dip nth nth ;
: example ( -- )
readln readln [ string>number ] bi@ zero-matrix ! create the array
[ [ 42 { 0 0 } ] dip set-Mi,j ] ! set the { 0 0 } element to 42
[ [ { 0 0 } ] dip Mi,j . ] ! read the { 0 0 } element
bi ;

View file

@ -0,0 +1,6 @@
?m; {imput the dimensions of the array}
?n;
Array a[m,n]; {generate an array of m rows and n columns}
a[m\2, n\2] := m+n-1; {put some value in one of the cells}
!!a[m\2, n\2]; {display that entry}
@[a]; {delete the array}

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,11 @@
' FB 1.05.0 Win64
Dim As Integer i, j
Input "Enter two positive integers, separated by a comma"; i, j
Dim a(1 To i, 1 To j) As Integer
a(i, j) = i * j
Print "a("; Str(i); ","; Str(j); ") ="; a(i, j)
Erase a
Print
Print "Press any key to quit"
Sleep

View file

@ -0,0 +1,4 @@
[rows, cols] = dims = eval[input["Enter dimensions: ", ["Rows", "Columns"]]]
a = new array[dims, 0] // Create and initialize to 0
a@(rows-1)@(cols-1) = 10
println[a@(rows-1)@(cols-1)]

View file

@ -0,0 +1,15 @@
# Creating an array of 0
a := NullMat(2, 2);
# [ [ 0, 0 ], [ 0, 0 ] ]
# Some assignments
a[1][1] := 4;
a[1][2] := 5;
a[2][1] := 3;
a[2][2] := 4;
a
# [ [ 4, 5 ], [ 3, 4 ] ]
Determinant(a);
# 1

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,3 @@
def make2d = { nrows, ncols ->
(0..<nrows).collect { [0]*ncols }
}

View file

@ -0,0 +1,19 @@
def r = new Random()
System.in.splitEachLine(/,\s*/) { dim ->
def nrows = dim[0] as int
def ncols = dim[1] as int
def a2d = make2d(nrows, ncols)
def row = r.nextInt(nrows)
def col = r.nextInt(ncols)
def val = r.nextInt(nrows*ncols)
a2d[row][col] = val
println "a2d[${row}][${col}] == ${a2d[row][col]}"
a2d.each { println it }
println()
}

View file

@ -0,0 +1,3 @@
import Data.Array
doit n m = a!(0,0) where a = array ((0,0),(n,m)) [((0,0),42)]

View file

@ -0,0 +1,7 @@
REAL :: array(1)
DLG(NameEdit=rows, NameEdit=cols, Button='OK', TItle='Enter array dimensions')
ALLOCATE(array, cols, rows)
array(1,1) = 1.234
WRITE(Messagebox, Name) array(1,1)

View file

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

View file

@ -0,0 +1,4 @@
100 INPUT PROMPT "Enter array dimensions separated by a coma: ":A,B
110 NUMERIC ARRAY(1 TO A,1 TO B)
120 LET ARRAY(1,1)=PI
130 PRINT ARRAY(1,1)

View file

@ -0,0 +1,13 @@
procedure main(args)
nr := integer(args[1]) | 3 # Default to 3x3
nc := integer(args[2]) | 3
A := list(nr)
every !A := list(nc)
x := ?nr # Select a random element
y := ?nc
A[x][y] := &pi
write("A[",x,"][",y,"] -> ",A[x][y])
end

View file

@ -0,0 +1,2 @@
array1=:i. 3 4 NB. a 3 by 4 array with arbitrary values
array2=: 5 6 $ 2 NB. a 5 by 6 array where every value is the number 2

View file

@ -0,0 +1 @@
array1=: 99 (<0 0)} array1

View file

@ -0,0 +1,9 @@
task=: verb define
assert. y -: 0 0 + , y NB. error except when 2 dimensions are specified
INIT=. 0 NB. array will be populated with this value
NEW=. 1 NB. we will later update one location with this value
ARRAY=. y $ INIT NB. here, we create our 2-dimensional array
INDEX=. < ? $ ARRAY NB. pick an arbitrary location within our array
ARRAY=. NEW INDEX} ARRAY NB. use our new value at that location
INDEX { ARRAY NB. and return the value from that location
)

View file

@ -0,0 +1,3 @@
'init new' =. ' ';'x' NB. literals
'init new' =. 1r2;2r3 NB. fractions
'init new' =. a: ; <<'Rosetta' NB. boxes

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,17 @@
var width = Number(prompt("Enter width: "));
var height = Number(prompt("Enter height: "));
//make 2D array
var arr = new Array(height);
for (var i = 0; i < h; i++) {
arr[i] = new Array(width);
}
//set value of element
a[0][0] = 'foo';
//print value of element
console.log('arr[0][0] = ' + arr[0][0]);
//cleanup array
arr = void(0);

View file

@ -0,0 +1,11 @@
# A function to create an m x n matrix
# filled with the input element
def matrix(m;n):
. as $init
| ( [ range(0; n + 1) ] | map($init)) as $row
| ( [ range(0; m + 1) ] | map($row))
;
# Task: create a matrix with dimensions specified by the user
# and set the [1,2] element:
(0 | matrix($m|tonumber; $n|tonumber)) | setpath([1,2]; 99)

View file

@ -0,0 +1 @@
[[0,0,0,0],[0,0,99,0],[0,0,0,0]]

View file

@ -0,0 +1,16 @@
function input(prompt::AbstractString)
print(prompt)
return readline()
end
n = input("Upper bound for dimension 1: ") |>
x -> parse(Int, x)
m = input("Upper bound for dimension 2: ") |>
x -> parse(Int, x)
x = rand(n, m)
display(x)
x[3, 3] # overloads `getindex` generic function
x[3, 3] = 5.0 # overloads `setindex!` generic function
x::Matrix # `Matrix{T}` is an alias for `Array{T, 2}`
x = 0; gc() # Julia has no `del` command, rebind `x` and call the garbage collector

View file

@ -0,0 +1,15 @@
fun main(args: Array<String>) {
// build
val dim = arrayOf(10, 15)
val array = Array(dim[0], { IntArray(dim[1]) } )
// fill
array.forEachIndexed { i, it ->
it.indices.forEach { j ->
it[j] = 1 + i + j
}
}
// print
array.forEach { println(it.asList()) }
}

View file

@ -0,0 +1,9 @@
input "Enter first array dimension "; a
input "Enter second array dimension "; b
dim array( a, b)
array( 1, 1) = 123.456
print array( 1, 1)
end

View file

@ -0,0 +1,3 @@
make "a2 mdarray [5 5]
mdsetitem [1 1] :a2 0 ; by default, arrays are indexed starting at 1
print mditem [1 1] :a2 ; 0

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,15 @@
Module CheckArray {
Do {
Input "A, B=", A% ,B%
} Until A%>0 and B%>0
\\ 1@ is 1 Decimal
addone=lambda N=1@ ->{=N : N++}
Dim Base 1, Arr(A%,B%)<<addone()
\\ pi also is decimal
Arr(1,1)=pi
Print Arr(1,1)
Print Arr()
\\ all variables/arrays/inner functions/modules erased now
}
CheckArray

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,11 @@
a = getKBValue prompt:"Enter first dimension:"
b = getKBValue prompt:"Enter second dimension:"
arr1 = #()
arr2 = #()
arr2[b] = undefined
for i in 1 to a do
(
append arr1 (deepCopy arr2)
)
arr1[a][b] = 1
print arr1[a][b]

View file

@ -0,0 +1,11 @@
ARA2D
NEW X,Y,A,I,J
REARA
WRITE !,"Please enter two positive integers"
READ:10 !,"First: ",X
READ:10 !,"Second: ",Y
GOTO:(X\1'=X)!(X<0)!(Y\1'=Y)!(Y<0) REARA
FOR I=1:1:X FOR J=1:1:Y SET A(I,J)=I+J
WRITE !,"The corner of X and Y is ",A(X,Y)
KILL X,Y,A,I,J
QUIT

View file

@ -0,0 +1,12 @@
> a := Array( 1 .. 3, 1 .. 4 ): # initialised to 0s
> a[1,1] := 1: # assign an element
> a[2,3] := 4: # assign an element
> a; # display the array
[1 0 0 0]
[ ]
[0 0 4 0]
[ ]
[0 0 0 0]
> a := 'a': # unassign the name
> gc(); # force a garbage collection; may or may not actually collect the array, but it will be eventually

View file

@ -0,0 +1,4 @@
arrayFun[m_Integer,n_Integer]:=Module[{array=ConstantArray[0,{m,n}]},
array[[1,1]]=RandomReal[];
array[[1,1]]
]

View file

@ -0,0 +1,9 @@
printf(true, "in the following terminate every number with semicolon `;'")$
n: readonly("Input x-size: ")$
m: readonly("Input y-size: ")$
a: make_array(fixnum, n, m)$
fillarray(a, makelist(i, i, 1, m*n))$
/* indexing starts from 0 */
print(a[0,0]);
print(a[n-1,m-1]);

View file

@ -0,0 +1,12 @@
/* NetRexx */
options replace format comments java crossref symbols nobinary
say "give me the X and Y dimensions as two positive integers:"
parse ask xDim yDim
xPos = xDim % 2 -- integer divide to get close to the middle of the array
yPos = yDim % 2
arry = Rexx[xDim, yDim]
arry[xPos, yPos] = xDim / yDim -- make up a value...
say "arry["xPos","yPos"]:" arry[xPos, yPos]
return

View file

@ -0,0 +1,20 @@
import strutils, rdstdin
let
w = readLineFromStdin("Width: ").parseInt()
h = readLineFromStdin("Height: ").parseInt()
# Create the rows.
var s = newSeq[seq[int]](h)
# Create the columns.
for i in 0 ..< h:
s[i].newSeq(w)
# Store a value in an element.
s[0][0] = 5
# Retrieve and print it.
echo s[0][0]
# The allocated memory is freed by the garbage collector.

View file

@ -0,0 +1,5 @@
let nbr1 = read_int ();;
let nbr2 = read_int ();;
let array = Array.make_matrix nbr1 nbr2 0.0;;
array.(0).(0) <- 3.5;;
print_float array.(0).(0); print_newline ();;

View file

@ -0,0 +1,5 @@
let nbr1 = read_int ();;
let nbr2 = read_int ();;
let arr = Bigarray.Array2.create Bigarray.float32 Bigarray.c_layout nbr1 nbr2 ;;
arr.{0,0} <- 3.5;;
print_float arr.{0,0}; print_newline ();;

View file

@ -0,0 +1,23 @@
use IO;
bundle Default {
class TwoDee {
function : Main(args : System.String[]) ~ Nil {
DoIt();
}
function : native : DoIt() ~ Nil {
Console->GetInstance()->Print("Enter x: ");
x := Console->GetInstance()->ReadString()->ToInt();
Console->GetInstance()->Print("Enter y: ");
y := Console->GetInstance()->ReadString()->ToInt();
if(x > 0 & y > 0) {
array : Int[,] := Int->New[x, y];
array[0, 0] := 2;
array[0, 0]->PrintLine();
};
}
}
}

View file

@ -0,0 +1,26 @@
#import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
int num1, num2;
scanf("%d %d", &num1, &num2);
NSLog(@"%d %d", num1, num2);
NSMutableArray *arr = [NSMutableArray arrayWithCapacity: (num1*num2)];
// initialize it with 0s
for(int i=0; i < (num1*num2); i++) [arr addObject: @0];
// replace 0s with something more interesting
for(int i=0; i < num1; i++) {
for(int j=0; j < num2; j++) {
arr[i*num2+j] = @(i*j);
}
}
// access a value: i*num2+j, where i,j are the indexes for the bidimensional array
NSLog(@"%@", arr[1*num2+3]);
}
return 0;
}

View file

@ -0,0 +1,11 @@
Say "enter first dimension"
pull d1
say "enter the second dimension"
pull d2
a = .array~new(d1, d2)
a[1, 1] = "Abc"
say a[1, 1]
say d1 d2 a[d1,d2]
say a[10,10]
max=1000000000
b = .array~new(max,max)

View file

@ -0,0 +1,15 @@
declare
%% Read width and height from stdin
class TextFile from Open.file Open.text end
StdIn = {New TextFile init(name:stdin)}
Width = {String.toInt {StdIn getS($)}}
Height = {String.toInt {StdIn getS($)}}
%% create array
Arr = {Array.new 1 Width unit}
in
for X in 1..Width do
Arr.X := {Array.new 1 Height 0}
end
%% set and read element
Arr.1.1 := 42
{Show Arr.1.1}

View file

@ -0,0 +1,5 @@
tmp(m,n)={
my(M=matrix(m,n,i,j,0));
M[1,1]=1;
M[1,1]
};

Some files were not shown because too many files have changed in this diff Show more