c# - 使用 List.InsertRange() 或 List.Insert() 似乎正在编辑它从中插入的列表
问题描述
我正在尝试将 2D 列表插入另一个 2D 列表,该列表从 x,y 指定的点开始。
前任:
List A = {{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1}}
List B = {{2,2,2,2},
{2,2,2,2},
{2,2,2,2},
{2,2,2,2}}
MergeLists(A, B, 0, 0) would give:
{{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1}}
MergeLists(A, B, 2, 0) would give:
{{1,1,2,2,2,2,1,1},
{1,1,2,2,2,2,1,1},
{1,1,2,2,2,2,1,1},
{1,1,2,2,2,2,1,1}}
*My code adds an additional 0 at the end of each line but I'm not worried about that.
MergeLists(A, B, 5, 0) would give:
{{1,1,1,0,2,2,2,2},
{1,1,1,0,2,2,2,2},
{1,1,1,0,2,2,2,2},
{1,1,1,0,2,2,2,2}}
MergeLists(A, B, 0, 1) would give:
{{1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2}}
MergeLists(A, B, 0, 5) would give:
{{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{1,1,1,1},
{0},
{2,2,2,2},
{2,2,2,2},
{2,2,2,2},
{2,2,2,2}}
我的代码适用于 x 方向,但在 y>0 时会中断。相反,它似乎将它合并的最后一个列表添加到它将要合并的下一个列表的开头。
MergeLists(A, B, 0, 1) erroneously gives:
{{1,1,1,1},
{2,2,2,2,1,1,1,1},
{2,2,2,2,1,1,1,1,1,1,1,1},
{2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1},
{2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1}}
这是我的代码:
public class StrTester{
private List<List<int>> grid;
// Start is called before the first frame update
void Start(){
grid = new List<List<int>>();
List<List<int>> newGrid = new List<List<int>>();
List<int> ints = new List<int>();
for(int i=1; i<21; i++){
ints.Add(i);
if(i%4 == 0){
newGrid.Add(ints);
ints = new List<int>();
}
}
MergeLists(newGrid, 0, 0);
Print(newGrid);
MergeLists(newGrid, 0, 1);
Print(grid);
}
private void MergeLists(List<List<int>> newInts, int x, int y){
if(grid.Count == 0){
grid = new List<List<int>>(newInts);
} else {
while(y + newInts.Count >= grid.Count){
grid.Add(new List<int>());
}
foreach(List<int> ints in grid){
while(ints.Count < x){
ints.Add(0);
}
}
foreach(List<int> newIntRow in newInts){
Print(newIntRow);
grid[y].InsertRange(x, new List<int>(newIntRow));
Print(newIntRow);
y++;
Print(newIntRow);
}
}
}
private void Print(List<List<int>> printGrid){
string str = "";
foreach(List<int> lInt in printGrid){
foreach(int i in lInt){
str += i + ", ";
}
Debug.Log(str);
str = "";
}
}
private void Print(List<int> printList){
string str = "";
foreach(int i in printList){
str += i + ", ";
}
Debug.Log("this line is: " + str);
}
}
请注意,这是为了在统一引擎中使用而编写的,因此如果您在控制台上进行测试,您需要将“Start”方法更改为“Main”,并将 Print 方法中的“Debug.Log”更改为。
解决方案
推荐阅读
- awesome-wm - 当增加分辨率时,所有 GUI 文本和按钮等都会变大
- react-native - 在后台 React Native ble 广告商
- python - 如何让 Python 查询器在 Pycharm 中工作?
- python - 如何迭代地对numpy数组中的数值数据进行分类?
- laravel - 基于数据库字段使用两种不同的 orderBy 逻辑(null/not null)
- shell - youtube-dl 可以在下载播放列表时忽略特定视频吗?
- php - 在 WooCommerce 和 WPML 中隐藏特定运输类别的运输方式
- angular - 如何正确使用 RxJS 为返回到 Observable 的数组的每个对象添加一个新字段?
- c# - 为什么我的光线投射会击中错误的对象?
- spring - 使用 JPA 查询时未显示响应正文