Loop Fusion in Go: Optimizing Array Processing
Many programming tasks involve iterating over arrays or slices to perform a series of operations. When these operations are independent and can be applied to each element sequentially, combining multiple loops into a single loop (loop fusion) can significantly improve performance by reducing loop overhead and improving cache locality. This challenge will test your understanding of how to identify and implement loop fusion in Go.
Problem Description
Your task is to implement a function in Go that takes a slice of integers and performs two sequential operations on it:
- Doubling: Each element in the slice should be doubled.
- Adding Five: Five should be added to each element after it has been doubled.
You need to implement this using a single loop to achieve loop fusion. The original slice should be modified in-place.
Key Requirements:
- The function must accept a
[]intas input. - The function must modify the input slice in-place.
- The operations (doubling and adding five) must be performed within a single loop iteration for each element.
- The order of operations for each element is critical: first double, then add five.
Expected Behavior:
For an input slice [1, 2, 3]:
- Element
1becomes(1 * 2) + 5 = 7 - Element
2becomes(2 * 2) + 5 = 9 - Element
3becomes(3 * 2) + 5 = 11The resulting slice should be[7, 9, 11].
Edge Cases:
- An empty slice should be handled gracefully (no operations performed).
- A slice with a single element.
Examples
Example 1:
Input: []int{1, 2, 3}
Output: []int{7, 9, 11}
Explanation: Each element is doubled and then 5 is added.
Example 2:
Input: []int{0, -1, 10}
Output: []int{5, 3, 25}
Explanation:
0 becomes (0 * 2) + 5 = 5
-1 becomes (-1 * 2) + 5 = 3
10 becomes (10 * 2) + 5 = 25
Example 3:
Input: []int{}
Output: []int{}
Explanation: An empty slice remains empty.
Constraints
- The input slice will contain only integer values.
- The size of the slice can range from 0 to 10,000 elements.
- The absolute value of any integer in the slice will not exceed 1,000.
- The solution should aim for O(n) time complexity, where n is the number of elements in the slice.
Notes
Consider how you would approach this problem without loop fusion (i.e., two separate loops). Then, think about how combining these two sequential operations into one loop can be more efficient. This is a common optimization technique in performance-critical code. Pay close attention to the order of operations as specified.