Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. /**
  2. * Generate a poem from an input string.
  3. *
  4. * @param input string from which to create the poem
  5. * @return poem (as described above)
  6. */
  7. public String poem(String input) {
  8. List<String> output = new ArrayList<>();
  9. try (Scanner s = new Scanner(input).useDelimiter("\\s+")) {
  10. String old = "";
  11. while (s.hasNext()) {
  12. String cur = s.next();
  13. String prev = old.toLowerCase();
  14. String next = cur.toLowerCase();
  15. if (!old.isEmpty()) {
  16. output.add(old);
  17. Optional<String> bestBridge = graph.targets(prev).entrySet().stream()
  18. .filter(e -> graph.targets(e.getKey()).containsKey(next))
  19. .map(e -> e.getKey())
  20. .collect(Collectors.toMap(e -> e,
  21. e -> graph.sources(e).get(prev) + graph.targets(e).get(next)))
  22. .entrySet().stream()
  23. .sorted((a,b) -> b.getValue().compareTo(a.getValue()))
  24. .findFirst().map(e -> e.getKey());
  25. bestBridge.ifPresent(bridge -> output.add(bridge));
  26. }
  27. old = cur;
  28. }
  29. output.add(old);
  30. }
  31. checkRep();
  32. return output.stream().reduce((a,b) -> a + " " + b).orElse("");
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement