I have a List<object>
which can contain either an integer value or another List<object>
.
What I need to do, is to sum the values in the array, depending on its depth(If depth is 0, multiply by 0, if 1 then by 1 ... etc.)
Example array: [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
How it should be calculated: 5 2 2 * (7 - 1) 3 2 * (6 3 * (-13 8) 4) = 12
What I managed to get:
public class Program
{
public static List<object> TestCase1()
{
List<object> test = new List<object>(){
5,
2,
new List<object>(){
7, -1
},
3,
new List<object>(){
6,
new List<object>(){
-13, 8
},
4,
},
};
return test;
}
public static int ProductSum(List<object> array)
{
int depthCounter = 1;
int totalSum = 0;
int tempSum = 0;
for (int i = 0; i < array.Count; i )
{
if (array[i] is IList<object>)
{
totalSum = tempSum * depthCounter;
tempSum = 0;
depthCounter ;
}
else
{
tempSum = (int)array[i];
}
}
return totalSum;
}
static void Main(string[] args)
{
Console.WriteLine("Result = " ProductSum(TestCase1()));
}
}
The result from my code is
The problem that I have, is I don't see a way, that I could iterate through an array to calculate it ... Maybe there is a way to sort an array of objects in some way to simplify it?
CodePudding user response:
The method should call itself ("recursive"), when it encounters a nested list. It should also take a depth
parameter, keeping track of the depth. Every time you call the function recursively, you pass depth 1
as the new depth. Whenever you count something, you multiply by depth
.
public static int ProductSum(List<object> list) => ProductSum(list, 1);
public static int ProductSum(List<object> list, int depth)
{
var sum = 0;
foreach (var thing in list) {
if (thing is List<object> innerList) {
sum = ProductSum(innerList, depth 1) * depth;
} else if (thing is int x) {
sum = x * depth;
}
}
return sum;
}
CodePudding user response:
You should do it recusively:
public static int ProductSum(List<object> array, int depthCounter)
{
int totalSum = 0;
for (int i = 0; i < array.Count; i )
{
if (array[i] is List<object>)
{
totalSum = ProductSum(array[i] as List<Object>, depthCounter 1);
}
else
{
totalSum = (int)array[i] * depthCounter;
}
}
return totalSum;
}
You call it this way:
ProductSum(TestCase1(), 0);
But I don't get the number you calculated, though: If all depth 0 candidates are multiplied by 0, these are... 0! ;) Maybe there are some rules for your application that I don't know, and that's the reason why the calculations differ, but in the code you see how recursions work.