I have a function that looks a lot cleaner this way:
public static List<Integer> permuteDigits(int number) {
List<Integer> permutations = new ArrayList<>();
for (String s : permutations(String.valueOf(number)))
permutations.add(Integer.parseInt(s));
return permutations;
}
But you can see, there's a function call inside the for-each loop. I'm pretty sure that the compiler doesn't do this, but... the function isn't called on each iteration of the for loop, is it?
I'm almost positive this isn't the case, but I just wanted to make sure. That is to say, the above code is no less efficient than the following:
public static List<Integer> permuteDigits(int number) {
List<String> strPerms = permutations(String.valueOf(number));
List<Integer> permutations = new ArrayList<>();
for (String s : strPerms)
permutations.add(Integer.parseInt(s));
return permutations;
}
Correct?
In your first code block, permutations(String.valueOf(number)) will be called once, return its result, and then the for loop will iterate through the elements in the result. Like in the example below:
static List<Integer> createNumbers() {
System.out.println("createNumbers");
return Arrays.asList(0, 1, 2);
}
public static void main(String[] args) {
for (Integer num : createNumbers()) {
System.out.println(num);
}
}
The result shows that createNumbers() was called only once:
createNumbers
0
1
2
Yes, that is correct. Condition in the for-each loop is evaluated only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With