Ad
Code
Diff
  • public class Algorithms {
      public static int reverseInt(int n) {
        return Integer.parseInt(new StringBuilder(String.valueOf(n)).reverse().toString());
      }
    }
    • public class Algorithms {
    • public static int reverseInt(int n) {
    • return Integer.parseInt(new StringBuffer(String.valueOf(n)).reverse().toString());
    • }
    • return Integer.parseInt(new StringBuilder(String.valueOf(n)).reverse().toString());
    • }
    • }
Code
Diff
  • package com.mystuff.juststuff;
    
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    import java.util.Arrays;
    import java.util.Set;
    import java.util.SortedSet;
    import java.util.TreeSet;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    public class Palindrome {
    
      private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    
      public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
        final SortedSet<LocalDate> sortedDates = new TreeSet<>(Arrays.asList(startDate, endDate));
        return IntStream.rangeClosed(sortedDates.first().getYear(), sortedDates.last().getYear())
            .mapToObj(Palindrome::createPalindrome)
            .filter(isDateInRange(sortedDates.first(), sortedDates.last()))
            .collect(Collectors.toCollection(TreeSet::new));
      }
    
      private static LocalDate createPalindrome(final int year) {
        final String yearStr = String.valueOf(year);
        final String datePalindrome = new StringBuilder(yearStr).reverse().append(yearStr).toString();
        try {
          return LocalDate.parse(datePalindrome, formatter);
        } catch (final DateTimeParseException e) {}
        return null;
      }
    
      private static Predicate<LocalDate> isDateInRange(final LocalDate startDate, final LocalDate endDate) {
        return (date) -> !(date == null || date.isBefore(startDate) || date.isAfter(endDate));
      }
    }
    • package com.mystuff.juststuff;
    • import java.time.LocalDate;
    • import java.time.format.DateTimeFormatter;
    • import java.time.format.DateTimeParseException;
    • import java.util.Arrays;
    • import java.util.Set;
    • import java.util.SortedSet;
    • import java.util.TreeSet;
    • import java.util.function.Predicate;
    • import java.util.stream.Collectors;
    • import java.util.stream.IntStream;
    • public class Palindrome {
    • private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    • private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    • public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
    • return IntStream.range(startDate.getYear(), endDate.getYear() + 1).mapToObj(Palindrome::createPalindrome)
    • .filter(date -> isValidDate(date, startDate, endDate)).collect(Collectors.toCollection(TreeSet::new));
    • }
    • private static LocalDate createPalindrome(int year) {
    • String yearStr = String.valueOf(year);
    • String datePalindrome = new StringBuilder().append(yearStr).reverse().append(yearStr).toString();
    • try {
    • return LocalDate.parse(datePalindrome, formatter);
    • } catch (DateTimeParseException e) {
    • return null;
    • }
    • }
    • private static boolean isValidDate(final LocalDate date, LocalDate startDate, LocalDate endDate) {
    • if (date == null)
    • return false;
    • if (startDate.isEqual(date) || endDate.isEqual(date))
    • return true;
    • return startDate.isBefore(date) && endDate.isAfter(date) ||
    • endDate.isBefore(date) && startDate.isAfter(date);
    • }
    • public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
    • final SortedSet<LocalDate> sortedDates = new TreeSet<>(Arrays.asList(startDate, endDate));
    • return IntStream.rangeClosed(sortedDates.first().getYear(), sortedDates.last().getYear())
    • .mapToObj(Palindrome::createPalindrome)
    • .filter(isDateInRange(sortedDates.first(), sortedDates.last()))
    • .collect(Collectors.toCollection(TreeSet::new));
    • }
    • private static LocalDate createPalindrome(final int year) {
    • final String yearStr = String.valueOf(year);
    • final String datePalindrome = new StringBuilder(yearStr).reverse().append(yearStr).toString();
    • try {
    • return LocalDate.parse(datePalindrome, formatter);
    • } catch (final DateTimeParseException e) {}
    • return null;
    • }
    • private static Predicate<LocalDate> isDateInRange(final LocalDate startDate, final LocalDate endDate) {
    • return (date) -> !(date == null || date.isBefore(startDate) || date.isAfter(endDate));
    • }
    • }
Code
Diff
  • function nextGeneration(grid) {
      return grid.map(() => 0);
    }
    • function nextGeneration(grid) {
    • return grid;
    • return grid.map(() => 0);
    • }
