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.
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,
- ]);
- });
- });
package com.mystuff.juststuff; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class Palindrome { private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy"); public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) { final SortedSet<LocalDate> sortedDates = Stream.of(startDate, endDate).collect(Collectors.toCollection(TreeSet::new)); return Stream.iterate(sortedDates.first(), date -> date.plusDays(1)) .limit(ChronoUnit.DAYS.between(sortedDates.first(), sortedDates.last().plusDays(1))) .filter(Palindrome::isPalindrome) .collect(Collectors.toCollection(TreeSet::new)); } private static boolean isPalindrome(final LocalDate date) { final String fwd = date.format(formatter); return fwd.equals(new StringBuilder(fwd).reverse().toString()); } }
- package com.mystuff.juststuff;
import java.text.*;import java.util.*;- import java.util.Set;
- import java.util.SortedSet;
- import java.util.TreeSet;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.time.temporal.ChronoUnit;
- public class Palindrome {
private static final SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyy");- private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddyyyy");
public Set<Date> countDatePalindromes(final Date startDate, final Date endDate) {final Set<Date> set = new TreeSet<>();final GregorianCalendar startCal = new GregorianCalendar();final GregorianCalendar endCal = new GregorianCalendar();// If end date is before start date, flip them.startCal.setTime(startDate.before(endDate) ? startDate : endDate);endCal.setTime(startDate.after(endDate) ? startDate : endDate);for (; startCal.before(endCal) || startCal.equals(endCal); startCal.add(Calendar.DAY_OF_MONTH, 1)) {final String forward = sdf.format(startCal.getTime());final String back = new StringBuilder(forward).reverse().toString();if (forward.equals(back)) {set.add(startCal.getTime()); // Date string looks same both ways}}return set;}}- public Set<LocalDate> countDatePalindromes(final LocalDate startDate, final LocalDate endDate) {
- final SortedSet<LocalDate> sortedDates = Stream.of(startDate, endDate).collect(Collectors.toCollection(TreeSet::new));
- return Stream.iterate(sortedDates.first(), date -> date.plusDays(1))
- .limit(ChronoUnit.DAYS.between(sortedDates.first(), sortedDates.last().plusDays(1)))
- .filter(Palindrome::isPalindrome)
- .collect(Collectors.toCollection(TreeSet::new));
- }
- private static boolean isPalindrome(final LocalDate date) {
- final String fwd = date.format(formatter);
- return fwd.equals(new StringBuilder(fwd).reverse().toString());
- }
- }
package com.mystuff.juststuff; import static org.junit.Assert.assertTrue; import java.util.Set; import java.time.LocalDate; 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); } @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); } @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); } }
- package com.mystuff.juststuff;
- import static org.junit.Assert.assertTrue;
import java.util.Date;import java.util.GregorianCalendar;- import java.util.Set;
- import java.time.LocalDate;
- import org.junit.Test;
public class PalindromeTest{- public class PalindromeTest {
- @Test
public void testCountDatePalindromesEndDateBeforeStartDate(){GregorianCalendar startCalTest = new GregorianCalendar(2001, 11, 1);GregorianCalendar endCalTest = new GregorianCalendar(2001, 0, 31);Date startDate = new Date(startCalTest.getTimeInMillis());Date endDate = new Date(endCalTest.getTimeInMillis());Palindrome drome = new Palindrome();Set<Date> palSet = drome.countDatePalindromes(startDate, endDate);- 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(){GregorianCalendar startCalTest = new GregorianCalendar(2001, 0, 1);GregorianCalendar endCalTest = new GregorianCalendar(2001, 11, 31);Date startDate = new Date(startCalTest.getTimeInMillis());Date endDate = new Date(endCalTest.getTimeInMillis());Palindrome drome = new Palindrome();Set<Date> palSet = drome.countDatePalindromes(startDate, endDate);- 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(){GregorianCalendar startCalTest = new GregorianCalendar(2001, 11, 31); // Nov 31, 2001 is not a palindrome dateGregorianCalendar endCalTest = new GregorianCalendar(2001, 11, 31);Date startDate = new Date(startCalTest.getTimeInMillis());Date endDate = new Date(endCalTest.getTimeInMillis());Palindrome drome = new Palindrome();Set<Date> palSet = drome.countDatePalindromes(startDate, endDate);- 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);
- }
- @Test
public void testCountDatePalindromesStartDateEqualsEndDateOnePalindrome(){GregorianCalendar startCalTest = new GregorianCalendar(2001, 9, 2); // Oct 2, 2001 is a palindrome dateGregorianCalendar endCalTest = new GregorianCalendar(2001, 9, 2);Date startDate = new Date(startCalTest.getTimeInMillis());Date endDate = new Date(endCalTest.getTimeInMillis());Palindrome drome = new Palindrome();Set<Date> palSet = drome.countDatePalindromes(startDate, endDate);- 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);
- }
- @Test
public void testCountDatePalindromesHugeDateRange(){GregorianCalendar startCalTest = new GregorianCalendar(1900, 0, 1);GregorianCalendar endCalTest = new GregorianCalendar(2001, 11, 31);Date startDate = new Date(startCalTest.getTimeInMillis());Date endDate = new Date(endCalTest.getTimeInMillis());Palindrome drome = new Palindrome();Set<Date> palSet = drome.countDatePalindromes(startDate, endDate);- 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);
- }
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);
- }
- }
Changing "if n % i == 0" on line 6 to "if not(n % i)" made the time drop from 4126ms to 3810ms (as the longest time).
from math import sqrt, floor def divisors(n): fact = []; for i in range(1, int(floor(sqrt(n))) + 1): if not(n % i): fact.append(i) if n / i != i: fact.append(n / i) fact.sort() return fact
- from math import sqrt, floor
- def divisors(n):
- fact = [];
- for i in range(1, int(floor(sqrt(n))) + 1):
if n % i == 0:- if not(n % i):
- fact.append(i)
- if n / i != i:
- fact.append(n / i)
- fact.sort()
- return fact
from math import sqrt, floor def divisors_check(n): fact = []; for i in range(1, int(floor(sqrt(n))) + 1): if not(n % i): fact.append(i) if n / i != i: fact.append(n / i) fact.sort() return fact test.describe( "Static Cases" ) test.it( "n = 200" ) test.assert_equals(divisors(200), [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200]) test.it( "n = 560") test.assert_equals(divisors(560), [1, 2, 4, 5, 7, 8, 10, 14, 16, 20, 28, 35, 40, 56, 70, 80, 112, 140, 280, 560]) test.it("n = 755") test.assert_equals(divisors(755), [1, 5, 151, 755]) from random import randint test.describe( "Random Tests") test.it ("More than 1000 Random Tests with challenging values up to 1000000000(10e9)") for h in range(0,1000): n = randint(1000, 1000000000) result = divisors_check(n) res = divisors(n) test.it("Testing for = " + str(n)) test.assert_equals(res, result)
- from math import sqrt, floor
- def divisors_check(n):
- fact = [];
- for i in range(1, int(floor(sqrt(n))) + 1):
if n % i == 0:- if not(n % i):
- fact.append(i)
- if n / i != i:
- fact.append(n / i)
- fact.sort()
- return fact
- test.describe( "Static Cases" )
- test.it( "n = 200" )
- test.assert_equals(divisors(200), [1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200])
- test.it( "n = 560")
- test.assert_equals(divisors(560), [1, 2, 4, 5, 7, 8, 10, 14, 16, 20, 28, 35, 40, 56, 70, 80, 112, 140, 280, 560])
- test.it("n = 755")
- test.assert_equals(divisors(755), [1, 5, 151, 755])
- from random import randint
- test.describe( "Random Tests")
- test.it ("More than 1000 Random Tests with challenging values up to 1000000000(10e9)")
- for h in range(0,1000):
- n = randint(1000, 1000000000)
- result = divisors_check(n)
- res = divisors(n)
- test.it("Testing for = " + str(n))
- test.assert_equals(res, result)