Reputation: 1807
I have the following different types
Types:
R -> R1, R2, R3....
RE -> RE1, RE2, RE3....
REA -> REA1, REA2, REA3...
They have the following relationship.
For a given list of items i want to iterate over each leaf and perform some actions. Right now, i have a for loop nested three levels.
for (r in Rs) {
List<RE> REs = get(R);
for(re in REs) {
List<REA> REAs = get(re);
for(rea in REAs) {
//do some processing for the list of items
for(each item in items) {
//process each item
}
}
}
}
is there a better approach to this iterative one?
Upvotes: 0
Views: 91
Reputation: 29936
Not sure which language do you use, but you could shorten that snippet by not storing all the lists in locals:
for (r in Rs) {
for (re in get(r)) {
for (rea in get(re)) {
for (item in rea) {
//process each item
}
}
}
}
Or you can go recursive:
traverse(items) {
if (items.isLeaf()) {
// process items
} else {
for (item in items) {
traverse(item);
}
}
}
traverse(Rs)
Upvotes: 1