Last active
August 29, 2015 14:27
-
-
Save ophers/9f1c483f46a874521559 to your computer and use it in GitHub Desktop.
[Java Lambda MOOC] Lesson 3 solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static int[][] computeLevenshtein(List<String> wordList, boolean parallel, int method) { | |
final int LIST_SIZE = wordList.size(); | |
int[][] distances = new int[LIST_SIZE][LIST_SIZE]; | |
// For use with method 3 | |
class IntTrio { | |
int row, col, val; | |
public IntTrio(int row, int col, int val) { | |
this.row = row; | |
this.col = col; | |
this.val = val; | |
} | |
} | |
// Accumulator | |
class DoubleIntArray { | |
final int[][] arr; | |
final AtomicInteger ai; | |
DoubleIntArray(int[][] arr) { | |
this.arr = arr; | |
this.ai = new AtomicInteger(); | |
} | |
void add(int i) { | |
int index = ai.getAndIncrement(); | |
int row = index / LIST_SIZE; | |
int col = index % LIST_SIZE; | |
arr[row][col] = i; | |
} | |
void add(IntTrio it) { | |
arr[it.row][it.col] = it.val; | |
arr[it.col][it.row] = it.val; | |
} | |
} | |
final DoubleIntArray dia = new DoubleIntArray(distances); // singleton | |
// Word list stream factory for methods 1, 2 | |
Supplier<Stream<String>> wl = | |
() -> parallel? wordList.parallelStream() : wordList.stream(); | |
// Integer list stream factory for method 3 | |
IntFunction<IntStream> iss = i -> { | |
IntStream is = IntStream.range(i, LIST_SIZE); | |
return parallel? is.parallel() : is; | |
}; | |
switch (method) { | |
case 1: | |
// Method 1 | |
class Pair<T> { T a, b; Pair(T c, T d) {a=c; b=d;}} | |
wl.get() | |
.flatMap(l -> wl.get() | |
.map(r -> new Pair<String>(l, r))) | |
.mapToInt(p -> Levenshtein.lev(p.a, p.b)) | |
.collect(() -> dia, DoubleIntArray::add, (l, r) -> {}); | |
assert dia.ai.get() == LIST_SIZE*LIST_SIZE; | |
break; | |
case 2: | |
// Method 2 | |
wl.get() | |
.flatMapToInt(l -> wl.get() | |
.mapToInt(r -> Levenshtein.lev(l, r))) | |
.collect(() -> dia, DoubleIntArray::add, (l, r) -> {}); | |
assert dia.ai.get() == LIST_SIZE*LIST_SIZE; | |
break; | |
case 3: | |
// Method 3 | |
iss.apply(0) | |
.mapToObj(row -> iss.apply(row+1) | |
.mapToObj(col -> new IntTrio(row, col, | |
Levenshtein.lev(wordList.get(row), wordList.get(col))))) | |
.flatMap(s -> s) | |
.collect(() -> dia, DoubleIntArray::add, (l, r) -> {}); | |
break; | |
} | |
return distances; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment