Code
Diff
  • import static java.util.stream.DoubleStream.of;
    import static org.apache.commons.lang3.ArrayUtils.reverse;
    
    interface DeleteDuplicates {
      static double[] delete(double[] a) {
        if (of(a).anyMatch(d -> d < 0)) {
          return new double[]{-1};
        }
        reverse(a);
        var unique = of(a).distinct().toArray();
        reverse(unique);
        return unique;
      }
    }
  • 1βˆ’
    import java.util.*;
    
    1+
    import static java.util.stream.DoubleStream.of;
    
    2+
    import static org.apache.commons.lang3.ArrayUtils.reverse;
    
    22
    3βˆ’
    class DeleteDuplicates {
    
    4βˆ’
      public static double[] delete(double[] a) { 
    
    5βˆ’
        
    
    6βˆ’
        for(int i = 0; i < a.length / 2; i++) {
    
    7βˆ’
          double temp = a[i];
    
    8βˆ’
          a[i] = a[a.length - i - 1];
    
    9βˆ’
          a[a.length - i - 1] = temp;
    
    4+
    interface DeleteDuplicates {
    
    5+
      static double[] delete(double[] a) {
    
    6+
        if (of(a).anyMatch(d -> d < 0)) {
    
    7+
          return new double[]{-1};
    
    1010
        }
    
    11βˆ’
    12βˆ’
        Set<Double> set = new LinkedHashSet<>();
    
    13βˆ’
        for (double v : a) {
    
    14βˆ’
          set.add(v);
    
    15βˆ’
          if(v < 0.0)
    
    9+
        reverse(a);
    
    10+
        var unique = of(a).distinct().toArray();
    
    11+
        reverse(unique);
    
    12+
        return unique;
    
    2727
      }
    
    2828
    }
    
Regular Expressions
Declarative Programming
Advanced Language Features
Fundamentals
Strings
Code
Diff
  • interface StringParity {
      static boolean isEvenLength(String str) {
        return str.length() % 2 < 1;
      }
    }
  • 1βˆ’
    class StringParity {
    
    2βˆ’
        public static boolean isEvenLength(String str) {
    
    3βˆ’
          return (str.length() & 1) == 0;
    
    4βˆ’
        }
    
    1+
    interface StringParity {
    
    2+
      static boolean isEvenLength(String str) {
    
    3+
        return str.length() % 2 < 1;
    
    4+
      }
    
    55
    }
    
Code
Diff
  • interface Kumite {
      static int add(int x, int y) {
        return Math.addExact(x, y);
      }
    }
  • 1βˆ’
    public class Kumite {
    
    2βˆ’
      public static int add(int x, int y) {
    
    3βˆ’
        return x+y;
    
    1+
    interface Kumite {
    
    2+
      static int add(int x, int y) {
    
    3+
        return Math.addExact(x, y);
    
    44
      }
    
    55
    }
    
Code
Diff
  • function factorial (n) {
      return n > 1 ? n * factorial(n - 1) : 1;  
    }
  • 11
    function factorial (n) {
    
    2βˆ’
      if (n === 1) {
    
    3βˆ’
        return 1;
    
    4βˆ’
      } 
    
    5βˆ’
        
    
    6βˆ’
      return n * factorial(n - 1);
    
    7βˆ’
      
    
    2+
      return n > 1 ? n * factorial(n - 1) : 1;  
    
    88
    }
    
Mathematics
Algorithms
Numbers
Code
Diff
  • import static java.util.stream.LongStream.iterate;
    
    import java.util.HashSet;
    
    interface Kata {
      static boolean isHappy(long h) {
        var seen = new HashSet<>();
        while (seen.add(h)) {
          h = iterate(h, i -> i > 0, i -> i / 10).map(i -> (int) Math.pow(i % 10, 2)).sum();
        }
        return h == 1;
      }
    }
    
  • 1βˆ’
    public class Kata {
    
    2βˆ’
      private static Object[] root = {null,
    
    3βˆ’
                                        new Object[][]{null, null, null, null, null, null, null, null, null, null, {new Boolean(true)}},
    
    4βˆ’
                                        null,
    
    5βˆ’
                                        null,
    
    6βˆ’
                                        null,
    
    7βˆ’
                                        null,
    
    8βˆ’
                                        null,
    
    9βˆ’
                                        null,
    
    10βˆ’
                                        null,
    
    11βˆ’
                                        null,
    
    12βˆ’
                                        new Object[]{new Boolean(false)}
    
    13βˆ’
                                       };
    
    14βˆ’
      public static boolean isHappy(long current) {
    
    15βˆ’
        Boolean[] result = {false};
    
    16βˆ’
        outer:
    
    17βˆ’
        for (; ; ) {
    
    18βˆ’
          long next = 0;
    
    19βˆ’
          Object[] node = root;
    
    20βˆ’
          while (current > 0) {
    
    21βˆ’
            int remainder = (int) (current % 10);
    
    22βˆ’
            current /= 10;
    
    23βˆ’
            next += remainder * remainder;
    
    24βˆ’
            if (node[remainder] == null) {
    
    25βˆ’
              node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
    
    26βˆ’
              while (current > 0) {
    
    27βˆ’
                remainder = (int) (current % 10);
    
    28βˆ’
                current /= 10;
    
    29βˆ’
                next += remainder * remainder;
    
    30βˆ’
                node = (Object[]) (node[remainder] = new Object[remainder == 0 ? 10 : 11]);
    
    31βˆ’
              }
    
    32βˆ’
              node[10] = result;
    
    33βˆ’
              current = next;
    
    34βˆ’
              continue outer;
    
    35βˆ’
            }
    
    36βˆ’
            node = (Object[]) node[remainder];
    
    37βˆ’
          }
    
    38βˆ’
          if (node[10] != null) {
    
    39βˆ’
            return result[0] = (Boolean) ((Object[]) node[10])[0];
    
    40βˆ’
          }
    
    41βˆ’
          node[10] = result;
    
    42βˆ’
          current = next;
    
    1+
    import static java.util.stream.LongStream.iterate;
    
    2+
    3+
    import java.util.HashSet;
    
    4+
    5+
    interface Kata {
    
    6+
      static boolean isHappy(long h) {
    
    7+
        var seen = new HashSet<>();
    
    8+
        while (seen.add(h)) {
    
    9+
          h = iterate(h, i -> i > 0, i -> i / 10).map(i -> (int) Math.pow(i % 10, 2)).sum();
    
    4343
        }
    
    11+
        return h == 1;
    
    4444
      }
    
    4545
    }
    
Strings
Code
Diff
  • import static java.util.Map.of;
    import static java.util.stream.Collectors.joining;
    
    interface Dislexifier {
      static String dislexify(String str) {
        return str.chars().mapToObj(c -> of('a', "4", 'o', "0", 'e', "3", 'i', "1")
            .getOrDefault(Character.toLowerCase((char) c), (char) c + "")).collect(joining());
      }
    }
  • 1βˆ’
    import java.util.HashMap;
    
    2βˆ’
    import java.util.Map;
    
    3βˆ’
    import java.util.stream.Collector;
    
    1+
    import static java.util.Map.of;
    
    2+
    import static java.util.stream.Collectors.joining;
    
    44
    5βˆ’
    class Dislexifier
    
    6βˆ’
    {
    
    7βˆ’
      public static final Map<Integer, Character> replaceMap;
    
    8βˆ’
    9βˆ’
        static {
    
    4+
    interface Dislexifier {
    
    5+
      static String dislexify(String str) {
    
    6+
        return str.chars().mapToObj(c -> of('a', "4", 'o', "0", 'e', "3", 'i', "1")
    
    7+
            .getOrDefault(Character.toLowerCase((char) c), (char) c + "")).collect(joining());
    
    8+
      }
    
    2727
    }
    
Strings

Well, the solution uses String#replceAll that doesn't follow recommentaions from the original task. But why not :)

Code
Diff
  • interface Dislexifier {
      static String dislexify(String str) {
        return str.replaceAll("o|O", "0").replaceAll("i|I", "1").replaceAll("e|E", "3").replaceAll("a|A", "4");
      }
    }
  • 1βˆ’
    class Dislexifier
    
    2βˆ’
    {
    
    3βˆ’
      public static String theDislexifier(String str)
    
    4βˆ’
      {
    
    5βˆ’
        
    
    6βˆ’
        // TODO: Do your magic here 
    
    7βˆ’
        
    
    8βˆ’
        return str.replace("a","4").replace("A","4").replace("o","0").replace("O","0").replace("e","3").replace("E","3").replace("i","1").replace("I","1");
    
    1+
    interface Dislexifier {
    
    2+
      static String dislexify(String str) {
    
    3+
        return str.replaceAll("o|O", "0").replaceAll("i|I", "1").replaceAll("e|E", "3").replaceAll("a|A", "4");
    
    99
      }
    
    1010
    }
    
Algorithms
Arrays
Mathematics
Numbers

I had to use this for the kyu 3 binomial expansion kata since I have no clue how to use the BigInts library for Java. Instead of calculating the total value of each factorial, this finds the factors of the numerator and denominator, simplifies, and divides the results.

Note: The n-choose-k formula

        n!
  ------------
   k!(n - k)!
Code
Diff
  • import static java.util.stream.IntStream.rangeClosed;
    
    interface ArrayFactorial {
      static int factorial(int n, int k) {
        return rangeClosed(1, k).reduce(1, (r, i) -> r * (n + 1 - i) / i);
      }
    }
  • 1βˆ’
    import java.util.stream.IntStream;
    
    1+
    import static java.util.stream.IntStream.rangeClosed;
    
    22
    3βˆ’
    public class ArrayFactorial{
    
    4βˆ’
        public static int factorial(int n, int k) {
    
    5βˆ’
            return IntStream.rangeClosed(1, Math.min(k, n - k))
    
    6βˆ’
                .reduce(1, (r, i) -> r * (n - i + 1) / i);
    
    7βˆ’
        }
    
    3+
    interface ArrayFactorial {
    
    4+
      static int factorial(int n, int k) {
    
    5+
        return rangeClosed(1, k).reduce(1, (r, i) -> r * (n + 1 - i) / i);
    
    6+
      }
    
    88
    }
    
Dates/Time
Code
Diff
  • package com.codewars;
    
    import static java.time.LocalDateTime.parse;
    import static java.time.temporal.ChronoUnit.SECONDS;
    
    import java.time.LocalDateTime;
    
    interface TimeSlotFinder {
      static boolean isSuitable(TimeSlot slot, String startTimeString, long durationInSeconds) {
        var startTime = parse(startTimeString);
        var endTime = startTime.plus(durationInSeconds, SECONDS);
        return !(startTime.isBefore(slot.startTime) || endTime.isAfter(slot.endTime));
      }
    
      class TimeSlot {
        private final LocalDateTime startTime;
        private final LocalDateTime endTime;
    
        TimeSlot(LocalDateTime startTime, LocalDateTime endTime) {
          this.startTime = startTime;
          this.endTime = endTime;
        }
      }
    }
  • 11
    package com.codewars;
    
    22
    3βˆ’
    import java.time.LocalDateTime;
    
    4βˆ’
    import java.time.temporal.ChronoUnit;
    
    5βˆ’
    import java.util.Optional;
    
    6βˆ’
    import java.util.function.Predicate;
    
    7βˆ’
    8βˆ’
    public class TimeSlotFinder {
    
    9βˆ’
      
    
    10βˆ’
      public boolean isSuitable(TimeSlot slot, String startTimeString, long durationInSecodns) {
    
    11βˆ’
    		LocalDateTime startTime = LocalDateTime.parse(startTimeString);
    
    12βˆ’
    		return Optional.of(slot)
    
    13βˆ’
    				.filter(startsBefore(startTime))
    
    14βˆ’
    				.filter(hasEnoughTimeLeftInSlot(startTime, durationInSecodns))
    
    15βˆ’
    				.isPresent();
    
    16βˆ’
    	}
    
    17βˆ’
    18βˆ’
    	public Predicate<TimeSlot> startsBefore(LocalDateTime startTime) {
    
    19βˆ’
    		return slot -> slot.startTime.isBefore(startTime) || slot.startTime.isEqual(startTime);
    
    20βˆ’
    	}
    
    21βˆ’
    22βˆ’
    	public Predicate<TimeSlot> hasEnoughTimeLeftInSlot(LocalDateTime startTime, long durationInSecodns) {
    
    23βˆ’
    		return slot -> ChronoUnit.SECONDS.between(startTime, slot.endTime) >= durationInSecodns;
    
    24βˆ’
    	}
    
    3+
    import static java.time.LocalDateTime.parse;
    
    4+
    import static java.time.temporal.ChronoUnit.SECONDS;
    
    2525
    6+
    import java.time.LocalDateTime;
    
    2626
    27βˆ’
    28βˆ’
      public static class TimeSlot {
    
    29βˆ’
    		public final LocalDateTime startTime;
    
    30βˆ’
    		public final LocalDateTime endTime;
    
    31βˆ’
    		public final long durationInSeconds;
    
    32βˆ’
    33βˆ’
    		public TimeSlot(String dateTimeString, long durationInSeconds) {
    
    34βˆ’
    			this.startTime = LocalDateTime.parse(dateTimeString);
    
    35βˆ’
    			this.endTime = startTime.plus(durationInSeconds, ChronoUnit.SECONDS);
    
    36βˆ’
    			this.durationInSeconds = durationInSeconds;
    
    37βˆ’
    		}
    
    8+
    interface TimeSlotFinder {
    
    9+
      static boolean isSuitable(TimeSlot slot, String startTimeString, long durationInSeconds) {
    
    10+
        var startTime = parse(startTimeString);
    
    11+
        var endTime = startTime.plus(durationInSeconds, SECONDS);
    
    12+
        return !(startTime.isBefore(slot.startTime) || endTime.isAfter(slot.endTime));
    
    13+
      }
    
    14+
    15+
      class TimeSlot {
    
    16+
        private final LocalDateTime startTime;
    
    17+
        private final LocalDateTime endTime;
    
    18+
    19+
        TimeSlot(LocalDateTime startTime, LocalDateTime endTime) {
    
    20+
          this.startTime = startTime;
    
    21+
          this.endTime = endTime;
    
    22+
        }
    
    3838
      }
    
    3939
    }
    
Fundamentals
Numbers
Basic Language Features
Arrays
Code
Diff
  • import static java.util.stream.IntStream.of;
    
    interface MaxProduct {
      static int solve(int[] arr, int num) {
        var stats = of(arr).summaryStatistics();
        return num * (arr.length < 1 ? 0 : num < 0 ? stats.getMin() : stats.getMax());
      }
    }
  • 11
    import static java.util.stream.IntStream.of;
    
    22
    33
    interface MaxProduct {
    
    44
      static int solve(int[] arr, int num) {
    
    5βˆ’
        if (num < 0) {
    
    6βˆ’
          return of(arr).min().orElse(0) * num;
    
    7βˆ’
        }
    
    8βˆ’
        return of(arr).max().orElse(0) * num;
    
    5+
        var stats = of(arr).summaryStatistics();
    
    6+
        return num * (arr.length < 1 ? 0 : num < 0 ? stats.getMin() : stats.getMax());
    
    99
      }
    
    1010
    }
    
Code
Diff
  • import static java.util.stream.IntStream.rangeClosed;
    
    interface MaxConsecutiveSum {
      static int[] maxConsecutiveSum(int num) {
        for (long i = 1, j = 1, sum = j; num > 2 && j < num / 2 + 2; j++, sum += j) {
          while (sum > num) {
            sum -= i++;
          }
          if (sum == num) {
            return rangeClosed((int) i, (int) j).toArray();
          }
        }
        return new int[0];
      }
    }
  • 1βˆ’
    public class MaxConsecutiveSum {
    
    2βˆ’
      
    
    3βˆ’
      public static class ConsecutiveInts {
    
    4βˆ’
        public final int start;
    
    5βˆ’
        public final int numElements;
    
    6βˆ’
        
    
    7βˆ’
        public ConsecutiveInts(int start, int numElements) {
    
    8βˆ’
          this.start = start;
    
    9βˆ’
          this.numElements = numElements;
    
    10βˆ’
        }
    
    11βˆ’
        
    
    12βˆ’
        public int[] asIntArray() {
    
    13βˆ’
          int[] result = new int[numElements];
    
    14βˆ’
          for (int i = 0; i < numElements; i++) {
    
    15βˆ’
            result[i] = start + i;
    
    16βˆ’
          }
    
    17βˆ’
          return result;
    
    18βˆ’
        }
    
    19βˆ’
      }
    
    20βˆ’
      public static ConsecutiveInts maxConsecutiveSumHelper(int num){
    
    21βˆ’
        // Can only use positive integers, so anything less than 1 won't work.
    
    22βˆ’
        if (num < 1) {
    
    23βˆ’
          return new ConsecutiveInts(0, 0);
    
    24βˆ’
        }
    
    25βˆ’
        int start = 1; //  current lowest possible number in the consecutive integers
    
    26βˆ’
        long sum = 0; // Use a long to avoid overflow.
    
    27βˆ’
        // Largest possible sum of at least 2 consecutive would be (num/2) + (num/2 + 1).
    
    28βˆ’
        final int highestPossible = Math.min(num, (num / 2) + 2);
    
    29βˆ’
        for (int i = 1; i < highestPossible; i++) {
    
    30βˆ’
          sum += i;
    
    31βˆ’
          // If our sum exceeds the target, start chopping off the smallest numbers.
    
    1+
    import static java.util.stream.IntStream.rangeClosed;
    
    2+
    3+
    interface MaxConsecutiveSum {
    
    4+
      static int[] maxConsecutiveSum(int num) {
    
    5+
        for (long i = 1, j = 1, sum = j; num > 2 && j < num / 2 + 2; j++, sum += j) {
    
    3232
          while (sum > num) {
    
    33βˆ’
            sum -= start;
    
    34βˆ’
            start++;
    
    7+
            sum -= i++;
    
    3535
          }
    
    3636
          if (sum == num) {
    
    37βˆ’
            return new ConsecutiveInts(start, i - start + 1);
    
    10+
            return rangeClosed((int) i, (int) j).toArray();
    
    3838
          }
    
    39βˆ’
          // else, sum < num, so keep going.
    
    4040
        }
    
    41βˆ’
        // No two consecutive integers below num.
    
    42βˆ’
        return new ConsecutiveInts(0, 0);
    
    43βˆ’
      }
    
    44βˆ’
      
    
    45βˆ’
      public static int[] maxConsecutiveSum(int num){
    
    46βˆ’
        return maxConsecutiveSumHelper(num).asIntArray();
    
    13+
        return new int[0];
    
    4747
      }
    
    4848
    }
    

But indeed, there is another way :)

Code
Diff
  • interface Primeira {
      static int sum(int a, int b) {
        return Math.addExact(a, b);
      }
    }
    
  • 1βˆ’
    public class Primeira {
    
    2βˆ’
        public static int sum (int a, int b) {
    
    3βˆ’
            return a + b;
    
    4βˆ’
        }
    
    1+
    interface Primeira {
    
    2+
      static int sum(int a, int b) {
    
    3+
        return Math.addExact(a, b);
    
    4+
      }
    
    55
    }
    

I guess this can be treated as "without sorting" :)

Code
Diff
  • import static java.util.stream.IntStream.of;
    
    interface HighLow {
      static int[] printLargestAndSmallest(int[] nums) {
        var stats = of(nums).summaryStatistics();
        return new int[]{stats.getMin(), stats.getMax()};
      }
    }
    
  • 1βˆ’
    public class HighLow{
    
    2βˆ’
      public static int[] printLargestAndSmallest(int[] nums){
    
    3βˆ’
    		int low[] = nums;
    
    4βˆ’
    		int high[] = nums;
    
    5βˆ’
    		int lowest = nums[0];
    
    6βˆ’
    		int highest = nums[0];
    
    7βˆ’
    		int count = 0;
    
    8βˆ’
    		
    
    9βˆ’
    		for(int i = 0; i < nums.length;i+=2){
    
    10βˆ’
    			int num1 = nums[i];
    
    11βˆ’
    			int num2 = nums[i+1];
    
    12βˆ’
    			
    
    13βˆ’
    			if(num1<num2){
    
    14βˆ’
    				low[count] = num1;
    
    15βˆ’
    				high[count] = num2;
    
    16βˆ’
    				count++;
    
    17βˆ’
    			}else{
    
    18βˆ’
    				low[count] = num2;
    
    19βˆ’
    				high[count] = num1;
    
    20βˆ’
    				count++;
    
    21βˆ’
    			}
    
    22βˆ’
    			
    
    23βˆ’
    			lowest = low[0];
    
    24βˆ’
    			highest = high[0];
    
    25βˆ’
    			
    
    26βˆ’
    			for(int j = 1; j < low.length; j++){
    
    27βˆ’
    				if(low[j] < lowest){
    
    28βˆ’
    					lowest = low[j];			
    
    29βˆ’
    				}
    
    30βˆ’
    			}
    
    31βˆ’
    			
    
    32βˆ’
    			for(int j = 1; j < high.length; j++){
    
    33βˆ’
    				if(high[j] > highest){
    
    34βˆ’
    					highest = high[j];
    
    35βˆ’
    				}
    
    36βˆ’
    			}
    
    1+
    import static java.util.stream.IntStream.of;
    
    3737
    38βˆ’
    		}
    
    39βˆ’
        int[] finalHighLow = new int[2];
    
    40βˆ’
        finalHighLow[0] = lowest;
    
    41βˆ’
        finalHighLow[1] = highest;
    
    42βˆ’
        return finalHighLow;
    
    43βˆ’
    	}
    
    3+
    interface HighLow {
    
    4+
      static int[] printLargestAndSmallest(int[] nums) {
    
    5+
        var stats = of(nums).summaryStatistics();
    
    6+
        return new int[]{stats.getMin(), stats.getMax()};
    
    7+
      }
    
    4444
    }
    

A code-golfed variation of @rowcased authored solution.

Code
Diff
  • interface Calculator {
      static int calculate(int a, int b, char ops) {
        return new int[]{a * b, a + b, 0, a - b}[ops - 42];
      }
    }
    
  • 11
    interface Calculator {
    
    22
      static int calculate(int a, int b, char ops) {
    
    3βˆ’
        int[] calcs = {a * b, a + b, 0, a - b, 0, a / b};
    
    4βˆ’
        return calcs[ops - 42];
    
    3+
        return new int[]{a * b, a + b, 0, a - b}[ops - 42];
    
    55
      }
    
    66
    }
    

Create a simple calculator that given two numbers and an operator returns the value of the arithmetic operation. Here are the operations to support:

  • + - addition
  • - - subtraction
  • * - multiplication

Example:

Calculator.calculate(2, 2, '+') // => 4
Calculator.calculate(5, 5, '-') // => 0
Calculator.calculate(1, 1, '*') // => 1
Code
Diff
  • import javax.script.ScriptEngineManager;
    
    interface Calculator {
      static int calculate(int a, int b, char operation) {
        var engine = new ScriptEngineManager().getEngineByName("JavaScript");
        try {
          return Integer.parseInt(String.valueOf(engine.eval(a + " " + operation + " " + b)));
        } catch (Exception cause) {
          return 0;
        }
      }
    }
    
  • 1βˆ’
    public class calculator {
    
    2βˆ’
      public static int calculate(int n, int m, char symbol) {
    
    3βˆ’
        // do your best :)
    
    4βˆ’
        int result = 0;
    
    5βˆ’
        switch(symbol) {
    
    6βˆ’
            case '+':
    
    7βˆ’
          result = n + m;
    
    8βˆ’
          break;
    
    9βˆ’
            case '-':
    
    10βˆ’
          result = n - m;
    
    11βˆ’
          break;
    
    12βˆ’
            case '*':
    
    13βˆ’
          result = n * m;
    
    14βˆ’
          break;
    
    1+
    import javax.script.ScriptEngineManager;
    
    2+
    3+
    interface Calculator {
    
    4+
      static int calculate(int a, int b, char operation) {
    
    5+
        var engine = new ScriptEngineManager().getEngineByName("JavaScript");
    
    6+
        try {
    
    7+
          return Integer.parseInt(String.valueOf(engine.eval(a + " " + operation + " " + b)));
    
    8+
        } catch (Exception cause) {
    
    9+
          return 0;
    
    1515
        }
    
    16βˆ’
      return result;
    
    1717
      }
    
    1818
    }
    
Loading more items...