// Returns an array that has every element in arr mulitplied by two public int[] timesTwo(int[] arr) { int[] result = new int[arr.length]; for (int i = 0; i < arr.length; i++) { result[i] = arr[i] * 2; } } // Returns an array that has every element in arr plus one public int[] plusOne(int[] arr) { int[] result = new int[arr.length]; for (int i = 0; i < arr.length; i++) { result[i] = arr[i] + 1; } } // In pseduo code, we could imagine factoring out this redundancy by thinking about these in terms of maps // where you pass in the array to process and the thing you want to perform on each element public int[] timesTwo(int[] arr) { map(arr, *2); // multiple each element by two } public int[] plusOne(int[] arr) { map(arr, +1); // add one to every element } /* Why is it helpful to think about code in terms of maps? * * One possible answer: Easier to reason about code at a higher level and can get parallelism for free! * * What are examples of some other maps? What is an example of an algorithm that is not a map? * * map(arr, is even) * mapp(arr, divide by 5); * * An example of something that can't be a map is sorting an array, it requires swapping things around and * global knowledge of the array; you would be hard pressed to write a function that took an element and * returned the right element for that spot. */ // Reductions are the same idea but they take an array and collapse it down to one value public int findMax(int[] arr) { int max = -Integer.MIN_VALUE; for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { maxx = arr[i]; } } return max; } // In pseudocode could be written something like this reduce(arr, MAX); // collapse the array down the the max value /* What are examples of some other reductions you can perform on an array? * * Some possible answers: Min, average, all odd, leftmost even * * * What is an example of something that can't be written as a reduction. * * One possible answer is median. */