Dart-通过更改变量向列表中添加常量值
我无法将列表添加到列表中。 添加到列表“pusta”的位置在我更改变量“row”时不会保持不变。结果应该是这样的:[[0,1,2],[1,2,3],[2,3,4]]。我得到[[2,3,4],[2,3,4],[2,3,4]。我用省道板写字。 我试图在添加到列表时将行更改为字符串,但对Codewars的测试并没有将其作为解决方案Dart-通过更改变量向列表中添加常量值,dart,Dart,我无法将列表添加到列表中。 添加到列表“pusta”的位置在我更改变量“row”时不会保持不变。结果应该是这样的:[[0,1,2],[1,2,3],[2,3,4]]。我得到[[2,3,4],[2,3,4],[2,3,4]。我用省道板写字。 我试图在添加到列表时将行更改为字符串,但对Codewars的测试并没有将其作为解决方案 logisticMap(width, height, xs, ys) { manhDist(width, height,xs,ys, pozx, pozy){
logisticMap(width, height, xs, ys) {
manhDist(width, height,xs,ys, pozx, pozy){
int x =0;
List<int> lista =[];
int i=0;
while(x<xs.length) {
num wart = (xs[x]-pozx).abs() + (ys[x]-pozy).abs();
lista.add(wart);
x++;
}
int minimum = lista[0];
while (i<lista.length) {
(lista[i]<minimum) ? minimum=lista[i] : minimum;
i++;
}
return minimum;
}
int i=0;
int j=0;
List<int> row =[];
List<List> pusta=[];
if (xs.isNotEmpty) {
while (i<height) {
row.clear();
while (j<width) {
row.add(manhDist(width, height, xs,ys,j,i));
j++;
}
j=0;
pusta.add(row);
i++;
}
return pusta;
} else {
while (j < height) {
row.clear();
while (i < width) {
row.add(null);
i++;
}
i = 0;
pusta.add(row);
j++;
}
return pusta;
}
}
void main() {
logisticMap(3, 3, [0], [0]);
}
logisticMap(宽度、高度、xs、ys){
人孔区(宽度、高度、xs、ys、pozx、pozy){
int x=0;
列表lista=[];
int i=0;
while(x)正确格式化代码会使代码更容易理解。我假设您正在重用一个列表实例,而不是创建一个新列表,这就是为什么修改一个列表也会修改其他列表,而“其他”只是对同一列表的其他引用。您的意思是将row.clear()替换为list row=[]?我已经这样做了。效果是一样的。很抱歉格式化不好。诸如此类。你在这两个地方都做了更改吗?我没有尝试理解你的代码到底做了什么。是的,现在我觉得很愚蠢。它工作了。它返回了一个从最近的供应点到曼哈顿距离的2D列表(矩阵?)。谢谢你的帮助。
List<List<int>> logisticMap(width,height,xs,ys) {
List<List<int>> result = [];
for (int i = 0; i < height; ++i) {
List<int> rowResult = [];
for (int j = 0; j < width; ++j) {
rowResult.add(closestSupplyPoint(xs, ys, j, i));
}
result.add(rowResult);
}
return result;
}
int closestSupplyPoint(xs, ys, x, y) {
int minDistance = null;
for (int i = 0; i < xs.length; ++i) {
int distance = (xs[i] - x).abs() + (ys[i] - y).abs();
if (minDistance == null || distance < minDistance) {
minDistance = distance;
}
}
return minDistance;
}