Difference between revisions of "Pack"
Line 21: | Line 21: | ||
|} | |} | ||
Notice how each position that that was flagged now has a distinct number assigned to it in the prefix sum array. We can use this to help us index the output array. | Notice how each position that that was flagged now has a distinct number assigned to it in the prefix sum array. We can use this to help us index the output array. | ||
+ | |||
+ | =Code To Investigate= | ||
+ | |||
+ | {{CodeToInvestigate|ParallelPack|createArray|pack.studio}} | ||
+ | <pre> private static <T> T[] createArray(Class<T[]> arrayType, int length) { | ||
+ | return arrayType.cast(Array.newInstance(arrayType.getComponentType(), length)); | ||
+ | }</pre> | ||
=Code To Implement= | =Code To Implement= |
Revision as of 20:26, 2 April 2019
Contents
Motivation
One of the applications for scan is pack operation. Given an input array, the operation produces an output array containing only the elements that satisfy some specified predicate.
The problem with parallelizing pack is that although it is easy to determine whether an element should be filtered out into the output, we can't know where to put the element in the output array. It seems that placing an element into the output requires knowledge of the placement of the previous elements. This is where prefix sum becomes very useful.
Think about quick sort. In the partition step, we are given a pivot and need to separate the array by the predicate of whether an element is larger than the pivot. This is the perfect place to use the pack operation. You are going to build a more general pack filter in this studio, but you can still attempt the parallel partitioner challenge here: Quicksort Parallel Partitioner.
Background
For example, if you have an integer array input:
2 | 6 | 1 | 3 | 7 | 9 | 4 |
You want to filter out all elements that are less than five. You can first create a flag array in which all the positions i where input[i] is less than 5 is flagged as "1" and all other positions are marked as "0".
1 | 0 | 1 | 1 | 0 | 0 | 1 |
The prefix sum of this flag array is:
1 | 1 | 2 | 3 | 3 | 3 | 4 |
Notice how each position that that was flagged now has a distinct number assigned to it in the prefix sum array. We can use this to help us index the output array.
Code To Investigate
class: | ParallelPack.java | DEMO: |
methods: | createArray | |
package: | pack.studio | |
source folder: | src//java |
private static <T> T[] createArray(Class<T[]> arrayType, int length) { return arrayType.cast(Array.newInstance(arrayType.getComponentType(), length)); }
Code To Implement
Parallel Pack
class: | ParallelPack.java | |
methods: | pack | |
package: | pack.studio | |
source folder: | student/src/main/java |
method: public static <T> T[] pack(Class<T[]> arrayType, T[] arr, Predicate<T> predicate)
(parallel implementation required)
Testing Your Solution
class: | PackTestSuite.java | |
package: | pack.studio | |
source folder: | testing/src/test/java |