Code
Diff
  • package com.mystuff.juststuff;
    
    import java.util.Set;
    import java.util.SortedSet;
    import java.util.TreeSet;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.ChronoUnit;
    
    
    public class Palindrome {
    
      private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    
      public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
        final SortedSet<LocalDate> sortedDates = Stream.of(startDate, endDate).collect(Collectors.toCollection(TreeSet::new));
        return Stream.iterate(sortedDates.first(), date -> date.plusDays(1))
            .limit(ChronoUnit.DAYS.between(sortedDates.first(), sortedDates.last().plusDays(1)))
            .filter(Palindrome::isPalindrome)
            .collect(Collectors.toCollection(TreeSet::new));
      }
      
      private static boolean isPalindrome(final LocalDate date) {
        final String fwd = date.format(formatter);
        return fwd.equals(new StringBuilder(fwd).reverse().toString());
      }
    }
    • package com.mystuff.juststuff;
    • import java.text.*;
    • import java.util.*;
    • import java.util.Set;
    • import java.util.SortedSet;
    • import java.util.TreeSet;
    • import java.util.stream.Collectors;
    • import java.util.stream.Stream;
    • import java.time.LocalDate;
    • import java.time.format.DateTimeFormatter;
    • import java.time.temporal.ChronoUnit;
    • public class Palindrome {
    • private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");
    • private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
    • public Set<Date> countDatePalindromes(final Date startDate, final Date endDate) {
    • final Set<Date> set = new TreeSet<>();
    • final GregorianCalendar startCal = new GregorianCalendar();
    • final GregorianCalendar endCal = new GregorianCalendar();
    • // If end date is before start date, flip them.
    • startCal.setTime(startDate.before(endDate) ? startDate : endDate);
    • endCal.setTime(startDate.after(endDate) ? startDate : endDate);
    • for (; startCal.before(endCal) || startCal.equals(endCal); startCal.add(Calendar.DAY_OF_MONTH, 1)) {
    • final String forward = sdf.format(startCal.getTime());
    • final String back = new StringBuilder(forward).reverse().toString();
    • if (forward.equals(back)) {
    • set.add(startCal.getTime()); // Date string looks same both ways
    • }
    • }
    • return set;
    • }
    • }
    • public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
    • final SortedSet<LocalDate> sortedDates = Stream.of(startDate, endDate).collect(Collectors.toCollection(TreeSet::new));
    • return Stream.iterate(sortedDates.first(), date -> date.plusDays(1))
    • .limit(ChronoUnit.DAYS.between(sortedDates.first(), sortedDates.last().plusDays(1)))
    • .filter(Palindrome::isPalindrome)
    • .collect(Collectors.toCollection(TreeSet::new));
    • }
    • private static boolean isPalindrome(final LocalDate date) {
    • final String fwd = date.format(formatter);
    • return fwd.equals(new StringBuilder(fwd).reverse().toString());
    • }
    • }
