public class Recursion { public static void main(String[] args) { for (int i = 1; i < 10; i++) System.out.println(fib(i)); } public static long fib(long num) { if (num == 1) { return 0; } if (num == 2) { return 1; } return fib(num - 1) + fib(num - 2); } }
Wednesday, November 13, 2019
Fibonacci with Recursion
Common and Uncommon Words from Two Sentences
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; public class Strings { public static void main(String[] args) { String str1 = "my name is lenin koppoju"; String str2 = "my name is pradyumna koppoju"; System.out.println(common(str1, str2)); System.out.println(uncommon(str1, str2)); } public static List>String> uncommon(String str1, String str2) { return ucp(str1, str2, x -> !x.getValue()); } public static List>String> common(String str1, String str2) { return ucp(str1, str2, x -> x.getValue()); } private static List>String> ucp(String str1, String str2, Predicate>Map.Entry>String, Boolean>> predicate) { Map map = getMap(str1, str2); return filter(map, predicate); } private static Map>String, Boolean> getMap(String str1, String str2) { Map>String, Boolean> map = new HashMap>>(); prepareCardinalMap(map, str1); prepareCardinalMap(map, str2); return map; } private static List>String> filter(Map>String, Boolean> cardinalMap, Predicate>Map.Entry>String, Boolean>> predicate) { return cardinalMap.entrySet().stream().filter(predicate).map(x -> x.getKey()).collect(Collectors.toList()); } private static void prepareCardinalMap(Map>String, Boolean> map, String str) { for (String ss : str.split("\\s+")) { map.put(ss, map.containsKey(ss)); } } }
Subscribe to:
Posts (Atom)