Skip to content

Instantly share code, notes, and snippets.

@maxmalysh
Last active October 3, 2015 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxmalysh/f2f3224491fcc0a33163 to your computer and use it in GitHub Desktop.
Save maxmalysh/f2f3224491fcc0a33163 to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang.RandomStringUtils;
public class Main {
public static abstract class Test {
abstract boolean start(String a, String b);
long run(String a, String b) {
long startTime = System.currentTimeMillis();
start(a, b);
long stopTime = System.currentTimeMillis();
return stopTime - startTime;
}
}
public static Test test1 = new Test() {
public boolean start(String a, String b) {
Map<Character, Integer> countChars = new HashMap<>();
// in Java 8. For older versions, it is also easy but more verbose
for (char ch : a.toCharArray()) countChars.put(ch, countChars.getOrDefault(ch, 0) + 1);
for (char ch : b.toCharArray()) {
int count = countChars.getOrDefault(ch, 0);
if (count < 1) return false;
countChars.put(ch, count - 1);
}
return true;
}
};
public static Test test2 = new Test() {
public boolean start(String a, String b) {
// Here we are counting occurrences of characters in the string
Map<Integer, Long> aCounted = a.chars().boxed().collect(Collectors.groupingBy(o -> o, Collectors.counting()));
Map<Integer, Long> bCounted = b.chars().boxed().collect(Collectors.groupingBy(o -> o, Collectors.counting()));
// Now we're checking if the second string contains all the characters from the first
return bCounted.keySet().stream().allMatch(
x -> bCounted.getOrDefault(x, 0l) >= aCounted.getOrDefault(x, 0l)
);
}
};
public static Test test3 = new Test() {
public boolean start(String a, String b) {
// Here we are counting occurrences of characters in the string
Map<Integer, Long> aCounted = a.chars().parallel().boxed().collect(Collectors.groupingBy(o -> o, Collectors.counting()));
Map<Integer, Long> bCounted = b.chars().parallel().boxed().collect(Collectors.groupingBy(o -> o, Collectors.counting()));
// Now we're checking if the second string contains all the characters from the first
return bCounted.keySet().parallelStream().allMatch(
x -> bCounted.getOrDefault(x, 0l) >= aCounted.getOrDefault(x, 0l)
);
}
};
public static void main(String[] args) {
int[] size = {15000, 500000, 5000000, 50000000};
Test[] tests = { test1, test2, test3 };
for (int N : size) {
String a = RandomStringUtils.randomAlphanumeric(N);
String b = RandomStringUtils.randomAlphanumeric(N);
// Warm-up JIT compiler
for (Test test : tests) {
test.start(a, b);
}
System.out.printf("N = %9d: ", N);
for (Test test : tests) {
long runTime = test.run(a, b);
System.out.printf("%8dms", runTime);
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment