input Data
1 -> [2]
2 -> [3, 5, 7, 9]
3 -> [4]
4 -> [5]
5 -> [6]
6 -> [7, 9]
7 -> [8]
8 -> [9]
tree child
how can i get output like below using data above a few for loop checks but i couldn't. I want something like combination but infinite
Out data
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,9
1,2,5,6,7,8,9
1,2,5,6,9
1,2,7,8,9
1,2,9
CodePudding user response:
Assuming your input tree isn't too large, you could use recursion to achieve what you want to do.
Let's say your input data is populated in a Dictionary
, as follows:
var input = new Dictionary<int, int[]>
{
[1] = new[] { 2 },
[2] = new[] { 3, 5, 7, 9 },
[3] = new[] { 4 },
[4] = new[] { 5 },
[5] = new[] { 6 },
[6] = new[] { 7, 9 },
[7] = new[] { 8 },
[8] = new[] { 9 }
};
var output = input.GetPossibleRanges();
You could then "build" all possible tree branches recursively, using extension methods such as:
public static IEnumerable<List<int>> GetPossibleRanges(this Dictionary<int, int[]> dict)
{
var ranges = new List<int> { dict.Keys.Min() }.BuildRanges(dict);
return ranges;
}
public static IEnumerable<List<int>> BuildRanges(this List<int> range, Dictionary<int, int[]> dict)
{
if (dict.TryGetValue(range.Last(), out int[] nextLevel))
{
foreach (var child in nextLevel)
{
foreach (var grownRange in range.Append(child).ToList().BuildRanges(dict))
{
yield return grownRange;
}
}
}
else
{
yield return range;
}
}
Given the provided input, the resulting output is then:
foreach (var entry in output)
{
Console.WriteLine(string.Join(",", entry));
}
1,2,3,4,5,6,7,8,9
1,2,3,4,5,6,9
1,2,5,6,7,8,9
1,2,5,6,9
1,2,7,8,9
1,2,9
CodePudding user response:
public static IEnumerable<List> GetPossibleRanges(this Dictionary<int, int[]> dict) { var ranges = new List { dict.Keys.Min() }.BuildRanges(dict);
return ranges;
}
public static IEnumerable<List<int>> BuildRanges(this List<int> range, Dictionary<int, int[]> dict) {
if (dict.TryGetValue(range.Last(), out int[] nextLevel)) {
foreach (var child in nextLevel) {
range.Add(child);
foreach (var grownRange in range.ToList().BuildRanges(dict)) {
yield return grownRange;
}
}
} else {
yield return range;
}
}
1,2,3,4,5,6,7,8,9 1,2,3,4,5,6,7,9 1,2,3,5,6,7,8,9 1,2,3,5,6,7,9 1,2,3,5,7,8,9 1,2,3,5,7,9
range.Append(child).ToList().BuildRanges(dict)
Append Error