有一个二进制值列表:
List<bool> myList = new List<bool>(){true, true, false, false, true, false, false, false, true, true, true, false, false};
Run Code Online (Sandbox Code Playgroud)
我的算法旨在将任何false项转换为true,如果它们与真值相邻:
result = {true, true, true, true, true, true, false, true, true, true, true, true, false}
Run Code Online (Sandbox Code Playgroud)
正如您将看到的,我的解决方案有效.我可以通过两个不同的循环来完成它,然后压缩两个列表:
List<bool> firstList = new List<bool>();
List<bool> secondList = new List<bool>();
for(int i=0; i<myList.Count()-1; i++){
if(myList[i]==true){
firstList[i]=true;
firstList[i+1]=true;
}
}
for(int i=1; i<myList.Count(); i++){
if(myList[i]==true){
secondList[i]=true;
secondList[i-1]=true;
}
}
List<bool> finalList = firstList.Zip(secondList, (a,b)=>a||b).ToList();
Run Code Online (Sandbox Code Playgroud)
但是,它似乎不是最佳解决方案,因为问题看起来很容易.有没有想过通过一个循环或最好使用linq?
你可以在一个循环中完成它:
List<bool> result = myList.Select((b, index) =>
b ||
(index > 0 && myList[index-1]) ||
(index < (myList.Count - 1) && myList[index+1])).ToList();
Run Code Online (Sandbox Code Playgroud)
如果这个本身或者是调整值,那么这会占用b你的每一个myList并检查(通过index)true.当然,我们必须检查index列表边界.
这是Linq方法
基本上它与你的方法具有相同的行为 - 元素self x,前一个.ElementAtOrDefault(i - 1)或下一个.ElementAtOrDefault(i + 1)元素必须是真的.
List<bool> result = myList.Select((x, i) => x || myList.ElementAtOrDefault(i - 1) || myList.ElementAtOrDefault(i + 1)).ToList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
124 次 |
| 最近记录: |