Ad
Code
Diff
  • import static java.util.Arrays.stream;
    
    interface Solution {
      static int similarPairs(String[] words) {
        return words.length - (int) stream(words).distinct().count();
      }
    }
    • import static java.util.stream.Collectors.toMap;
    • import static java.util.stream.IntStream.range;
    • import static java.util.function.Function.identity;
    • import static java.util.Arrays.stream;
    • class Solution {
    • public static int similarPairs(String[] words) {
    • return stream(words)
    • .collect(toMap(identity(), x -> 1, Integer::sum))
    • .values()
    • .stream()
    • .mapToInt(x -> x - 1)
    • .sum();
    • }
    • interface Solution {
    • static int similarPairs(String[] words) {
    • return words.length - (int) stream(words).distinct().count();
    • }
    • }

Shortified 😉

Code
Diff
  • interface Kata {
      static int doubleValue(int x) {
        return x + x;
      }
    }
    • package cat;
    • public class kata{
    • public static int doubleValue(int x) {
    • return x*2;
    • interface Kata {
    • static int doubleValue(int x) {
    • return x + x;
    • }
    • }

Shortified 😉

Code
Diff
  • import static java.util.stream.IntStream.of;
    
    class SpeedLimit {
       static int sequence(int[] arr) {
        return of(arr).sum();
      }
    }
    • import java.util.Arrays;
    • import static java.util.stream.IntStream.of;
    • public class SpeedLimit {
    • public static int sequence(int[] arr) {
    • return Arrays.stream(arr).sum();
    • class SpeedLimit {
    • static int sequence(int[] arr) {
    • return of(arr).sum();
    • }

Shortified 😉

Code
Diff
  • fun fact(n: Int) = (1..n).reduce(Int::times)
    • fun fact(n: Int): Int = if (n == 0) 1 else fact(n-1) * n
    • fun fact(n: Int) = (1..n).reduce(Int::times)
Arrays
Code
Diff
  • import static java.util.stream.IntStream.of;
    
    interface Kata {
      static int speedLimit(int speed, int[] signals) {
        return of(signals).reduce(0, (fine, sign) -> fine + (
            speed > sign + 29 ? 500 :
            speed > sign + 19 ? 250 :
            speed > sign +  9 ? 100 : 0));
      }
    }
    • public class Kata {public static int speedLimit(int speed, int[] signals) {int penalty = 0; for (int signal : signals) {int diff = speed - signal;penalty += diff >= 30 ? 500 : (diff >= 20 ? 250 :(diff >= 10 ? 100 :0));} return penalty;}}
    • import static java.util.stream.IntStream.of;
    • interface Kata {
    • static int speedLimit(int speed, int[] signals) {
    • return of(signals).reduce(0, (fine, sign) -> fine + (
    • speed > sign + 29 ? 500 :
    • speed > sign + 19 ? 250 :
    • speed > sign + 9 ? 100 : 0));
    • }
    • }
Code
Diff
  • class EvenOrOdd {    
      static String evenOrOdd(int n) {
        return n % 2 > 0 ? "Odd" : "Even";
      }
    }
    • class EvenOrOdd {
    • public static String evenOrOdd(int input) {
    • if (input%2==0){
    • return "Even";
    • }
    • return "Odd";
    • }
    • static String evenOrOdd(int n) {
    • return n % 2 > 0 ? "Odd" : "Even";
    • }
    • }
Code
Diff
  • returnInputNumber = n => n
    • from numpy import exp, array, random, dot
    • def returnInputNumber(n: int):
    • training_set_inputs = array([[0, 0, 1], [1, 1, 1], [1, 0, 1], [0, 1, 1]])
    • training_set_outputs = array([[0, 1, 1, 0]]).T
    • random.seed(1)
    • synaptic_weights = 2 * random.random((3, 1)) - 1
    • for i in range(10000):
    • output = 1 / (1 + exp(-(dot(training_set_inputs, synaptic_weights))))
    • synaptic_weights += dot(training_set_inputs.T, (training_set_outputs - output) * output * (1 - output))
    • return int(1 / (1 + exp(-(dot(array([1, 0, 0]), synaptic_weights)))) + 1) * n
    • returnInputNumber = n => n
Code
Diff
  • import static java.time.format.DateTimeFormatter.ofPattern;
    
    import java.time.LocalDateTime;
    
    public class Account {
      private Transaction current = new Transaction(0, 0);
    
      public void deposit(int amount) {
        current = new Transaction(current.balance() + amount, Math.abs(amount));
      }
    
      public void withdraw(int amount) {
        deposit(-amount);
      }
    
      public String printStatement() {
        return current.toString();
      }
    
      private record Transaction(int balance, int amount, LocalDateTime date) {
    
        public Transaction(int balance, int amount) {
          this(balance, amount, LocalDateTime.now());
        }
    
        @Override
        public String toString() {
          return String.format("Date Amount Balance%n%s%n%s %d %d",
              balance < 0 ? "Failed: Insufficient Funds" : amount <= 0 ? "Failed: Negative Transaction" : "",
              date.format(ofPattern("dd-MM-yyyy")), amount, balance);
        }
      }
    }
    • import static java.time.format.DateTimeFormatter.ofPattern;
    • import java.time.LocalDateTime;
    • import java.time.format.DateTimeFormatter;
    • public class Account {
    • private Transaction current = new Transaction(0, 0);
    • public void deposit(int amount) {
    • current = new Transaction(current.balance() + amount, Math.abs(amount));
    • }
    • LocalDateTime lastTransactionDate = LocalDateTime.of(1900,1,1,1,1);
    • int lastTransactionAmount = 0;
    • int lastTransactionBalance = 0;
    • private String statement = "Date Amount Balance" + "\n";
    • private static final String DATE_FORMATTER= "dd-MM-yyyy";
    • DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMATTER);
    • public void withdraw(int amount) {
    • deposit(-amount);
    • }
    • public String printStatement() {
    • return current.toString();
    • }
    • private record Transaction(int balance, int amount, LocalDateTime date) {
    • public String printStatement() {
    • if(this.lastTransactionBalance < 0){
    • return this.statement + "\n Failed: Insufficient Funds";
    • } else if(this.lastTransactionAmount <= 0){
    • return this.statement + "Failed: Negative Transaction";
    • }
    • return this.statement + "\n" + lastTransactionDate.format(formatter) + " " + lastTransactionAmount + " " + lastTransactionBalance;
    • public Transaction(int balance, int amount) {
    • this(balance, amount, LocalDateTime.now());
    • }
    • public void deposit(int amount){
    • this.lastTransactionBalance += amount;
    • this.lastTransactionAmount = amount;
    • this.lastTransactionDate = LocalDateTime.now();;
    • @Override
    • public String toString() {
    • return String.format("Date Amount Balance%n%s%n%s %d %d",
    • balance < 0 ? "Failed: Insufficient Funds" : amount <= 0 ? "Failed: Negative Transaction" : "",
    • date.format(ofPattern("dd-MM-yyyy")), amount, balance);
    • }
    • public void withdraw(int amount){
    • this.lastTransactionBalance -= amount;
    • this.lastTransactionAmount = amount;
    • this.lastTransactionDate = LocalDateTime.now();
    • }
    • }
Strings
Fundamentals
Code
Diff
  • interface PhoneWords {
      static String phoneWords(String str) {
        String[] pad = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        var message = new StringBuilder();
        for (int i = 0, j; i < str.length(); i += j + 1) {
          var abc = pad[str.charAt(i) - 48];
          j = offset(str, abc.length() - 1, i);
          message.append(abc.charAt(j));
        }
        return message.toString();
      }
    
      private static int offset(String str, int length, int i) {
        int j = 0;
        while (j < length && i + j < str.length() - 1 && str.charAt(i + j) == str.charAt(i + j + 1)) {
          j++;
        }
        return j;
      }
    }
    • import java.util.Map;
    • import java.util.HashMap;
    • interface PhoneWords {
    • static String phoneWords(String str) {
    • String[] pad = {" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    • var message = new StringBuilder();
    • for (int i = 0, j; i < str.length(); i += j + 1) {
    • var abc = pad[str.charAt(i) - 48];
    • j = offset(str, abc.length() - 1, i);
    • message.append(abc.charAt(j));
    • }
    • return message.toString();
    • }
    • public class phoneWords{
    • final static Map<Character, String> map = new HashMap<Character, String>() {{
    • put('0', " ");
    • put('2', "abc");
    • put('3', "def");
    • put('4', "ghi");
    • put('5', "jkl");
    • put('6', "mno");
    • put('7', "pqrs");
    • put('8', "tuv");
    • put('9', "wxyz");
    • }};
    • public static String phoneWords(String str){
    • StringBuilder mensaje = new StringBuilder();
    • for (int i = 0; i < str.length(); ++i) {
    • char letter = str.charAt(i);
    • int cont = 0;
    • int comparator = "79".indexOf(letter) == -1? 2: 3;
    • while (cont != comparator && i != str.length() - 1 && str.charAt(i) == str.charAt(i + 1)) {
    • ++cont;
    • ++i;
    • }
    • mensaje.append(map.get(letter).charAt(cont));
    • }
    • return mensaje.toString();
    • }
    • private static int offset(String str, int length, int i) {
    • int j = 0;
    • while (j < length && i + j < str.length() - 1 && str.charAt(i + j) == str.charAt(i + j + 1)) {
    • j++;
    • }
    • return j;
    • }
    • }
Code
Diff
  • import java.util.HashMap;
    import java.util.Map;
    
    class ReservationSystem {
      private static final int MAX_CAPACITY = 12;
      private final Map<String, Integer> availabilityByDate = new HashMap<>();
      private final Map<Reservation, Integer> reservations = new HashMap<>();
    
      public boolean request(String date, String name, String phone, int size) {
        int available = availabilityByDate.getOrDefault(date, MAX_CAPACITY);
        if (size < 1 || available < size) {
          return false;
        }
        reservations.put(new Reservation(date, name, phone), size);
        availabilityByDate.put(date, available - size);
        return true;
      }
    
      public void cancel(String date, String name, String phone) {
        var size = reservations.remove(new Reservation(date, name, phone));
        if (size != null) {
          availabilityByDate.computeIfPresent(date, (d, c) -> c + size);
        }
      }
    
      private record Reservation(String date, String name, String phone) {}
    }
    • import java.util.Map;
    • import java.util.HashMap;
    • import java.util.ArrayList;
    • import java.util.Map;
    • class ReservationSystem {
    • Map<String, ArrayList<Reservation>> bookings2 = new HashMap<>();
    • private static final int MAX_CAPACITY = 12;
    • private final Map<String, Integer> availabilityByDate = new HashMap<>();
    • private final Map<Reservation, Integer> reservations = new HashMap<>();
    • public boolean request(String date, String name, String phone, int size) {
    • if (!capacityAvailable(date, size)) {return false;}
    • commitReservation(date, name, phone, size);
    • int available = availabilityByDate.getOrDefault(date, MAX_CAPACITY);
    • if (size < 1 || available < size) {
    • return false;
    • }
    • reservations.put(new Reservation(date, name, phone), size);
    • availabilityByDate.put(date, available - size);
    • return true;
    • }
    • public void cancel(String date, String name, String phone) {
    • ArrayList<Reservation> reservations = bookings2.get(date);
    • if (reservations == null) {reservations = new ArrayList<Reservation>();}
    • ArrayList<Reservation> updatedReservations = new ArrayList<>();
    • for (Reservation reservation : reservations) {
    • if(reservation.name != name || reservation.phone != phone) {
    • updatedReservations.add(reservation);
    • }
    • var size = reservations.remove(new Reservation(date, name, phone));
    • if (size != null) {
    • availabilityByDate.computeIfPresent(date, (d, c) -> c + size);
    • }
    • bookings2.put(date, updatedReservations);
    • }
    • private boolean capacityAvailable(String date, int size) {
    • if (size <= 0) {return false;}
    • int booked = bookedCapacity(date);
    • return booked + size <= 12;
    • }
    • private int bookedCapacity(String date){
    • ArrayList<Reservation> booked = bookings2.get(date);
    • if(booked == null) {
    • booked = new ArrayList<Reservation>();
    • }
    • int totalBooked = 0;
    • for (Reservation r : booked) {
    • totalBooked += r.size;
    • }
    • return totalBooked;
    • }
    • private void commitReservation(String date, String name, String phone, int size) {
    • ArrayList<Reservation> reservations = bookings2.get(date);
    • if (reservations == null) {reservations = new ArrayList<Reservation>();}
    • reservations.add(new Reservation(date, name, phone, size));
    • bookings2.put(date, reservations);
    • }
    • }
    • class Reservation {
    • public final String date;
    • public final String name;
    • public final String phone;
    • public final int size;
    • public Reservation(String date, String name, String phone, int size) {
    • this.date = date;
    • this.name = name;
    • this.phone = phone;
    • this.size = size;
    • }
    • private record Reservation(String date, String name, String phone) {}
    • }
Code
Diff
  • import static java.util.function.Predicate.not;
    import static java.util.regex.Pattern.compile;
    
    interface StringCalculator {
      static int add(String numbers) {
        return compile("\\D")
            .splitAsStream(numbers)
            .filter(not(String::isEmpty))
            .mapToInt(Integer::parseInt)
            .sum();
      }
    }
    • import java.util.Arrays;
    • import static java.util.function.Predicate.not;
    • import static java.util.regex.Pattern.compile;
    • interface StringCalculator {
    • static int add(String numbers) {
    • return Arrays.stream(numbers.split("\\D"))
    • .filter(str -> str.length() > 0)
    • .mapToInt(Integer::parseInt)
    • .sum();
    • return compile("\\D")
    • .splitAsStream(numbers)
    • .filter(not(String::isEmpty))
    • .mapToInt(Integer::parseInt)
    • .sum();
    • }
    • }
Code
Diff
  • import static java.util.stream.IntStream.rangeClosed;
    import java.util.List;
    
    interface FizzBuzz {
      static List<String> evaluate(int input) {
        return rangeClosed(1, input).mapToObj(i -> i % 15 == 0 ? "FizzBuzz" :
            i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : "" + i).toList();
      }
    }
    • import static java.util.stream.IntStream.rangeClosed;
    • import java.util.List;
    • import java.util.ArrayList;
    • public class FizzBuzz {
    • public static List<String> evaluate(int input) {
    • List<String> listOfString = new ArrayList<>();
    • for (int i = 1; i < input + 1; i++) {
    • listOfString.add(parse(i));
    • }
    • return listOfString;
    • }
    • private static String parse(int number) {
    • if (number == 3) {
    • return "Fizz";
    • } else if (number == 5) {
    • return "Buzz";
    • }
    • return Integer.toString(number);
    • interface FizzBuzz {
    • static List<String> evaluate(int input) {
    • return rangeClosed(1, input).mapToObj(i -> i % 15 == 0 ? "FizzBuzz" :
    • i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : "" + i).toList();
    • }
    • }
Code
Diff
  • interface StringCalculator {
      static int add(String numbers) {
        int sum = 0;
        var temp = new StringBuilder("0");
        for (char c : numbers.toCharArray()) {
          if (Character.isDigit(c)) {
            temp.append(c);
          } else {
            sum += Integer.parseInt(temp.toString());
            temp.setLength(1);
          }
        }
        return sum + Integer.parseInt(temp.toString());
      }
    }
    • public class StringCalculator{
    • public static int add(String numbers){
    • int result = 0;
    • if(numbers == "")
    • return result;
    • numbers = numbers.replace(";", ",");
    • numbers = numbers.replace(getCustomDelimiter(numbers), ",");
    • numbers = numbers.replace("\n", ",");
    • for(String n: numbers.split(","))
    • {
    • result = result + parseValue(n);
    • }
    • return result;
    • }
    • private static int parseValue(String value) {
    • String regex = "\\d+";
    • if(value.matches(regex)) {
    • return Integer.parseInt(value);
    • } else {
    • return 0;
    • }
    • }
    • private static String getCustomDelimiter(String delim) {
    • if(delim.startsWith("//")) {
    • return delim.substring(2,3);
    • } else {
    • return "XXX";
    • interface StringCalculator {
    • static int add(String numbers) {
    • int sum = 0;
    • var temp = new StringBuilder("0");
    • for (char c : numbers.toCharArray()) {
    • if (Character.isDigit(c)) {
    • temp.append(c);
    • } else {
    • sum += Integer.parseInt(temp.toString());
    • temp.setLength(1);
    • }
    • }
    • return sum + Integer.parseInt(temp.toString());
    • }
    • }
    • }

Shortified ;)

Code
Diff
  • import static com.google.common.primitives.Ints.*;
    import static org.apache.commons.lang3.ArrayUtils.isEmpty;
    
    interface HighLow {
      static int[] findLargestAndSmallest(int[] nums) {
        return isEmpty(nums) ? null : new int[]{min(nums), max(nums)};
      }
    }
    • import static java.util.stream.IntStream.of;
    • import static com.google.common.primitives.Ints.*;
    • import static org.apache.commons.lang3.ArrayUtils.isEmpty;
    • interface HighLow {
    • static int[] findLargestAndSmallest(int[] nums) {
    • return (nums == null || nums.length == 0) ? null : new int[] {of(nums).summaryStatistics().getMin(), of(nums).summaryStatistics().getMax()};
    • }
    • }
    • static int[] findLargestAndSmallest(int[] nums) {
    • return isEmpty(nums) ? null : new int[]{min(nums), max(nums)};
    • }
    • }
Code
Diff
  • interface Kumite {
      static boolean hasThree(int x) {
        return (x + "").contains("3") ;
      }
    }
    • interface Kumite {
    • static boolean hasThree(int x) {
    • return !(x + "").replace("3","").equals((x + "")) ;
    • return (x + "").contains("3") ;
    • }
    • }
Loading more items...