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.
Description
You will be given a String which will be composed of different groups of letters and numbers separated by a blank space. You will have to calculate for each group whether the value of the sum of the letters is greater, equal or less than the multiplication of the numbers. The value of each letter corresponds to its position in the alphabet so a=1, b=2, c=3 ... x=24, y=25 and z=26. If there are more groups that have a greater numeric value you will return 1. If the alphabetic value is greater for more groups, you will return -1. If there are the same number of groups with greater numeric and alphabetic values, you will return 0.
Example:
("12345 9812") -> 1
("abc def") -> -1
("abcdef 12345") -> 0 since the first group has a greater letter value and the second group has a greater numeric value
("a1b2c3") -> 0 since the sum of the letters (1(a)+2(b)+3(c)) is equal to the multiplication of the numbers (1*2*3)
Notes:
- There won't be any uppercase letters
- Special characters such as # or $ do not have any value
- There might be empty Strings
import static org.junit.jupiter.api.Assertions.*; import java.util.HashMap; import java.util.Random; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; class Tests { final String allChars = "abcdefghijklmnopqrstuvwxyz1234567890"; @Test void test() { assertEquals(1,NumbersVsLetters.numbersVsLetters("12345 98212")); assertEquals(1,NumbersVsLetters.numbersVsLetters("9999")); assertEquals(-1,NumbersVsLetters.numbersVsLetters("abcdefg")); assertEquals(-1,NumbersVsLetters.numbersVsLetters("zzzzzzz213 9ppppopppo2")); assertEquals(0,NumbersVsLetters.numbersVsLetters("abcdef 12345")); } @Test void hiddenTest() { assertEquals(0,NumbersVsLetters.numbersVsLetters("")); assertEquals(0,NumbersVsLetters.numbersVsLetters(" ")); assertEquals(0,NumbersVsLetters.numbersVsLetters("a1")); assertEquals(1,NumbersVsLetters.numbersVsLetters("a1b2c3 d4e5f6")); assertEquals(0,NumbersVsLetters.numbersVsLetters("a1b2c3 5y5")); assertEquals(0,NumbersVsLetters.numbersVsLetters("a1b2c3 5y5")); assertEquals(0,NumbersVsLetters.numbersVsLetters("5y5 a1b2c3 ")); assertEquals(1,NumbersVsLetters.numbersVsLetters("9%$@")); assertEquals(-1,NumbersVsLetters.numbersVsLetters("~$@#a")); assertEquals(0,NumbersVsLetters.numbersVsLetters("~$@#")); assertEquals(0,NumbersVsLetters.numbersVsLetters("0")); } @RepeatedTest(100) void randomTests() { String randomString = generateRandomString(); assertEquals(KataSolution.sol(randomString),NumbersVsLetters.numbersVsLetters(randomString )); } private String generateRandomString() { Random rnd = new Random(); StringBuilder randomString = new StringBuilder(); int finalStringLength =rnd.nextInt(100); for(int i=0;i<finalStringLength;i++) { int currentWordLength = rnd.nextInt(20); for(int j=0;j<currentWordLength;j++) { randomString.append(allChars.charAt(rnd.nextInt(36))).append(" "); } } return randomString.toString().trim(); } }
- import static org.junit.jupiter.api.Assertions.*;
- import java.util.HashMap;
- import java.util.Random;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Test;
- class Tests {
- final String allChars = "abcdefghijklmnopqrstuvwxyz1234567890";
- @Test
- void test() {
- assertEquals(1,NumbersVsLetters.numbersVsLetters("12345 98212"));
- assertEquals(1,NumbersVsLetters.numbersVsLetters("9999"));
- assertEquals(-1,NumbersVsLetters.numbersVsLetters("abcdefg"));
- assertEquals(-1,NumbersVsLetters.numbersVsLetters("zzzzzzz213 9ppppopppo2"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("abcdef 12345"));
- }
- @Test
- void hiddenTest() {
- assertEquals(0,NumbersVsLetters.numbersVsLetters(""));
- assertEquals(0,NumbersVsLetters.numbersVsLetters(" "));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("a1"));
- assertEquals(1,NumbersVsLetters.numbersVsLetters("a1b2c3 d4e5f6"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("a1b2c3 5y5"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("a1b2c3 5y5"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("5y5 a1b2c3 "));
- assertEquals(1,NumbersVsLetters.numbersVsLetters("9%$@"));
- assertEquals(-1,NumbersVsLetters.numbersVsLetters("~$@#a"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("~$@#"));
- assertEquals(0,NumbersVsLetters.numbersVsLetters("0"));
- }
- @RepeatedTest(100)
- void randomTests() {
- String randomString = generateRandomString();
- assertEquals(KataSolution.sol(randomString),NumbersVsLetters.numbersVsLetters(randomString ));
- }
- private String generateRandomString() {
- Random rnd = new Random();
- StringBuilder randomString = new StringBuilder();
int finalStringLength =(int) (Math.random() * 100);- int finalStringLength =rnd.nextInt(100);
- for(int i=0;i<finalStringLength;i++) {
int currentWordLength = (int) (Math.random() * 20);- int currentWordLength = rnd.nextInt(20);
- for(int j=0;j<currentWordLength;j++) {
randomString.append(allChars.charAt((int)(Math.random() * 35))).append(" ");- randomString.append(allChars.charAt(rnd.nextInt(36))).append(" ");
- }
- }
- return randomString.toString().trim();
- }
- }
Task:
Write a program that takes as input an array of integers representing the durations in seconds of the songs in a concert, and returns the maximum number of seconds whose total duration approximates or equals a minimum of 50 minutes and a maximum of 60 minutes (including the additional minute between each song).
Input:
An array of integers representing the durations in seconds of the songs in the concert.
Output:
An integer representing the maximum number of songs that can be included in the concert, according to the criteria mentioned above.
Example:
1º Array with song durations: [240, 300, 180, 360, 120, 240, 300, 240, 180, 240]. Total duration: 49 minutes (Does not meet the minimum of 50 minutes)
2º Array with song durations: [420, 180, 360, 240, 120, 240, 300, 180]. Total duration: 59 minutes and 15 seconds (Meets the criteria)
3º Array with song durations: [300, 240, 480, 180, 240, 240, 300, 360]. Total duration: 57 minutes and 40 seconds (Meets the criteria)
Note:
- The input array must not be null or empty.
- The song durations must be positive integers.
- The program must consider the additional minute between each song when calculating the total duration of the concert.
Good luck!
public class HowManySongYouCanPlay { public static String playSongs(Integer[] songDuration) { return ""; } }
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"); } }
class KumiteFoo: def __init__(self, p): self.p = p self.condition = ['No', 'Yes'][len(self.p) and not sum(map(ord, self.p.lower())) % 324] def solution(self): return self.condition
- class KumiteFoo:
- def __init__(self, p):
- self.p = p
self.condition = 'Yes' if len(self.p) and not sum(map(ord, self.p.lower())) % 324 else 'No'- self.condition = ['No', 'Yes'][len(self.p) and not sum(map(ord, self.p.lower())) % 324]
- def solution(self):
- return self.condition
class TemperatureConverter: def __init__(self, temp): self.temp = temp self._k1 = 5 / 9 self._k2 = self._k1 * 32 def fahrenheit_to_celsius(self): return round(self.temp * self._k1 - self._k2, 2) def celsius_to_fahrenheit(self): return round((self.temp + self._k2) / self._k1, 2)
- class TemperatureConverter:
- def __init__(self, temp):
- self.temp = temp
- self._k1 = 5 / 9
- self._k2 = self._k1 * 32
- def fahrenheit_to_celsius(self):
return round((self.temp - 32) * 5 / 9, 2)- return round(self.temp * self._k1 - self._k2, 2)
- def celsius_to_fahrenheit(self):
return round((self.temp * 9 / 5) + 32, 2)- return round((self.temp + self._k2) / self._k1, 2)
def flat_the_list(lst): def flatten(l): for i in l: if isinstance(i, (list, tuple)): for j in flat_the_list(i): yield j else: yield i return list(flatten(lst))
def flat_the_list(item_list):return [subitem for item in item_list for subitem in item]- def flat_the_list(lst):
- def flatten(l):
- for i in l:
- if isinstance(i, (list, tuple)):
- for j in flat_the_list(i):
- yield j
- else:
- yield i
- return list(flatten(lst))
import codewars_test as test from solution import flat_the_list @test.describe("flat_list") def test_group(): @test.it("basic test case") def basic_test_case(): test.assert_equals(flat_the_list([[1,2,3], [4,5,6], [7,8,9]]), [1,2,3,4,5,6,7,8,9]) test.assert_equals(flat_the_list([[0], [1,2,3], [4,5,6,7], [8,9]]), [0,1,2,3,4,5,6,7,8,9]) test.assert_equals(flat_the_list([[], [], []]), []) test.assert_equals(flat_the_list(['eat', (0, ([1, 2, [3, [['sleep', [[4]]]]], (((6,),),), 'code', 7, [[[8]]], 9]),), 'repeat']),['eat', 0, 1, 2, 3, 'sleep', 4, 6, 'code', 7, 8, 9, 'repeat'])
- import codewars_test as test
- from solution import flat_the_list
- @test.describe("flat_list")
- def test_group():
- @test.it("basic test case")
- def basic_test_case():
- test.assert_equals(flat_the_list([[1,2,3], [4,5,6], [7,8,9]]), [1,2,3,4,5,6,7,8,9])
- test.assert_equals(flat_the_list([[0], [1,2,3], [4,5,6,7], [8,9]]), [0,1,2,3,4,5,6,7,8,9])
test.assert_equals(flat_the_list([[], [], []]), [])- test.assert_equals(flat_the_list([[], [], []]), [])
- test.assert_equals(flat_the_list(['eat', (0, ([1, 2, [3, [['sleep', [[4]]]]], (((6,),),), 'code', 7, [[[8]]], 9]),), 'repeat']),['eat', 0, 1, 2, 3, 'sleep', 4, 6, 'code', 7, 8, 9, 'repeat'])
import java.util.regex.*; import java.util.Arrays; import java.util.Comparator; public class NamesAndNumbers{ public static String run(int[]numbers, String[] names){ if(numbers == null || names == null) { return "array is null"; } else if(numbers.length == 0 || names.length == 0) { return "length is zero"; } Arrays.sort(names, Comparator.comparingInt(String::length)); Arrays.sort(numbers); StringBuilder cadenaValue = new StringBuilder(); for(int i = 0; i<names.length; i++) { cadenaValue.append(names[i]).append(":").append(numbers[i]).append(","); } cadenaValue.deleteCharAt(cadenaValue.length() - 1); String outputValue = cadenaValue.toString(); return outputValue; } }//end class.
- import java.util.regex.*;
- import java.util.Arrays;
- import java.util.Comparator;
- public class NamesAndNumbers{
- public static String run(int[]numbers, String[] names){
String outputValue = "error";- if(numbers == null || names == null) {
- return "array is null";
- } else if(numbers.length == 0 || names.length == 0) {
- return "length is zero";
- }
return outputValue;- Arrays.sort(names, Comparator.comparingInt(String::length));
- Arrays.sort(numbers);
- StringBuilder cadenaValue = new StringBuilder();
- for(int i = 0; i<names.length; i++) {
- cadenaValue.append(names[i]).append(":").append(numbers[i]).append(",");
- }
- cadenaValue.deleteCharAt(cadenaValue.length() - 1);
- String outputValue = cadenaValue.toString();
- return outputValue;
- }
- }//end class.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; class SolutionTest { @Test void lengthIsntZeroTest() { assertEquals("length is zero", NamesAndNumbers.run(new int[1], new String[0])); assertNotEquals("length is zero", NamesAndNumbers.run(new int[1], new String[1])); } @Test void arrayIsntNullTest() { String[]arrStr = null; assertEquals("array is null", NamesAndNumbers.run(new int[1], arrStr)); assertNotEquals("array is null", NamesAndNumbers.run(new int[1], new String[1])); } @Test void syntaxTest() { int[] numbers = {10, 37, 23, 49, 42}; String[] names = {"Juan", "María", "Pedro", "Ana", "Luisa"}; assertEquals("Ana:10,Juan:23,María:37,Pedro:42,Luisa:49", NamesAndNumbers.run(numbers, names)); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.jupiter.api.Assertions.assertNotEquals;
- class SolutionTest {
- @Test
- void lengthIsntZeroTest() {
- assertEquals("length is zero", NamesAndNumbers.run(new int[1], new String[0]));
- assertNotEquals("length is zero", NamesAndNumbers.run(new int[1], new String[1]));
- }
- @Test
- void arrayIsntNullTest() {
- String[]arrStr = null;
- assertEquals("array is null", NamesAndNumbers.run(new int[1], arrStr));
- assertNotEquals("array is null", NamesAndNumbers.run(new int[1], new String[1]));
- }
- @Test
- void syntaxTest() {
- int[] numbers = {10, 37, 23, 49, 42};
- String[] names = {"Juan", "María", "Pedro", "Ana", "Luisa"};
- assertEquals("Ana:10,Juan:23,María:37,Pedro:42,Luisa:49", NamesAndNumbers.run(numbers, names));
- }
- }
public class ConfusedDouble { public static String clearDouble(String str) { if (str == null || str.length() == 0 || str.matches("^[^.]*$")){ return ""; } String ret = str.replaceAll("[^0-9.]", ""); if(ret.length() == 1) return ""; return ret; } }
//hacer que no funcione con una expresion regular con el caracter fin de cadena- public class ConfusedDouble {
public static String clearDouble(String str) {- public static String clearDouble(String str) {
- if (str == null || str.length() == 0 || str.matches("^[^.]*$")){
return "";}double num = Double.parseDouble(str.replaceAll("[^0-9.]", ""));String result = Double.toString(num);return result;- return "";
- }
- String ret = str.replaceAll("[^0-9.]", "");
- if(ret.length() == 1) return "";
- return ret;
- }
- }
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Random; import org.junit.jupiter.api.Tag; class ConfusedDoubleTest { @Test @Tag("SampleTests") void SampleTests() { assertEquals("523.8822", ConfusedDouble.clearDouble("d5fjhjed`´<23.882fhhjk2")); assertEquals("3.15", ConfusedDouble.clearDouble("sakd3xH>Q;_r.wB1==5")); assertEquals("", ConfusedDouble.clearDouble("djasfkhkcnksnd12346gfkdj")); assertEquals("", ConfusedDouble.clearDouble("95847352414153884")); } @Test @Tag("EmptyDoubleTest") void emptyDoubleTest() { assertEquals("", ConfusedDouble.clearDouble(".")); } @Test @Tag("NullityTest") void nullityTest() { assertEquals("", ConfusedDouble.clearDouble(null)); } @Test @Tag("EmptyStringTest") void emptyTest() { assertEquals("", ConfusedDouble.clearDouble("")); } @Test @Tag("RandomTests") void randomTest() { //Tests for a random generated String 50 times Random r = new Random(); for(int j = 0; j < 50; ++j) { StringBuilder sb = new StringBuilder(); int i = 0; //Creates a string of 100 random characters from ASCII table while(i < 100) { int numAscii = r.nextInt(256); if(numAscii != 46) {//46 - point in ASCII table sb.append((char)numAscii); i++; } } sb.insert(r.nextInt(sb.length()), '.'); String randomText = sb.toString(); assertEquals(Kata.clearDouble(randomText), ConfusedDouble.clearDouble(randomText)); } } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import java.util.Random;
- import org.junit.jupiter.api.Tag;
- class ConfusedDoubleTest {
- @Test
- @Tag("SampleTests")
- void SampleTests() {
//assertEquals("expected", "actual");- assertEquals("523.8822", ConfusedDouble.clearDouble("d5fjhjed`´<23.882fhhjk2"));
- assertEquals("3.15", ConfusedDouble.clearDouble("sakd3xH>Q;_r.wB1==5"));
- assertEquals("", ConfusedDouble.clearDouble("djasfkhkcnksnd12346gfkdj"));
- assertEquals("", ConfusedDouble.clearDouble("95847352414153884"));
assertEquals("", ConfusedDouble.clearDouble(""));- }
- @Test
- @Tag("EmptyDoubleTest")
- void emptyDoubleTest() {
- assertEquals("", ConfusedDouble.clearDouble("."));
- }
- @Test
- @Tag("NullityTest")
- void nullityTest() {
- assertEquals("", ConfusedDouble.clearDouble(null));
- }
- @Test
- @Tag("EmptyStringTest")
- void emptyTest() {
- assertEquals("", ConfusedDouble.clearDouble(""));
- }
- @Test
- @Tag("RandomTests")
- void randomTest() {
//creates a string of 100 random characters from ASCII table- //Tests for a random generated String 50 times
- Random r = new Random();
StringBuilder sb = new StringBuilder();int i = 0;while(i < 100) {int numAscii = r.nextInt(256);if(numAscii != 46) {//46 - point in ASCII tablesb.append((char)numAscii);i++;- for(int j = 0; j < 50; ++j) {
- StringBuilder sb = new StringBuilder();
- int i = 0;
- //Creates a string of 100 random characters from ASCII table
- while(i < 100) {
- int numAscii = r.nextInt(256);
- if(numAscii != 46) {//46 - point in ASCII table
- sb.append((char)numAscii);
- i++;
- }
- }
- sb.insert(r.nextInt(sb.length()), '.');
- String randomText = sb.toString();
- assertEquals(Kata.clearDouble(randomText), ConfusedDouble.clearDouble(randomText));
- }
- }
sb.insert(r.nextInt(sb.length()), '.');String randomText = sb.toString();assertEquals(Kata.clearDouble(randomText), ConfusedDouble.clearDouble(randomText));}- }
Replace Letter
Given a string and a number (n), generate an array in which each position will be that same string but modifying the letter of its first position (0) by the one in its n position.
Input:
hello, 2
Output:
[lello, hollo, hehlo, heleo, helll]
Restrictions:
-
where n will always be a number between 0 and the length of the string.
-
It is case-insensitive and does not discriminate between letters, numbers, and special characters.
-
When current position + n is greater than the length of the string, it will return to start.
-
The spaces will be considered:
- If there is a space, that position will not be replaced.
- The space will not replace any letter.
For example
Given the string = "hello world"
and n=1
Should return:
[eello world, Hlllo world, Hello world, Heloo world, Hello oorld, Hello wrrld, Hello wolld, Hello wordd, Hello worlH]
It would not admit:
hellowword
hell word
import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; public class Kata{ public static String[] replaceLetter(String str, int n) { ArrayList<String> arr = new ArrayList<>(); StringBuilder strFinal = new StringBuilder(str); for (int i = 0; i < str.length(); i++) { int nextIndex = (i + n) % str.length() ; if (str.charAt(i) != ' ' && str.charAt(nextIndex) != ' ') { nextIndex = (i + n) % str.length(); strFinal.replace(i, i + 1, String.valueOf(str.charAt(nextIndex))); arr.add(strFinal.toString()); strFinal.replace(0, str.length(), str); } } return arr.toArray(new String[arr.size()]); } }
- import java.text.ParseException;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.Random;
- import java.util.concurrent.ThreadLocalRandom;
- public class Kata{
- public static String[] replaceLetter(String str, int n) {
- ArrayList<String> arr = new ArrayList<>();
- StringBuilder strFinal = new StringBuilder(str);
- for (int i = 0; i < str.length(); i++) {
- int nextIndex = (i + n) % str.length() ;
- if (str.charAt(i) != ' ' && str.charAt(nextIndex) != ' ') {
- nextIndex = (i + n) % str.length();
- strFinal.replace(i, i + 1, String.valueOf(str.charAt(nextIndex)));
- arr.add(strFinal.toString());
- strFinal.replace(0, str.length(), str);
- }
- }
String[] array = arr.toArray(new String[arr.size()]);return array;- return arr.toArray(new String[arr.size()]);
- }
- }
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import java.util.Random; import java.util.ArrayList; // TODO: Replace examples and use TDD by writing your own tests class SolutionTest { @Test @Tag("BasicTest") void BasicTest() { String[] reverseLeterHello = { "lello", "hollo", "hehlo", "heleo", "helll" }; String[] reverseLeterBye = { "eye", "bbe", "byy" }; String[] reverseLeterCodewars = { "oello codewars", "hdllo codewars", "heelo codewars", "helwo codewars", "hella codewars", "hello sodewars", "hello chdewars", "hello coeewars", "hello codlwars", "hello codelars", "hello codewors", "hello codewarc" }; String[] reverseLeterThanks = { "Thanks", "Thanks", "Thanks", "Thanks", "Thanks", "Thanks" }; assertArrayEquals(reverseLeterHello, Kata.replaceLetter("hello", 3)); assertArrayEquals(reverseLeterBye, Kata.replaceLetter("bye", 2)); assertArrayEquals(reverseLeterCodewars, Kata.replaceLetter("hello codewars", 7)); assertArrayEquals(reverseLeterThanks, Kata.replaceLetter("Thanks", 0)); } @Test @Tag("SpecialCase") void SpecialCase() { String[] reverseLeterVoid = {}; assertArrayEquals(reverseLeterVoid, Kata.replaceLetter("", 2)); assertArrayEquals(reverseLeterVoid, Kata.replaceLetter(" ", 2)); assertArrayEquals(reverseLeterVoid, Kata.replaceLetter(" ", 0)); } @Tag("RandomTest") @RepeatedTest(10) @DisplayName("RandomWord") void RandomTest() { String word = generate(new Random().nextInt(15) + 1); int letterRandom = new Random().nextInt(word.length()); assertArrayEquals(replaceLetter(word, letterRandom), Kata.replaceLetter(word, letterRandom)); } public static String generate(int length) { String strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ^*¨_:;=?¿"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { int nRandom = new Random().nextInt(strChars.length()); sb.append(strChars.charAt(nRandom)); } return sb.toString(); } public static String[] replaceLetter(String str, int n) { ArrayList<String> arr = new ArrayList<>(); StringBuilder strFinal = new StringBuilder(str); for (int i = 0; i < str.length(); i++) { int nextIndex = (i + n) % str.length(); if (str.charAt(i) != ' ' && str.charAt(nextIndex) != ' ') { nextIndex = (i + n) % str.length(); strFinal.replace(i, i + 1, String.valueOf(str.charAt(nextIndex))); arr.add(strFinal.toString()); strFinal.replace(0, str.length(), str); } } String[] array = arr.toArray(new String[arr.size()]); return array; } }
- import static org.junit.jupiter.api.Assertions.*;
- import org.junit.jupiter.api.DisplayName;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Tag;
- import org.junit.jupiter.api.Test;
- import java.util.Random;
- import java.util.ArrayList;
- // TODO: Replace examples and use TDD by writing your own tests
- class SolutionTest {
- @Test
- @Tag("BasicTest")
- void BasicTest() {
- String[] reverseLeterHello = { "lello", "hollo", "hehlo", "heleo", "helll" };
- String[] reverseLeterBye = { "eye", "bbe", "byy" };
- String[] reverseLeterCodewars = { "oello codewars", "hdllo codewars", "heelo codewars", "helwo codewars",
- "hella codewars", "hello sodewars", "hello chdewars", "hello coeewars", "hello codlwars",
- "hello codelars", "hello codewors", "hello codewarc" };
- String[] reverseLeterThanks = { "Thanks", "Thanks", "Thanks", "Thanks", "Thanks", "Thanks" };
- assertArrayEquals(reverseLeterHello, Kata.replaceLetter("hello", 3));
- assertArrayEquals(reverseLeterBye, Kata.replaceLetter("bye", 2));
- assertArrayEquals(reverseLeterCodewars, Kata.replaceLetter("hello codewars", 7));
- assertArrayEquals(reverseLeterThanks, Kata.replaceLetter("Thanks", 0));
- }
- @Test
- @Tag("SpecialCase")
- void SpecialCase() {
- String[] reverseLeterVoid = {};
- assertArrayEquals(reverseLeterVoid, Kata.replaceLetter("", 2));
- assertArrayEquals(reverseLeterVoid, Kata.replaceLetter(" ", 2));
- assertArrayEquals(reverseLeterVoid, Kata.replaceLetter(" ", 0));
- }
@Test@Tag("UnitTest")void parseExceptionFecha() {assertThrows(NullPointerException.class, () -> {int nRandom = new Random().nextInt(15)+1;Kata.replaceLetter(null, nRandom);});}- @Tag("RandomTest")
- @RepeatedTest(10)
- @DisplayName("RandomWord")
- void RandomTest() {
- String word = generate(new Random().nextInt(15) + 1);
- int letterRandom = new Random().nextInt(word.length());
- assertArrayEquals(replaceLetter(word, letterRandom), Kata.replaceLetter(word, letterRandom));
- }
- public static String generate(int length) {
String strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";- String strChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 ^*¨_:;=?¿";
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < length; i++) {
- int nRandom = new Random().nextInt(strChars.length());
- sb.append(strChars.charAt(nRandom));
- }
- return sb.toString();
- }
- public static String[] replaceLetter(String str, int n) {
- ArrayList<String> arr = new ArrayList<>();
- StringBuilder strFinal = new StringBuilder(str);
- for (int i = 0; i < str.length(); i++) {
- int nextIndex = (i + n) % str.length();
- if (str.charAt(i) != ' ' && str.charAt(nextIndex) != ' ') {
- nextIndex = (i + n) % str.length();
- strFinal.replace(i, i + 1, String.valueOf(str.charAt(nextIndex)));
- arr.add(strFinal.toString());
- strFinal.replace(0, str.length(), str);
- }
- }
- String[] array = arr.toArray(new String[arr.size()]);
- return array;
- }
- }