Created
March 3, 2016 15:58
-
-
Save Fireforge/e1d3500e3dbb98e25ef9 to your computer and use it in GitHub Desktop.
Simple IEnumerable functions to find continuous sections
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Finds sections of the given IEnumerable<bool> that are continuously true | |
/// </summary> | |
/// <param name="src">Any IEnumerable<bool></param> | |
/// <returns>An IEnumerable<Tuple<int, int> where each pair represents the start and end index that is continuously true</returns> | |
private IEnumerable<Tuple<int, int>> FindContinuousTrue(IEnumerable<bool> src) | |
{ | |
var res = new Collection<Tuple<int, int>>(); | |
var srclist = src.ToList(); | |
// Bool edge detection algorithm | |
bool pairclosed = true; | |
int risingedgeidx = 0; | |
for (int i = 1; i < srclist.Count; i++) | |
{ | |
if (!srclist[i - 1] && srclist[i]) // rising edge False -> True | |
{ | |
risingedgeidx = i; | |
pairclosed = false; | |
} | |
else if (srclist[i - 1] && !srclist[i]) // falling edge True -> False | |
{ | |
res.Add(new Tuple<int, int>(risingedgeidx, i - 1)); | |
pairclosed = true; | |
} | |
} | |
if (!pairclosed) | |
{ | |
res.Add(new Tuple<int, int>(risingedgeidx, srclist.Count - 1)); | |
} | |
// Special case: If no edges can be found and the first element is true, all elements must be true | |
if (res.Count() == 0 && srclist[0] == true) | |
{ | |
res.Add(new Tuple<int, int>(0, srclist.Count - 1)); | |
} | |
return res; | |
} | |
/// <summary> | |
/// Finds sections of the given IEnumerable<int> that are continuous in value | |
/// </summary> | |
/// <param name="src">Any IEnumerable<int></param> | |
/// <returns>An IEnumerable<Tuple<int, int> where each pair represents the start and end index that is continuous</returns> | |
private IEnumerable<Tuple<int, int>> FindContinuous(IEnumerable<int> src) | |
{ | |
var res = new Collection<Tuple<int, int>>(); | |
var srclist = src.ToList(); | |
// edge detection algorithm | |
int lastedgeidx = 0; | |
for (int i = 1; i < srclist.Count; i++) | |
{ | |
if (srclist[i - 1] != srclist[i]) // edge | |
{ | |
res.Add(new Tuple<int, int>(lastedgeidx, i - 1)); | |
lastedgeidx = i; | |
} | |
} | |
res.Add(new Tuple<int, int>(lastedgeidx, srclist.Count - 1)); | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment