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

→‎{{header|Tcl}}: ++ smalltalk
(→‎{{header|Tcl}}: ++ smalltalk)
Line 382:
arr[1][3] = 5
p arr[1][3]</lang>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
Smalltalk has no problems in creating objects at runtime. I haven't found a class for multidimensional array in the standard library, so let us suppose to have a class named MultidimensionalArray.
 
<lang smalltalk>|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
]
].</lang>
 
A possible implementation for a '''Bi'''dimensionalArray class is the following (changing ''Multi'' into ''Bi'' and using this class, the previous code runs fine):
 
<lang smalltalk>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
]
].</lang>
 
Instead of implementing such a class (or the MultidimensionalArray one), we can use a LookupTable class, using Array objects as keys (each element of the array will be an index for a specific ''dimension'' of the "array"). The final effect is the same as using an array (almost in the ''AWK sense'') and the approach has some advantages.
 
<lang smalltalk>|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.
]
].</lang>
 
 
 
=={{header|Tcl}}==