Smalltalk 如何用随机数填充二维数组?
Smalltalk How to Fill 2d array with random numbers?
在 java 中,或者使用两个嵌套的 for 循环可以用 C# 填充二维数组,但是在 smalltalk 中我似乎找不到做同样事情的方法。
谁能帮帮我?
您可以使用 Matrix
并将其创建为:
| random |
random := Random new.
^ Matrix
rows: rowNumber
columns: columnNumber
tabulate: [ :i :j | random next ]
其中 i 和 j 是元素的索引(我没有在示例中使用)
如果你真的想用二维数组做一些事情,我建议你做这样的事情:
| random |
random := Random new.
^ (1 to: rowNumber) collect: [ :i |
(1 to: columnNumber) collect: [ :j |
random next ]
也可以在创建后遍历一个矩阵:
| random matrix |
random := Random new.
matrix := Matrix rows: rowNumber columns: columnNumber.
martix indicesCollect: [ :i :j | random next ].
^ matrix
在 java 中,或者使用两个嵌套的 for 循环可以用 C# 填充二维数组,但是在 smalltalk 中我似乎找不到做同样事情的方法。 谁能帮帮我?
您可以使用 Matrix
并将其创建为:
| random |
random := Random new.
^ Matrix
rows: rowNumber
columns: columnNumber
tabulate: [ :i :j | random next ]
其中 i 和 j 是元素的索引(我没有在示例中使用)
如果你真的想用二维数组做一些事情,我建议你做这样的事情:
| random |
random := Random new.
^ (1 to: rowNumber) collect: [ :i |
(1 to: columnNumber) collect: [ :j |
random next ]
也可以在创建后遍历一个矩阵:
| random matrix |
random := Random new.
matrix := Matrix rows: rowNumber columns: columnNumber.
martix indicesCollect: [ :i :j | random next ].
^ matrix