Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.
You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.
A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.
package com.mystuff.juststuff; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Set; import java.util.TreeSet; 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) { 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); } }
- package com.mystuff.juststuff;
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.time.format.DateTimeParseException;
- 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;- 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) {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());}- 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);
- }
- }
package com.mystuff.juststuff; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.util.Set; import org.junit.Test; public class PalindromeTest { @Test public void testCountDatePalindromesEndDateBeforeStartDate() { final LocalDate startDate = LocalDate.of(2001, 12, 1); final LocalDate endDate = LocalDate.of(2001, 1, 31); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertTrue("Set size should be greater than zero", palSet.size() > 0); } @Test public void testCountDatePalindromesStartDateBeforeEndDate() { final LocalDate startDate = LocalDate.of(2001, 1, 1); final LocalDate endDate = LocalDate.of(2001, 12, 31); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertTrue("Set size should be greater than zero", palSet.size() > 0); } @Test public void testCountDatePalindromesStartDateEqualsEndDateNoPalindromes() { final LocalDate startDate = LocalDate.of(2001, 12, 31); // Dec 31, 2001 is not a palindrome date final LocalDate endDate = LocalDate.of(2001, 12, 31); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertEquals("Set size should be zero", 0, palSet.size()); } @Test public void testCountDatePalindromesStartDateEqualsEndDateOnePalindrome() { final LocalDate startDate = LocalDate.of(2001, 10, 2); // Oct 2, 2001 is a palindrome date final LocalDate endDate = LocalDate.of(2001, 10, 2); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertEquals("Set size should be one", 1, palSet.size()); } @Test public void testCountDatePalindromesHugeDateRange() { final LocalDate startDate = LocalDate.of(1900, 1, 1); final LocalDate endDate = LocalDate.of(2001, 12, 31); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertEquals("There is 1 palindrom date between 1/1/1900 12/31/2001", 1, palSet.size()); } @Test public void testCountDatePalindromesMultipleValues() { final LocalDate startDate = LocalDate.of(1900, 1, 1); final LocalDate endDate = LocalDate.of(2010, 12, 31); final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate); assertEquals("There are 2 palindrom date between 1/1/1900 12/31/2010", 2, palSet.size()); } }
- package com.mystuff.juststuff;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertTrue;
import java.util.Set;- import java.time.LocalDate;
- import java.util.Set;
- import org.junit.Test;
- public class PalindromeTest {
- @Test
- public void testCountDatePalindromesEndDateBeforeStartDate() {
- final LocalDate startDate = LocalDate.of(2001, 12, 1);
- final LocalDate endDate = LocalDate.of(2001, 1, 31);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
- assertTrue("Set size should be greater than zero", palSet.size() > 0);
- }
- @Test
- public void testCountDatePalindromesStartDateBeforeEndDate() {
- final LocalDate startDate = LocalDate.of(2001, 1, 1);
- final LocalDate endDate = LocalDate.of(2001, 12, 31);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
- assertTrue("Set size should be greater than zero", palSet.size() > 0);
- }
- @Test
- public void testCountDatePalindromesStartDateEqualsEndDateNoPalindromes() {
- final LocalDate startDate = LocalDate.of(2001, 12, 31); // Dec 31, 2001 is not a palindrome date
- final LocalDate endDate = LocalDate.of(2001, 12, 31);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
assertTrue("Set size should be zero", palSet.size() == 0);- assertEquals("Set size should be zero", 0, palSet.size());
- }
- @Test
- public void testCountDatePalindromesStartDateEqualsEndDateOnePalindrome() {
- final LocalDate startDate = LocalDate.of(2001, 10, 2); // Oct 2, 2001 is a palindrome date
- final LocalDate endDate = LocalDate.of(2001, 10, 2);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
assertTrue("Set size should be one", palSet.size() == 1);- assertEquals("Set size should be one", 1, palSet.size());
- }
- @Test
- public void testCountDatePalindromesHugeDateRange() {
- final LocalDate startDate = LocalDate.of(1900, 1, 1);
- final LocalDate endDate = LocalDate.of(2001, 12, 31);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
assertTrue("Set size should be greater than zero", palSet.size() > 0);- assertEquals("There is 1 palindrom date between 1/1/1900 12/31/2001", 1, palSet.size());
- }
- @Test
- public void testCountDatePalindromesMultipleValues() {
- final LocalDate startDate = LocalDate.of(1900, 1, 1);
- final LocalDate endDate = LocalDate.of(2010, 12, 31);
- final Set<LocalDate> palSet = new Palindrome().countDatePalindromes(startDate, endDate);
- assertEquals("There are 2 palindrom date between 1/1/1900 12/31/2010", 2, palSet.size());
- }
- }
The exact same program as before but with some rather messy comments in between (and at the start and end of the program). The Codewars built-in runBF
interpreter should correctly handle the program regardless and return the string "Hello World!"
.
[ This is a loop comment. Command characters, they should be ignored <here>. Including [matching square brackets]. Oh, and "+" and >-< signs. And gibberish: skldfjsdklfjs,..sd,dsf,s.fd,++--sdfsdsdfKLSDJFKLDSJ[[[][]][][[[][]]]] And unmatched round brackets: ((((()))(((())))))))))))))))))))))) ] sdklfjsdkldfjskldfs+++++++++++++++++sdlkfjsdlkfjsdfklsdjfkldsjfd++++++++++++++++++SDLKFJSDKLJSDFKLDSFJFDSKLJDFS++++++++++++++++++++++++SDLKFJDSFKLJFSDKLDSFJKSLDFJDSFKLDFSJ+++++++++++++.>++++(+++++(+()++)+((++)(++)))++++++++++++++NESWNEWSNEWWWSEEEEE+++++++++++++++;;++++++++++++;;;;;++++++++++++;;;;+++++++++;;;;;++++++++++++********++++++++++.>+++*****++++++++++++++***;;;*****++++++++++++;;**;;;+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.+++++sdfsfdsdfsdfsfd++++sdfsdffdsfds++sdfsdffsddfssdf+ (These last few plus signs should not affect the final output)
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.- [
- This is a loop comment.
- Command characters, they should be ignored <here>.
- Including [matching square brackets].
- Oh, and "+" and >-< signs.
- And gibberish: skldfjsdklfjs,..sd,dsf,s.fd,++--sdfsdsdfKLSDJFKLDSJ[[[][]][][[[][]]]]
- And unmatched round brackets: ((((()))(((()))))))))))))))))))))))
- ]
- sdklfjsdkldfjskldfs+++++++++++++++++sdlkfjsdlkfjsdfklsdjfkldsjfd++++++++++++++++++SDLKFJSDKLJSDFKLDSFJFDSKLJDFS++++++++++++++++++++++++SDLKFJDSFKLJFSDKLDSFJKSLDFJDSFKLDFSJ+++++++++++++.>++++(+++++(+()++)+((++)(++)))++++++++++++++NESWNEWSNEWWWSEEEEE+++++++++++++++;;++++++++++++;;;;;++++++++++++;;;;+++++++++;;;;;++++++++++++********++++++++++.>+++*****++++++++++++++***;;;*****++++++++++++;;**;;;+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++.+++++sdfsfdsdfsdfsfd++++sdfsdffdsfds++sdfsdffsddfssdf+ (These last few plus signs should not affect the final output)
After doing:
- Extract method
- Move method donde calcular el precio (movie or rental)?
- Unit test smell: Indirect Testing
- Replace temp with query
- Replace Type Code with State/Strategy
- Replace Conditional with Polymorphism
- Replace Constructor with Factory Method
class RentalReport { statement(customer) { let result = "Rental Record for " + customer.name + "\n"; customer.rentals.forEach((each) => { //show figures for this rental result += "\t" + each.movie.title+ "\t" + each.getAmount() + "\n"; }); //add footer lines result += "Amount owed is " + customer.getTotalAmount() + "\n"; result += "You earned " + customer.getFrequentPoints() + " frequent renter points"; return result; } } const MovieType = { CHILDREN: Symbol('CHILDREN'), REGULAR: Symbol('REGULAR'), NEW_RELEASE: Symbol('NEW_RELEASE'), } class Price { static create(priceCode) { switch (priceCode) { case MovieType.REGULAR: return new RegularPrice(); case MovieType.NEW_RELEASE: return new NewReleasePrice(); case MovieType.CHILDREN: return new ChildrenPrice(); } } get code() { throw "not implemented"; } getAmount(daysRented) { throw "not implemented"; } getFrequentPoints(daysRented) { return 1; } } class ChildrenPrice extends Price { get code() { return MovieType.CHILDREN; } getAmount(daysRented) { let amount = 1.5; if (daysRented > 3) amount += (daysRented - 3) * 1.5; return amount; } } class RegularPrice extends Price { get code() { return MovieType.REGULAR; } getAmount(daysRented) { let amount = 2; if (daysRented > 2) amount += (daysRented - 2) * 1.5; return amount; } } class NewReleasePrice extends Price { get code() { return MovieType.NEW_RELEASE; } getAmount(daysRented) { return daysRented * 3; } getFrequentPoints(daysRented) { return daysRented > 1 ? 2 : 1; } } class Movie { constructor (title, priceCode) { this._title = title; this.priceCode = priceCode; } set priceCode(priceCode) { this._price = Price.create(priceCode); } get priceCode() { return this._price.code; } get title() { return this._title; } getAmount(daysRented) { return this._price.getAmount(daysRented); } getFrequentPoints(daysRented) { return this._price.getFrequentPoints(daysRented); } } class Rental { constructor(movie, daysRented) { this._movie = movie; this._daysRented = daysRented; } get daysRented() { return this._daysRented; } get movie() { return this._movie; } getAmount() { return this.movie.getAmount(this.daysRented); } getFrequentPoints() { return this.movie.getFrequentPoints(this.daysRented); } } class Customer { constructor(name) { this._name = name; this._rentals = []; } get name() { return this._name; } get rentals() { return this._rentals; } addRental(rental) { this._rentals.push(rental); } getFrequentPoints() { return this.rentals.reduce((frequentPoints, rental) => frequentPoints + rental.getFrequentPoints(), 0); } getTotalAmount() { return this.rentals.reduce((amount, rental) => amount + rental.getAmount(), 0); } }
- class RentalReport {
- statement(customer) {
let totalAmount = 0;let frequentRenterPoints = 0;- let result = "Rental Record for " + customer.name + "\n";
- customer.rentals.forEach((each) => {
let thisAmount = 0;//determine amounts for each lineswitch (each.movie.priceCode) {case MovieType.REGULAR:thisAmount += 2;if (each.daysRented > 2)thisAmount += (each.daysRented - 2) * 1.5;break;case MovieType.NEW_RELEASE:thisAmount += each.daysRented * 3;break;case MovieType.CHILDREN:thisAmount += 1.5;if (each.daysRented > 3)thisAmount += (each.daysRented - 3) * 1.5;break;}// add frequent renter pointsfrequentRenterPoints ++;// add bonus for a two day new release rentalif ((each.movie.priceCode == MovieType.NEW_RELEASE) && each.daysRented > 1) frequentRenterPoints ++;- //show figures for this rental
result += "\t" + each.movie.title+ "\t" + thisAmount + "";totalAmount += thisAmount;- result += "\t" + each.movie.title+ "\t" + each.getAmount() + "
- ";
- });
- //add footer lines
result += "Amount owed is " + totalAmount + "";result += "You earned " + frequentRenterPoints + " frequent renter points";- result += "Amount owed is " + customer.getTotalAmount() + "
- ";
- result += "You earned " + customer.getFrequentPoints() + " frequent renter points";
- return result;
- }
- }
- const MovieType = {
- CHILDREN: Symbol('CHILDREN'),
- REGULAR: Symbol('REGULAR'),
- NEW_RELEASE: Symbol('NEW_RELEASE'),
- }
- class Price {
- static create(priceCode) {
- switch (priceCode) {
- case MovieType.REGULAR:
- return new RegularPrice();
- case MovieType.NEW_RELEASE:
- return new NewReleasePrice();
- case MovieType.CHILDREN:
- return new ChildrenPrice();
- }
- }
- get code() {
- throw "not implemented";
- }
- getAmount(daysRented) {
- throw "not implemented";
- }
- getFrequentPoints(daysRented) {
- return 1;
- }
- }
- class ChildrenPrice extends Price {
- get code() {
- return MovieType.CHILDREN;
- }
- getAmount(daysRented) {
- let amount = 1.5;
- if (daysRented > 3)
- amount += (daysRented - 3) * 1.5;
- return amount;
- }
- }
- class RegularPrice extends Price {
- get code() {
- return MovieType.REGULAR;
- }
- getAmount(daysRented) {
- let amount = 2;
- if (daysRented > 2)
- amount += (daysRented - 2) * 1.5;
- return amount;
- }
- }
- class NewReleasePrice extends Price {
- get code() {
- return MovieType.NEW_RELEASE;
- }
- getAmount(daysRented) {
- return daysRented * 3;
- }
- getFrequentPoints(daysRented) {
- return daysRented > 1 ? 2 : 1;
- }
- }
- class Movie {
- constructor (title, priceCode) {
- this._title = title;
this._priceCode = priceCode;- this.priceCode = priceCode;
- }
- set priceCode(priceCode) {
- this._price = Price.create(priceCode);
- }
- get priceCode() {
return this._priceCode;- return this._price.code;
- }
- get title() {
- return this._title;
- }
- getAmount(daysRented) {
- return this._price.getAmount(daysRented);
- }
- getFrequentPoints(daysRented) {
- return this._price.getFrequentPoints(daysRented);
- }
- }
- class Rental {
- constructor(movie, daysRented) {
- this._movie = movie;
- this._daysRented = daysRented;
- }
- get daysRented() {
- return this._daysRented;
- }
- get movie() {
- return this._movie;
- }
- getAmount() {
- return this.movie.getAmount(this.daysRented);
- }
- getFrequentPoints() {
- return this.movie.getFrequentPoints(this.daysRented);
- }
- }
- class Customer {
- constructor(name) {
- this._name = name;
- this._rentals = [];
- }
- get name() {
- return this._name;
- }
- get rentals() {
- return this._rentals;
- }
- addRental(rental) {
- this._rentals.push(rental);
- }
}- getFrequentPoints() {
- return this.rentals.reduce((frequentPoints, rental) => frequentPoints + rental.getFrequentPoints(), 0);
- }
- getTotalAmount() {
- return this.rentals.reduce((amount, rental) => amount + rental.getAmount(), 0);
- }
- }
function nextGeneration(grid) { return grid.map(() => 0); }
- function nextGeneration(grid) {
return grid;- return grid.map(() => 0);
- }
describe("Given empty grid", () => { it("when next generation, should return empty", () => { assert.deepEqual(nextGeneration([]), []); }); }); describe("Given a single cell", () => { it("when next generation, should die", () => { assert.deepEqual(nextGeneration([ 0,0,0, 0,1,0, 0,0,0, ]), [ 0,0,0, 0,0,0, 0,0,0, ]); }); }); describe("Given three neighbouring cells", () => { it("when next generation, produce a living cell", () => { assert.deepEqual(nextGeneration([ 0,1,0, 1,1,0, 0,0,0, ]), [ 1,1,0, 1,1,0, 0,0,0, ]); }); });
- describe("Given empty grid", () => {
- it("when next generation, should return empty", () => {
- assert.deepEqual(nextGeneration([]), []);
- });
- });
- describe("Given a single cell", () => {
- it("when next generation, should die", () => {
- assert.deepEqual(nextGeneration([
- 0,0,0,
- 0,1,0,
- 0,0,0,
- ]), [
- 0,0,0,
- 0,0,0,
- 0,0,0,
- ]);
- });
- });
- describe("Given three neighbouring cells", () => {
- it("when next generation, produce a living cell", () => {
- assert.deepEqual(nextGeneration([
- 0,1,0,
- 1,1,0,
- 0,0,0,
- ]), [
- 1,1,0,
- 1,1,0,
- 0,0,0,
- ]);
- });
- });
function sayHello(input) { return !input ? "Hello World!" : "Hello " + input + "!" };
- function sayHello(input) {
if (input !== true){return "Hello World!";} else {return "Hello " + input + "!";}- return !input ? "Hello World!" : "Hello " + input + "!"
- };
describe("given we are annonymous", () => { it("should say hello world", () => { Test.assertEquals(sayHello(), "Hello World!"); }); it("should say hello amigo", () => { Test.assertEquals(sayHello("Amigo"), "Hello Amigo!"); }); });
- describe("given we are annonymous", () => {
- it("should say hello world", () => {
- Test.assertEquals(sayHello(), "Hello World!");
- });
- it("should say hello amigo", () => {
- Test.assertEquals(sayHello("Amigo"), "Hello Amigo!");
- });
- });
/* 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();
- }
- }
import java.util.*; import org.junit.Before; import org.junit.Test; import org.junit.runners.JUnit4; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; public class MockTest { private Map<Integer, Integer> dummyMap; @Before public void setUp() { dummyMap = new HashMap<Integer, Integer>() {{ put(1, 1); put(2, 1); put(3, 1); put(4, 1); put(5, 1); put(6, 1); }}; } @Test public void testMapFromRangeClosed() { assertThat(HashMapDemo.mapFromRangeClosed(1, 6, i -> 1), is(dummyMap)); } @Test public void testForamttingEntry() { assertThat(HashMapDemo.formattingEntry().apply(new AbstractMap.SimpleEntry(123.45, "foo")), is("123.45 foo")); } @Test public void testToString() { assertThat(HashMapDemo.toString(dummyMap, e -> String.format("(%s -> %s)", e.getKey(), e.getValue()), ", "), is("(1 -> 1), (2 -> 1), (3 -> 1), (4 -> 1), (5 -> 1), (6 -> 1)")); } }
- import java.util.*;
- import org.junit.Before;
- import org.junit.Test;
import static org.junit.Assert.assertEquals;- import org.junit.runners.JUnit4;
import java.util.*;- import static org.junit.Assert.assertThat;
- import static org.hamcrest.CoreMatchers.is;
public class MockTest {- public class MockTest {
- private Map<Integer, Integer> dummyMap;
- @Before
- public void setUp() {
- dummyMap = new HashMap<Integer, Integer>() {{
- put(1, 1);
- put(2, 1);
- put(3, 1);
- put(4, 1);
- put(5, 1);
- put(6, 1);
- }};
- }
- @Test
public void test() {assertEquals(1, 1);}- public void testMapFromRangeClosed() {
- assertThat(HashMapDemo.mapFromRangeClosed(1, 6, i -> 1), is(dummyMap));
- }
- @Test
- public void testForamttingEntry() {
- assertThat(HashMapDemo.formattingEntry().apply(new AbstractMap.SimpleEntry(123.45, "foo")),
- is("123.45 foo"));
- }
- @Test
- public void testToString() {
- assertThat(HashMapDemo.toString(dummyMap, e -> String.format("(%s -> %s)", e.getKey(), e.getValue()), ", "),
- is("(1 -> 1), (2 -> 1), (3 -> 1), (4 -> 1), (5 -> 1), (6 -> 1)"));
- }
- }
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);
- }
- }
public class Primes { public static boolean isAPrime(int number) { if (number < 2 || (number % 2 == 0 && number != 2)) return false; for (int i = 3; i*i <= number; i += 2) { if (number % i == 0) return false; } return true; } }
- public class Primes {
- public static boolean isAPrime(int number) {
if(number > 1 && number == 2) return true; //1 is not a prime number by definitionelse {for(int i = 3; i*i < number; i +=2) {if (number % i == 0) return false;}- if (number < 2 || (number % 2 == 0 && number != 2)) return false;
- for (int i = 3; i*i <= number; i += 2) {
- if (number % i == 0) return false;
- }
- return true;
- }
- }
import org.junit.Test; import static org.junit.Assert.assertEquals; import org.junit.runners.JUnit4; import java.util.Random; public class SolutionTest { private static final Random RANDOM = new Random(); @Test public void twoShouldBeAPrime() { int numberToCheck = 2; boolean expected = true; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } @Test public void fortySevenShouldBeAPrime() { int numberToCheck = 47; boolean expected = true; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } @Test public void nineShouldNotBeAPrime() { int numberToCheck = 9; boolean expected = false; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } @Test public void n123ShouldNotBeAPrime() { int numberToCheck = 123; boolean expected = false; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } @Test public void n91ShouldNotBeAPrime() { int numberToCheck = 91; boolean expected = false; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } @Test public void n17977ShouldBeAPrime() { int numberToCheck = 17977; boolean expected = true; boolean actual = Primes.isAPrime(numberToCheck); assertEquals(expected, actual); } // better tests from @spacebison @Test public void fourShouldNotBeAPrime() { testPrime(4, false); } @Test public void aSquareShouldNotAPrime() { for (int i = 0; i < 10000; ++i) { int randomNumber = RANDOM.nextInt(Short.MAX_VALUE) + 2; int numberToCheck = randomNumber * randomNumber; testPrime(numberToCheck, false); } } @Test public void aProductOfTwoIntegersShouldNotBeAPrime() { for (int i = 0; i < 100000; ++i) { int a = RANDOM.nextInt(Short.MAX_VALUE) + 2; int b = RANDOM.nextInt(Short.MAX_VALUE) + 2; int numberToCheck = a * b; testPrime(numberToCheck, false); } } private static void testPrime(int numberToCheck, boolean expected) { boolean actual = Primes.isAPrime(numberToCheck); assertEquals(Integer.toString(numberToCheck), expected, actual); } }
- import org.junit.Test;
- import static org.junit.Assert.assertEquals;
- import org.junit.runners.JUnit4;
- import java.util.Random;
- public class SolutionTest {
- private static final Random RANDOM = new Random();
- @Test
- public void twoShouldBeAPrime() {
- int numberToCheck = 2;
- boolean expected = true;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
@Test- @Test
- public void fortySevenShouldBeAPrime() {
- int numberToCheck = 47;
- boolean expected = true;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
- @Test
- public void nineShouldNotBeAPrime() {
- int numberToCheck = 9;
- boolean expected = false;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
- @Test
- public void n123ShouldNotBeAPrime() {
- int numberToCheck = 123;
- boolean expected = false;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
- @Test
- public void n91ShouldNotBeAPrime() {
- int numberToCheck = 91;
- boolean expected = false;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
- @Test
- public void n17977ShouldBeAPrime() {
- int numberToCheck = 17977;
- boolean expected = true;
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(expected, actual);
- }
- // better tests from @spacebison
- @Test
- public void fourShouldNotBeAPrime() {
- testPrime(4, false);
- }
- @Test
- public void aSquareShouldNotAPrime() {
- for (int i = 0; i < 10000; ++i) {
- int randomNumber = RANDOM.nextInt(Short.MAX_VALUE) + 2;
- int numberToCheck = randomNumber * randomNumber;
- testPrime(numberToCheck, false);
- }
- }
- @Test
- public void aProductOfTwoIntegersShouldNotBeAPrime() {
- for (int i = 0; i < 100000; ++i) {
- int a = RANDOM.nextInt(Short.MAX_VALUE) + 2;
- int b = RANDOM.nextInt(Short.MAX_VALUE) + 2;
- int numberToCheck = a * b;
- testPrime(numberToCheck, false);
- }
- }
- private static void testPrime(int numberToCheck, boolean expected) {
- boolean actual = Primes.isAPrime(numberToCheck);
- assertEquals(Integer.toString(numberToCheck), expected, actual);
- }
- }