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();
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; // TODO: Replace examples and use TDD by writing your own tests class SolutionTest { @Test void testSomething() { String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; String[] cars2 = {"Volvo", "Volvo", "Volvo", "Mazda"}; assertEquals(Solution.similarPairs(cars), 0); assertEquals(Solution.similarPairs(cars2), 2); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- // TODO: Replace examples and use TDD by writing your own tests
- class SolutionTest {
- @Test
- void testSomething() {
Solution aaa = new Solution();- String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
- String[] cars2 = {"Volvo", "Volvo", "Volvo", "Mazda"};
assertEquals("actual", "actual");assertEquals(aaa.similarPairs(cars), 0);assertEquals(aaa.similarPairs(cars2), 2);- assertEquals(Solution.similarPairs(cars), 0);
- assertEquals(Solution.similarPairs(cars2), 2);
- }
- }
Shortified 😉
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;
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void sample() { assertEquals(Kata.doubleValue(2), 4); assertEquals(Kata.doubleValue(3), 6); assertEquals(Kata.doubleValue(100), 200); assertEquals(Kata.doubleValue(628), 1256); assertEquals(Kata.doubleValue(-7), -14); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
import cat.kata.*;// TODO: Replace examples and use TDD by writing your own tests// added some tests here as well,- class SolutionTest {
@Testvoid testSomething() {assertEquals(cat.kata.doubleValue(2), 4);assertEquals(cat.kata.doubleValue(3), 6);assertEquals(cat.kata.doubleValue(100), 200);assertEquals(cat.kata.doubleValue(628), 1256);assertEquals(cat.kata.doubleValue(-7), -14);}}- @Test
- void sample() {
- assertEquals(Kata.doubleValue(2), 4);
- assertEquals(Kata.doubleValue(3), 6);
- assertEquals(Kata.doubleValue(100), 200);
- assertEquals(Kata.doubleValue(628), 1256);
- assertEquals(Kata.doubleValue(-7), -14);
- }
- }
Shortified 😉
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 😉
Arrays
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));
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void sample() { assertEquals(0, Kata.speedLimit(60, new int[0])); assertEquals(0, Kata.speedLimit(60, new int[] {80, 70, 60})); assertEquals(0, Kata.speedLimit(0, new int[] {15, 25, 35, 46})); assertEquals(250, Kata.speedLimit(100, new int[] {110, 100, 80})); assertEquals(500, Kata.speedLimit(130, new int[]{140, 130, 100})); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO: Replace examples and use TDD by writing your own tests- class SolutionTest {
- @Test
void testSpeedLimit() {assertEquals(0, Kata.speedLimit(60, new int[] {80,70,60 }));assertEquals(250, Kata.speedLimit(100, new int[]{110,100,80}));assertEquals(500, Kata.speedLimit(130, new int[]{140,130,100}));}@Testvoid emptyTest() {assertEquals(0, Kata.speedLimit(0, new int[]{15,25,35,46,}));assertEquals(0, Kata.speedLimit(60, new int[] {}));}- void sample() {
- assertEquals(0, Kata.speedLimit(60, new int[0]));
- assertEquals(0, Kata.speedLimit(60, new int[] {80, 70, 60}));
- assertEquals(0, Kata.speedLimit(0, new int[] {15, 25, 35, 46}));
- assertEquals(250, Kata.speedLimit(100, new int[] {110, 100, 80}));
- assertEquals(500, Kata.speedLimit(130, new int[]{140, 130, 100}));
- }
- }
returnInputNumber = n => n
from numpy import exp, array, random, dotdef 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]]).Trandom.seed(1)synaptic_weights = 2 * random.random((3, 1)) - 1for 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
const assert = require("chai").assert; describe("Getter", () => { it("sample", () => { assert.strictEqual(returnInputNumber(-4), -4); assert.strictEqual(returnInputNumber(0), 0); assert.strictEqual(returnInputNumber(1), 1); assert.strictEqual(returnInputNumber(2), 2); }); });
import codewars_test as test- const assert = require("chai").assert;
from solution import returnInputNumber@test.describe("Example")def test_group():@test.it("test case")def test_case():test.assert_equals(returnInputNumber(0), 0)test.assert_equals(returnInputNumber(-10), -10)test.assert_equals(returnInputNumber(3), 3)- describe("Getter", () => {
- it("sample", () => {
- assert.strictEqual(returnInputNumber(-4), -4);
- assert.strictEqual(returnInputNumber(0), 0);
- assert.strictEqual(returnInputNumber(1), 1);
- assert.strictEqual(returnInputNumber(2), 2);
- });
- });
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();- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; // TODO: Replace examples and use TDD by writing your own tests class SolutionTest { @Test void printStatement_displays_column_headings() { Account account = new Account(); String statement = account.printStatement(); String[] rows = statement.split("\\n"); String[] columns= rows[0].split("\\s"); String[] expectedColumns = "Date Amount Balance".split(" "); assertArrayEquals(expectedColumns, columns); } @Test void depositAmountIsDisplayedOnStatement(){ Account account = new Account(); account.deposit(500); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(500, line.amount()); } @Test void depositAmountIsAddedToAccountBalance(){ Account account = new Account(); account.deposit(500); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(500, line.balance()); } @Test void depositDateIsDisplayedOnStatment(){ String DATE_FORMATTER= "dd-MM-yyyy"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMATTER); Account account = new Account(); account.deposit(500); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(LocalDateTime.now().format(formatter), line.date()); } @Test void withdrawalAmountIsDisplayedOnStatement(){ Account account = new Account(); account.deposit(500); account.withdraw(100); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(100, line.amount()); } @Test void withdrawalAmountIsSubtractedFromAccountBalance(){ Account account = new Account(); account.deposit(500); account.withdraw(100); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(400, line.balance()); } @Test void withdrawalDateIsDisplayedOnStatment(){ String DATE_FORMATTER= "dd-MM-yyyy"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMATTER); Account account = new Account(); account.deposit(100); account.withdraw(100); String testStatement = account.printStatement(); String[] lines = testStatement.split("\n"); StatementLine line = parseStatementLine(lines[lines.length - 1]); assertEquals(LocalDateTime.now().format(formatter), line.date()); } @Test public void cannotOverdrawAccount(){ } //test helper method private StatementLine parseStatementLine(String statementLine) { String[] lineContents = statementLine.trim().split("\\s"); String date = lineContents[0]; int amount = Integer.parseInt(lineContents[1]); int balance = Integer.parseInt(lineContents[2]); return new StatementLine(date, amount, balance); } private record StatementLine(String date, int amount, int balance){} }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.jupiter.api.Assertions.assertTrue;
- import static org.junit.jupiter.api.Assertions.assertArrayEquals;
- import java.time.LocalDateTime;
- import java.time.format.DateTimeFormatter;
- // TODO: Replace examples and use TDD by writing your own tests
- class SolutionTest {
- @Test
- void printStatement_displays_column_headings() {
- Account account = new Account();
- String statement = account.printStatement();
- String[] rows = statement.split("\\n");
- String[] columns= rows[0].split("\\s");
- String[] expectedColumns = "Date Amount Balance".split(" ");
- assertArrayEquals(expectedColumns, columns);
- }
- @Test
- void depositAmountIsDisplayedOnStatement(){
- Account account = new Account();
- account.deposit(500);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(500, line.amount());
- }
- @Test
- void depositAmountIsAddedToAccountBalance(){
- Account account = new Account();
- account.deposit(500);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(500, line.balance());
- }
- @Test
- void depositDateIsDisplayedOnStatment(){
- String DATE_FORMATTER= "dd-MM-yyyy";
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMATTER);
- Account account = new Account();
- account.deposit(500);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(LocalDateTime.now().format(formatter), line.date());
- }
- @Test
- void withdrawalAmountIsDisplayedOnStatement(){
- Account account = new Account();
- account.deposit(500);
- account.withdraw(100);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(100, line.amount());
- }
- @Test
- void withdrawalAmountIsSubtractedFromAccountBalance(){
- Account account = new Account();
- account.deposit(500);
- account.withdraw(100);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(400, line.balance());
- }
- @Test
- void withdrawalDateIsDisplayedOnStatment(){
- String DATE_FORMATTER= "dd-MM-yyyy";
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMATTER);
- Account account = new Account();
account.lastTransactionBalance = 100;- account.deposit(100);
- account.withdraw(100);
- String testStatement = account.printStatement();
- String[] lines = testStatement.split("\n");
- StatementLine line = parseStatementLine(lines[lines.length - 1]);
- assertEquals(LocalDateTime.now().format(formatter), line.date());
- }
- @Test
- public void cannotOverdrawAccount(){
- }
- //test helper method
- private StatementLine parseStatementLine(String statementLine) {
- String[] lineContents = statementLine.trim().split("\\s");
- String date = lineContents[0];
- int amount = Integer.parseInt(lineContents[1]);
- int balance = Integer.parseInt(lineContents[2]);
- return new StatementLine(date, amount, balance);
- }
- private record StatementLine(String date, int amount, int balance){}
- }
Strings
Fundamentals
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;
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void sample() { assertEquals("", PhoneWords.phoneWords("")); assertEquals("hello how are you", PhoneWords.phoneWords("443355555566604466690277733099966688")); assertEquals("kata", PhoneWords.phoneWords("55282")); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
// TODO: Replace examples and use TDD by writing your own tests- class SolutionTest {
- @Test
void testSomething() {// assertEquals("expected", "actual");- void sample() {
- assertEquals("", PhoneWords.phoneWords(""));
- assertEquals("hello how are you", PhoneWords.phoneWords("443355555566604466690277733099966688"));
- assertEquals("kata", PhoneWords.phoneWords("55282"));
- }
@Testvoid isEmpty(){assertEquals("",phoneWords.phoneWords(""));}@Testvoid BasicTest(){assertEquals("hello how are you",phoneWords.phoneWords("443355555566604466690277733099966688"));assertEquals("kata",phoneWords.phoneWords("55282"));}}- }
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) {}
- }
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();
- }
- }
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();
- }
- }
import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; class SolutionTest { @Test void shouldAcceptInt() { assertEquals(List.of("1"), FizzBuzz.evaluate(1)); } @Test void inputOfTwo() { assertEquals(List.of("1", "2"), FizzBuzz.evaluate(2)); } @Test void inputOfThree() { assertEquals(List.of("1", "2", "Fizz"), FizzBuzz.evaluate(3)); } @Test void inputOfFive() { assertEquals(List.of("1", "2", "Fizz", "4", "Buzz"), FizzBuzz.evaluate(5)); } @Test void inputOfFifteen() { assertEquals(List.of("1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"), FizzBuzz.evaluate(15)); } }
- import org.junit.jupiter.api.Test;
- import java.util.List;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- class SolutionTest {
- @Test
- void shouldAcceptInt() {
- assertEquals(List.of("1"), FizzBuzz.evaluate(1));
- }
- @Test
- void inputOfTwo() {
- assertEquals(List.of("1", "2"), FizzBuzz.evaluate(2));
- }
- @Test
- void inputOfThree() {
- assertEquals(List.of("1", "2", "Fizz"), FizzBuzz.evaluate(3));
- }
- @Test
- void inputOfFive() {
- assertEquals(List.of("1", "2", "Fizz", "4", "Buzz"), FizzBuzz.evaluate(5));
- }
- @Test
- void inputOfFifteen() {
- assertEquals(List.of("1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"), FizzBuzz.evaluate(15));
- }
- }
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 ;)
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)};
- }
- }