Implementation of zip function #72 (#92)

* #72: First test passing

* #72: Second test passing

* #72: Third test passing

* #72: Added extra assertion

* #72: Fixed wrong test

* #72: Fixed wrong test

* #72: Added fourth test (passing)

* #72: fixed typo in test name

* #72: added fifth test

* #72: fixed test names

* #72: refactored for multiple inputs

* #72: added extra test cases and documentation

* #72: addressed @shekhargulati comments
This commit is contained in:
César Aguilera
2017-06-14 20:41:54 +05:30
committed by Shekhar Gulati
parent 375da9342d
commit 90322a7339
2 changed files with 108 additions and 0 deletions
+54
View File
@@ -33,6 +33,8 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import static java.lang.Math.min;
import static java.util.Collections.emptyList;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.*;
@@ -1334,5 +1336,57 @@ public abstract class Strman {
return countSubstr(value.substring(offset), subStr, allowOverlapping, ++count);
}
/**
* Aggregates the contents of n strings into a single list of tuples.
*
* @param inputs A list of strings.
* @return A list of strings if none of the strings in the input is null or empty.
* An empty list otherwise.
*/
public static List<String> zip(String... inputs) {
if (inputs.length == 1) {
return inputs[0].codePoints()
.mapToObj(Character::toChars)
.map(String::new)
.collect(toList());
}
int minLength = calculateMinLength(inputs);
if (minLength == -1) {
return emptyList();
}
List<String> zipped = new ArrayList<>(minLength);
for (int elementIndex = 0; elementIndex < minLength; ++elementIndex) {
StringBuilder tuple = new StringBuilder();
for (int inputIndex = 0; inputIndex < inputs.length; ++inputIndex) {
tuple.append(inputs[inputIndex].charAt(elementIndex));
}
zipped.add(tuple.toString());
}
return zipped;
}
private static int calculateMinLength(String[] inputs) {
if (inputs.length == 0) {
return -1;
}
int minLength = Integer.MAX_VALUE;
for (String input : inputs) {
if (isNullOrEmpty(input)) {
return -1;
}
minLength = min(minLength, input.length());
}
return minLength;
}
}