Infection \ passing value to neighboring list items in C #

There is a list of binary values:

List<bool> myList = new List<bool>(){true, true, false, false, true, false, false, false, true, true, true, false, false}; 

my algorithm aims to convert any false element to true if they are adjacent to the true value:

 result = {true, true, true, true, true, true, false, true, true, true, true, true, false} 

My solution works as you will see. I can do this through two different loops, and then pin two lists:

 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(); 

However, this does not seem to be the best solution, since the problem looks very simple. Any idea to do this in one loop or preferably using linq?

+5
source share
3 answers

Here is the Linq approach

Basically, it has the same behavior as your approach - the self x element, the previous .ElementAtOrDefault(i - 1) element or the next .ElementAtOrDefault(i + 1) element should be true.

 List<bool> result = myList.Select((x, i) => x || myList.ElementAtOrDefault(i - 1) || myList.ElementAtOrDefault(i + 1)).ToList(); 
+6
source

You can do this in one loop:

 List<bool> result = myList.Select((b, index) => b || (index > 0 && myList[index-1]) || (index < (myList.Count - 1) && myList[index+1])).ToList(); 

It takes every b in your myList and checks (via index ) if it is itself or the adjacent true values. Of course, we have to check the index for the list bounds.

+6
source

I do not think this is particularly readable, but:

 var indexesToChange = Enumerable.Range(0, myList.Count) .Where(n => myList[n] || (n-1 >= 0 && myList[n-1]) || (n+1 < myList.Count && myList[n+1])) .ToList(); foreach (var i in indexesToChange) { myList[i] = true; } 

This will update the old list. You can copy to the new list in the foreach if you do not want to change the old one.

+1
source

Source: https://habr.com/ru/post/1274065/


All Articles