Hashes
Data Structures
Code
Diff
  • /* HashMap Example */
     
    import java.util.*;
    import java.util.function.*;
    import java.util.stream.*;
     
    class HashMapDemo {
      public static void main (final String[] args) throws Exception {
        System.out.println(toString(mapFromRangeClosed(1, 6, i -> 1), formattingEntry(), "\n"));
      }
      
      public static <T> Map<Integer, T> mapFromRangeClosed(final int lo, final int hi, final Function<Integer, T> valueMapper) {
        return IntStream.rangeClosed(lo, hi).boxed().collect(Collectors.toMap(Function.identity(), valueMapper));
      }
      
      public static <K,V> String toString(final Map<K, V> map, final Function<Map.Entry<K, V>, String> entryFormatter, final CharSequence delimiter) {
        return map.entrySet().stream().map(entryFormatter).collect(Collectors.joining(delimiter));
      }
      
      public static <K,V> Function<Map.Entry<K, V>, String> formattingEntry() {
        return e -> e.getKey() + " " + e.getValue();
      }
    }
    • /* HashMap Example */
    • import java.util.*;
    • import java.lang.*;
    • import java.io.*;
    • import java.util.function.*;
    • import java.util.stream.*;
    • class HashMapDemo
    • {
    • public static void main (String[] args) throws java.lang.Exception {
    • Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{
    • put(1, 1);
    • put(2, 1);
    • put(3, 1);
    • put(4, 1);
    • put(5, 1);
    • put(6, 1);
    • }};
    • map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
    • class HashMapDemo {
    • public static void main (final String[] args) throws Exception {
    • System.out.println(toString(mapFromRangeClosed(1, 6, i -> 1), formattingEntry(), "\n"));
    • }
    • public static <T> Map<Integer, T> mapFromRangeClosed(final int lo, final int hi, final Function<Integer, T> valueMapper) {
    • return IntStream.rangeClosed(lo, hi).boxed().collect(Collectors.toMap(Function.identity(), valueMapper));
    • }
    • public static <K,V> String toString(final Map<K, V> map, final Function<Map.Entry<K, V>, String> entryFormatter, final CharSequence delimiter) {
    • return map.entrySet().stream().map(entryFormatter).collect(Collectors.joining(delimiter));
    • }
    • public static <K,V> Function<Map.Entry<K, V>, String> formattingEntry() {
    • return e -> e.getKey() + " " + e.getValue();
    • }
    • }
Code
Diff
  • import java.util.Map;
    import java.util.function.Function;
    import java.util.stream.Collectors;
    import java.util.stream.IntStream;
    
    /**
      Time Complexity  : O(N)
      Space Complexity : O(N)
    */
    class MaxOccurence {
    
      public static int findMax(final int[] nums) {
        return IntStream.of(nums).boxed()
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
          .entrySet().stream()
          .max(Map.Entry.comparingByValue())
          .map(Map.Entry::getKey).orElse(-1);
      }
    }
    • import java.util.*;
    • import java.util.List;
    • import java.util.Map;
    • import java.util.Optional;
    • import java.util.function.Function;
    • import java.util.stream.Collectors;
    • import java.util.stream.IntStream;
    • /**
    • Time Complexity : O(N)
    • Space Complexity : O(N)
    • */
    • class MaxOccurence {
    • public static int findMax(int[] nums) {
    • Optional<Map.Entry<Integer, List<Integer>>> max = IntStream.of(nums)
    • .boxed()
    • .collect(Collectors.groupingBy(num -> num))
    • .entrySet()
    • .stream()
    • .max((e1, e2) -> e1.getValue().size() - e2.getValue().size());
    • return max.isPresent() ? max.get().getKey() : -1;
    • public static int findMax(final int[] nums) {
    • return IntStream.of(nums).boxed()
    • .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
    • .entrySet().stream()
    • .max(Map.Entry.comparingByValue())
    • .map(Map.Entry::getKey).orElse(-1);
    • }
    • }
Code
Diff
  • import java.util.*;
    import java.util.stream.*;
    
    class Solution {
         
      public static int retSmallestPositiveInteger() {
        return IntStream.iterate(1, x -> x + 1).filter(Solution::hasSameDigitsForFactorsInRange).findFirst().getAsInt();
      }
      
      private static boolean hasSameDigitsForFactorsInRange(final int x) {
        final Map<Integer, Integer> xDigits = digitsOf(x);
        return IntStream.rangeClosed(2, 6).allMatch(f -> xDigits.equals(digitsOf(x * f)));
      }
      
      private static Map<Integer, Integer> digitsOf(final int number) {
        return String.valueOf(number).chars().map(Character::getNumericValue)
    			    .collect(HashMap<Integer, Integer>::new,
    			             (m, x) -> m.put(x, m.getOrDefault(x, 0) + 1),
    			             HashMap::putAll);
      }
    }
    • import java.util.*;
    • import java.util.stream.*;
    • class Solution {
    • public static int retSmallestPositiveInteger() {
    • return IntStream.iterate(1, x -> x + 1).filter(Solution::hasSameDigitsForFactorsInRange).findFirst().getAsInt();
    • }
    • public static int retSmallestPositiveInteger() {
    • for(int i=1; ; i++) {
    • if(hasSameDigits(i, i*2) && hasSameDigits(i, i*3) && hasSameDigits(i, i*4) && hasSameDigits(i, i*5) && hasSameDigits(i, i*6))
    • return i;
    • }
    • }
    • private static boolean hasSameDigitsForFactorsInRange(final int x) {
    • final Map<Integer, Integer> xDigits = digitsOf(x);
    • return IntStream.rangeClosed(2, 6).allMatch(f -> xDigits.equals(digitsOf(x * f)));
    • }
    • private static boolean hasSameDigits(int x, int y) {
    • char[] xdigits = Integer.toString(x).toCharArray();
    • char[] ydigits = Integer.toString(y).toCharArray();
    • Arrays.sort(xdigits);
    • Arrays.sort(ydigits);
    • return Arrays.equals(xdigits, ydigits);
    • }
    • private static Map<Integer, Integer> digitsOf(final int number) {
    • return String.valueOf(number).chars().map(Character::getNumericValue)
    • .collect(HashMap<Integer, Integer>::new,
    • (m, x) -> m.put(x, m.getOrDefault(x, 0) + 1),
    • HashMap::putAll);
    • }
    • }