みんな、私はこれを試しました:
List<num> test
for(num i = ...){
test[i]...
(...)
for(num j = ...){
test[i][j] = ...
}
}
今日はうまくいかなかったようです。私の質問は...ダートでこれを作る方法はありますか?:)
みんな、私はこれを試しました:
List<num> test
for(num i = ...){
test[i]...
(...)
for(num j = ...){
test[i][j] = ...
}
}
今日はうまくいかなかったようです。私の質問は...ダートでこれを作る方法はありますか?:)
これを行う1つの方法は次のとおりです。
main() {
List<List<int>> matrix = new List<List<int>>();
for (var i = 0; i < 10; i++) {
List<int> list = new List<int>();
for (var j = 0; j < 10; j++) {
list.add(j);
}
matrix.add(list);
}
print(matrix);
print(matrix[2][4]);
}
事前に長さがわかっていて、それが変更されない場合は、長さをコンストラクターに渡すことができます。
main() {
int size = 10;
List<List<int>> matrix = new List<List<int>>(size);
for (var i = 0; i < size; i++) {
List<int> list = new List<int>(size);
for (var j = 0; j < size; j++) {
list[j] = j;
}
matrix[i] = list;
}
print(matrix);
print(matrix[2][4]);
}
主な違いに注意してください。最初の例では、リストは空で作成されるため、ループはリストに要素を明示的に追加する必要があります。2番目の例では、リストは固定サイズで作成され、各インデックスにnull要素があります。
変更ログ:2番目の例の元のバージョンでは、Dart1.0List.fixedLength(size)
より前に存在していたコンストラクターを使用していました。
各位置で異なる値を持つリストを作成する1つの方法は、イディオムを使用することです。
new Iterable.generate(size, function).toList()
makeMatrix(rows, cols) =>
new Iterable<List<num>>.generate(
rows,
(i) => new List<num>.fixedLength(cols, fill: 0)
).toList();
main() {
print(makeMatrix(3, 5));
}
プリント: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
fill:
パラメータを取得するために固定長のリストを作成する必要があるのは少し面倒です。塗りつぶしの値がない場合、内部リストにはnull
sが含まれます。初期値を持つ拡張可能なリストを取得する1つの方法は、空のリストを作成して拡張することです。
(i) => <num>[]..insertRange(0, cols, 0)
This is using a method cascade to modify the list before returning it - a..b()..c()
calls a.b()
and a.c()
before returning a
. This is handy as it avoids the need for a temporary variable.
Note that, for some reason, insertRange
has a positional rather than a named fill
parameter.
If you want more control over the contents, you can extend the generate-to-list idea to two levels:
makeMatrix(rows, cols, function) =>
new Iterable<List<num>>.generate(
rows,
(i) => new Iterable<num>.generate(cols, (j) => function(i, j)).toList()
).toList();
main() {
print(makeMatrix(3,5, (i, j) => i == j ? 1 : 0));
}
prints: [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0]]
行列を処理するための優れたライブラリがパブにいくつかあります(たとえば、Kevin MooreのBOTなど)が、何かをすばやく探している場合は、次のことを実行できます。
List<List> test = new List<List>(n);
for (var i = 0; i < n; i++) {
test[i] = new List(n);
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
test[i][j] = myValue;
}
}