Sunday, August 22, 2021

Product sum using recursion.

Here we apply recursion because our array contains another array .so the process of addition is same as the outer array .

public class MainApp {

public static void main(String[] args) {

List<Object> a1 = new ArrayList<Object>();

a1.add(1);

a1.add(2);

a1.add(3);

a1.add(4);


List<Object> a2 = new ArrayList<Object>();

a2.add(5);

a2.add(6);

a2.add(7);

List<Object> arrays = new ArrayList<Object>();

arrays.addAll(a1);

arrays.add(a2);

arrays.add(8);

arrays.add(9);

int result = productSum(arrays, 1);

System.out.println(result);

}

public static int productSum(List<Object> inputs, int depth) {


int sum = 0;

for (Object obj : inputs) {

if (obj instanceof List) {

sum += productSum((List<Object>) obj, depth + 1);

} else {

sum += (int) obj;

}

}

return sum * depth;

}

}


No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...