Sponsored
Sponsored
This approach involves manually iterating over each element of the array using a for loop. For each element, we apply the provided function fn with the current element and its index as arguments. The result is then pushed into a new result array, which is returned at the end.
Time Complexity: O(n), where n is the number of elements in the array.
Space Complexity: O(n) for the resultant array.
1#include <vector>
std::vector<int> transformArray(const std::vector<int>& arr, int(*fn)(int, int)) {
std::vector<int> result;
for (size_t i = 0; i < arr.size(); ++i) {
result.push_back(fn(arr[i], static_cast<int>(i)));
}
return result;
}
int plusOne(int n, int i) {
return n + 1;
}
int main() {
std::vector<int> arr = {1, 2, 3};
std::vector<int> result = transformArray(arr, plusOne);
for (int val : result) {
std::cout << val << ' ';
}
return 0;
}In the C++ implementation, the transformArray function takes a std::vector and a function pointer. It iterates over the vector, applying the function, and returns a result vector with transformed elements.
Another approach is to use recursion to apply the function to each element in the array. We define a recursive function that processes elements by moving from the start to the end of the array, applying transformations and constructing the result array.
Time Complexity: O(n)
Space Complexity: O(n) for result array and O(n) for function call stack.
1#include <stdio.h>
2#include <stdlib.h>
3
4void transformArrayRecursive(int* arr, int* result, int index, int size, int (*fn)(int, int)) {
5 if (index >= size) return;
6 result[index] = fn(arr[index], index);
7 transformArrayRecursive(arr, result, index + 1, size, fn);
8}
9
10int plusOne(int n, int i) {
11 return n + 1;
12}
13
14int main() {
15 int arr[] = {1, 2, 3};
16 int arrSize = sizeof(arr) / sizeof(arr[0]);
17 int* result = (int*)malloc(arrSize * sizeof(int));
18 transformArrayRecursive(arr, result, 0, arrSize, plusOne);
19 for(int i = 0; i < arrSize; i++) {
20 printf("%d ", result[i]);
21 }
22 free(result);
23 return 0;
24}In the recursive C solution, a helper function transformArrayRecursive is created. It recursively calls itself to apply the function to each element, building up the result array.