Reputation:
I've been trying to simplify the following by putting it into a loop..
int A0 = 0, A1 = 0, A2 = 0;
for (A0 = 0; A0 < nums.Length; A0++)
{
for (A1 = 0; A1 < nums.Length; A1++)
{
for (A2 = 0; A2 < nums.Length; A2++)
{
string ss = nums[A0] + nums[A1] + nums[A2];
dataGridView1.Rows.Add(new string[] { ss });
}
}
}
like A0, A1 and A2, i need to go until A75. I can get the result if i nest like the above. But how can i put it on a loop..??
I tried this one:
int[] A = new int[3];
for (int i = 0; i < A.Length; i++)
{
for (A[i] = 0; A[i] < nums.Length; A[i]++)
{
string ss = "";
for (int j = 0; j < A.Length; j++) ss += nums[A[i]];
dataGridView1.Rows.Add(new string[] { ss });
}
}
But it will perform only like..
int A0 = 0, A1 = 0, A2 = 0;
for (A0 = 0; A0 < nums.Length; A0++)
{
string ss = nums[A0] + nums[A1] + nums[A2];
dataGridView1.Rows.Add(new string[] { ss });
}
for (A1 = 0; A1 < nums.Length; A1++)
{
string ss = nums[A0] + nums[A1] + nums[A2];
dataGridView1.Rows.Add(new string[] { ss });
}
for (A2 = 0; A2 < nums.Length; A2++)
{
string ss = nums[A0] + nums[A1] + nums[A2];
dataGridView1.Rows.Add(new string[] { ss });
}
Upvotes: 3
Views: 200
Reputation: 6975
An equivalent to
public void DoNestedThings()
{
for(var A0 = 0; A0 < _max; A0 ++)
{
//...
for(var i5 = 0; i5 < _max; i5++)
{
DoThing(new List<int>{i0, ..., i5});
}
}
}
Would be:
private void DoNestedThings(int depth, Stack<int> indexes)
{
if(depth == 0)
{
DoThing(indexes);
return;
}
for(var i = 0; i < _max; i++)
{
indexes.Push(i);
DoNestedThings(depth-1, indexes);
indexes.Pop();
}
}
public void DoNestedThings()
{
DoNestedThings(5, new Stack<int>());
}
This replaces nested loops with a single loop, but then uses recursion to enter into that loop multiple times. Each time the DoNestedThings
method is called with depth
> 0, you enter into another loop.
(Note the order of the indexes passed to DoThing
will be reversed)
Upvotes: 2
Reputation: 203821
See Computing a Cartesian Product with LINQ for how to write a method that can compute the Cartesian Product of a number of collections not known at compile time, which is exactly the problem you're trying to solve.
You can then create the collection of collections dynamically by simply using Repeat
:
var query = Enumerable.Repeat(nums, 75)
.CartesianProduct()
.Select(combination => combination.Sum());
Of course, the size of such a query is going to be pretty large. This approach is going to leverage deferred execution to allow you to compute each result as you go, rather than computing every single result before giving you any, but if you actually try to compute a significant percentage of the values (or all of them) you're going to be waiting for...a long time.
Upvotes: 1