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.
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Random; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; class SolutionTest { // Today's date private static final String TODAY_DATE = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); // String of all available characters private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_@#$&0123456789"; // Diminutive of the months private static final String[] VALID_MONTHS = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; // List of all possible lengths. Prime numbers are more than once so they appear // more often private static final int[] LENGTHS = { 20, 21, 22, 23, 23, 23, 23, 23, 24, 25, 26, 27, 28, 29, 29, 29, 29, 29, 30, 31, 31, 31, 31, 31, 32, 33, 34, 35, 36, 37, 37, 37, 37, 37, 38, 39, 40, 41, 41, 41, 41, 41, 42, 43, 43, 43, 43, 43, 44, 45, 46, 47, 47, 47, 47, 47, 48, 49, 50 }; @Test void basicTest() { assertFalse(PasswordValidation.validatePassword("")); assertTrue(PasswordValidation.validatePassword("pass73$OCT" + TODAY_DATE + "len23")); assertFalse(PasswordValidation.validatePassword("PASS73$OCT" + TODAY_DATE + "LEN23")); assertFalse(PasswordValidation.validatePassword("TOdaY" + TODAY_DATE + ".feb29P6g@#fahHl")); assertFalse(PasswordValidation.validatePassword("sib$dic&omonUl98DSA" + TODAY_DATE + "len17shJDAIDB78334&Okk.53jfh")); assertTrue(PasswordValidation.validatePassword("dskjRUE3576&sj_88@mAyJun" + TODAY_DATE + "JUL47.1j6SB2nI7")); } @Test void largestBasicTest() { String randomDay = LocalDate.now().plusDays(2).format(DateTimeFormatter.ofPattern("yyyyMMdd")); assertTrue(PasswordValidation.validatePassword("TOdaY" + TODAY_DATE + ".feb29P6gwo@fahH")); assertTrue(PasswordValidation.validatePassword("h&ks-KlOCt" + TODAY_DATE + "#aai78Ho37M7M_lj73.")); assertTrue(PasswordValidation.validatePassword(TODAY_DATE + "&jUN1.df487-ks228d43#hULP0@cb111baQ")); assertFalse(PasswordValidation.validatePassword("k17DiC9@P" + TODAY_DATE)); assertFalse(PasswordValidation.validatePassword("hJAN" + TODAY_DATE + "&17a9")); assertFalse(PasswordValidation.validatePassword("p6NOv#L17" + TODAY_DATE)); assertFalse(PasswordValidation.validatePassword("MyP@ssworD-67sAloU" + TODAY_DATE + "29o")); assertFalse(PasswordValidation.validatePassword("MyP@sswMAy-67sAlU" + TODAY_DATE + "29o")); assertFalse(PasswordValidation.validatePassword("Lol_sC_apR01" + TODAY_DATE + "nOp")); assertFalse(PasswordValidation.validatePassword(".SiL" + TODAY_DATE + "jUt7190lAUG2f27")); assertFalse(PasswordValidation.validatePassword("JupoJUN43.90-12plUSlenght31$h#1")); assertFalse(PasswordValidation.validatePassword("n0TC84nTeInmar.nn_" + randomDay + "poAl98712mQ")); } public static String generateRandomPass() { Random random = new Random(); StringBuilder pass = new StringBuilder(); int length = LENGTHS[random.nextInt(LENGTHS.length)]; int month_pos = random.nextInt(length - 3); int date_pos = random.nextInt(length); int length_pos = random.nextInt(length - 2); for (int i = 0; i < length; i++) { pass.append(CHARS.charAt(random.nextInt(CHARS.length()))); if (i == month_pos) { pass.append(VALID_MONTHS[random.nextInt(VALID_MONTHS.length)]); i += 3; } if (i == length_pos) { pass.append(length); i += 2; } if (i == date_pos) { pass.append(TODAY_DATE); i += 8; } } return pass.toString(); } public static boolean checkPass(String pass) { if (pass.length() < 20 | pass.length() > 50) return false; if (!isPrime(pass.length())) return false; if (!pass.contains(String.valueOf(pass.length()))) return false; if (!pass.contains(TODAY_DATE)) return false; if (!Arrays.stream(VALID_MONTHS).anyMatch(s -> pass.toLowerCase().contains(s))) return false; if (pass.matches("[A-Z]{0,2}|[^a-z]+|[^-._@#$&]+|.*[-._@#$&][-._@#$&].*")) return false; if (Arrays.stream(pass.split("")).filter(s -> s.matches("[0-9]")).mapToInt(s -> Integer.valueOf(s)).sum() < 25) return false; return true; } public static boolean isPrime(int n) { for (int i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true; } @RepeatedTest(100) void randomTest() { String randomPass = generateRandomPass(); assertEquals(checkPass(randomPass), PasswordValidation.validatePassword(randomPass)); } }
- import org.junit.jupiter.api.Test;
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.Assert.assertFalse;
- import static org.junit.Assert.assertTrue;
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.util.Arrays;
- import java.util.Random;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Test;
- class SolutionTest {
- // Today's date
- private static final String TODAY_DATE = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
- // String of all available characters
- private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.-_@#$&0123456789";
- // Diminutive of the months
- private static final String[] VALID_MONTHS = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" };
- // List of all possible lengths. Prime numbers are more than once so they appear
- // more often
- private static final int[] LENGTHS = { 20, 21, 22, 23, 23, 23, 23, 23, 24, 25, 26, 27, 28, 29, 29, 29, 29, 29, 30,
- 31, 31, 31, 31, 31, 32, 33, 34, 35, 36, 37, 37, 37, 37, 37, 38, 39, 40, 41, 41, 41, 41, 41, 42, 43, 43, 43,
- 43, 43, 44, 45, 46, 47, 47, 47, 47, 47, 48, 49, 50 };
- @Test
- void basicTest() {
- assertFalse(PasswordValidation.validatePassword(""));
- assertTrue(PasswordValidation.validatePassword("pass73$OCT" + TODAY_DATE + "len23"));
- assertFalse(PasswordValidation.validatePassword("PASS73$OCT" + TODAY_DATE + "LEN23"));
- assertFalse(PasswordValidation.validatePassword("TOdaY" + TODAY_DATE + ".feb29P6g@#fahHl"));
- assertFalse(PasswordValidation.validatePassword("sib$dic&omonUl98DSA" + TODAY_DATE + "len17shJDAIDB78334&Okk.53jfh"));
- assertTrue(PasswordValidation.validatePassword("dskjRUE3576&sj_88@mAyJun" + TODAY_DATE + "JUL47.1j6SB2nI7"));
- }
- @Test
- void largestBasicTest() {
- String randomDay = LocalDate.now().plusDays(2).format(DateTimeFormatter.ofPattern("yyyyMMdd"));
- assertTrue(PasswordValidation.validatePassword("TOdaY" + TODAY_DATE + ".feb29P6gwo@fahH"));
- assertTrue(PasswordValidation.validatePassword("h&ks-KlOCt" + TODAY_DATE + "#aai78Ho37M7M_lj73."));
- assertTrue(PasswordValidation.validatePassword(TODAY_DATE + "&jUN1.df487-ks228d43#hULP0@cb111baQ"));
- assertFalse(PasswordValidation.validatePassword("k17DiC9@P" + TODAY_DATE));
- assertFalse(PasswordValidation.validatePassword("hJAN" + TODAY_DATE + "&17a9"));
- assertFalse(PasswordValidation.validatePassword("p6NOv#L17" + TODAY_DATE));
- assertFalse(PasswordValidation.validatePassword("MyP@ssworD-67sAloU" + TODAY_DATE + "29o"));
- assertFalse(PasswordValidation.validatePassword("MyP@sswMAy-67sAlU" + TODAY_DATE + "29o"));
- assertFalse(PasswordValidation.validatePassword("Lol_sC_apR01" + TODAY_DATE + "nOp"));
- assertFalse(PasswordValidation.validatePassword(".SiL" + TODAY_DATE + "jUt7190lAUG2f27"));
- assertFalse(PasswordValidation.validatePassword("JupoJUN43.90-12plUSlenght31$h#1"));
- assertFalse(PasswordValidation.validatePassword("n0TC84nTeInmar.nn_" + randomDay + "poAl98712mQ"));
- }
- public static String generateRandomPass() {
- Random random = new Random();
- StringBuilder pass = new StringBuilder();
- int length = LENGTHS[random.nextInt(LENGTHS.length)];
for (int i = 0; i < length; i++) {int position = random.nextInt(4);switch (position) {case 0 -> pass.append(CHARS.charAt(random.nextInt(CHARS.length())));case 1 -> {int monthIndex = random.nextInt(VALID_MONTHS.length);pass.append(VALID_MONTHS[monthIndex]);i += 2;}case 2 -> {pass.append(length);i++;}case 3 ->{pass.append(TODAY_DATE);i += 7;}}}return pass.toString();- int month_pos = random.nextInt(length - 3);
- int date_pos = random.nextInt(length);
- int length_pos = random.nextInt(length - 2);
- for (int i = 0; i < length; i++) {
- pass.append(CHARS.charAt(random.nextInt(CHARS.length())));
- if (i == month_pos) {
- pass.append(VALID_MONTHS[random.nextInt(VALID_MONTHS.length)]);
- i += 3;
- }
- if (i == length_pos) {
- pass.append(length);
- i += 2;
- }
- if (i == date_pos) {
- pass.append(TODAY_DATE);
- i += 8;
- }
- }
- return pass.toString();
- }
- public static boolean checkPass(String pass) {
- if (pass.length() < 20 | pass.length() > 50)
- return false;
- if (!isPrime(pass.length()))
- return false;
- if (!pass.contains(String.valueOf(pass.length())))
- return false;
- if (!pass.contains(TODAY_DATE))
- return false;
- if (!Arrays.stream(VALID_MONTHS).anyMatch(s -> pass.toLowerCase().contains(s)))
- return false;
- if (pass.matches("[A-Z]{0,2}|[^a-z]+|[^-._@#$&]+|.*[-._@#$&][-._@#$&].*"))
- return false;
- if (Arrays.stream(pass.split("")).filter(s -> s.matches("[0-9]")).mapToInt(s -> Integer.valueOf(s)).sum() < 25)
- return false;
- return true;
- }
- public static boolean isPrime(int n) {
- for (int i = 2; i <= Math.sqrt(n); i++) {
- if (n % i == 0)
- return false;
- }
- return true;
- }
- @RepeatedTest(100)
- void randomTest() {
- String randomPass = generateRandomPass();
- assertEquals(checkPass(randomPass), PasswordValidation.validatePassword(randomPass));
- }
- }
import java.util.List; import java.util.stream.Collectors; public class Kata { // <<-CONSTANTS->> private static final int UpperCase_LOWER_LIMIT = 65; private static final int UpperCase_UPPER_LIMIT = 90; private static final int LowerCase_LOWER_LIMIT = 97; private static final int LowerCase_UPPER_LIMIT = 122; private static final int INTERMEDIATE_OFFSET = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1; // <<-METHODS->> private static int getLastDigit(final int digit) { String str = String.valueOf(digit); str = str.substring(str.length() - 1, str.length()); return Integer.valueOf(str); } private static List<Integer> getEncryptationOffsets(String key) { return key.chars() .map(n -> getLastDigit(n) + key.length()) .boxed() .toList(); } private static List<Integer> getPhraseChars(String phrase) { return phrase.chars() .boxed() .collect(Collectors.toList()); } private static String parseChars(List<Integer> traduction) { return traduction.stream() .map(n -> (char) n.intValue()) .map(c -> Character.toString(c)) .collect(Collectors.joining()); } public static String encode(String phrase, String key) { if (phrase == null || phrase.isEmpty()) return ""; if (key == null || key.isEmpty()) return phrase; List<Integer> offsets = getEncryptationOffsets(key); List<Integer> phraseChars = getPhraseChars(phrase); List<Integer> traduction = new java.util.ArrayList<>(); for (int i = 0; i < phrase.length(); i++) { int keyIndex = i % offsets.size(); int current = phraseChars.get(i); int result = current + offsets.get(keyIndex); if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) { int offset = result - UpperCase_UPPER_LIMIT; result = LowerCase_LOWER_LIMIT + offset - 1; } if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) { result += INTERMEDIATE_OFFSET; } else if (result > LowerCase_UPPER_LIMIT) { result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1; } traduction.add(result); } return parseChars(traduction); } public static String decode(String phrase, String key) { if (phrase == null || phrase.isEmpty()) return ""; if (key == null || key.isEmpty()) return phrase; List<Integer> offsets = getEncryptationOffsets(key); List<Integer> phraseChars = getPhraseChars(phrase); List<Integer> traduction = new java.util.ArrayList<>(); for (int i = 0; i < phrase.length(); i++) { int keyIndex = i % offsets.size(); int current = phraseChars.get(i); int result = current - offsets.get(keyIndex); if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) { int offset = LowerCase_LOWER_LIMIT - result; result = UpperCase_UPPER_LIMIT - offset + 1; } if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) { result -= INTERMEDIATE_OFFSET; } else if (result < UpperCase_LOWER_LIMIT) { int offset = UpperCase_LOWER_LIMIT - result; result = LowerCase_UPPER_LIMIT - offset + 1; } traduction.add(result); } return parseChars(traduction); } }
- import java.util.List;
- import java.util.stream.Collectors;
- public class Kata {
// <<-CONSTANTS->>- // <<-CONSTANTS->>
- private static final int UpperCase_LOWER_LIMIT = 65;
- private static final int UpperCase_UPPER_LIMIT = 90;
- private static final int LowerCase_LOWER_LIMIT = 97;
- private static final int LowerCase_UPPER_LIMIT = 122;
- private static final int INTERMEDIATE_OFFSET = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1;
- // <<-METHODS->>
- private static int getLastDigit(final int digit) {
- String str = String.valueOf(digit);
- str = str.substring(str.length() - 1, str.length());
- return Integer.valueOf(str);
- }
- private static List<Integer> getEncryptationOffsets(String key) {
- return key.chars()
- .map(n -> getLastDigit(n) + key.length())
- .boxed()
- .toList();
- }
- private static List<Integer> getPhraseChars(String phrase) {
- return phrase.chars()
- .boxed()
- .collect(Collectors.toList());
- }
private static String parseChars(List<Integer> translation) {return translation.stream()- private static String parseChars(List<Integer> traduction) {
- return traduction.stream()
- .map(n -> (char) n.intValue())
- .map(c -> Character.toString(c))
- .collect(Collectors.joining());
- }
- public static String encode(String phrase, String key) {
if (phrase == null || phrase.isEmpty() || key == null) return "";if (key.isEmpty()) return phrase;- if (phrase == null || phrase.isEmpty()) return "";
- if (key == null || key.isEmpty()) return phrase;
- List<Integer> offsets = getEncryptationOffsets(key);
- List<Integer> phraseChars = getPhraseChars(phrase);
List<Integer> translation = new java.util.ArrayList<>();- List<Integer> traduction = new java.util.ArrayList<>();
int keyIndex = 0;- for (int i = 0; i < phrase.length(); i++) {
keyIndex = i % offsets.size();- int keyIndex = i % offsets.size();
- int current = phraseChars.get(i);
- int result = current + offsets.get(keyIndex);
- if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) {
- int offset = result - UpperCase_UPPER_LIMIT;
- result = LowerCase_LOWER_LIMIT + offset - 1;
- }
- if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) {
- result += INTERMEDIATE_OFFSET;
- } else if (result > LowerCase_UPPER_LIMIT) {
- result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1;
- }
translation.add(result);keyIndex++;- traduction.add(result);
- }
return parseChars(translation);- return parseChars(traduction);
- }
- public static String decode(String phrase, String key) {
if (phrase == null || phrase.isEmpty() || key == null) return "";if (key.isEmpty()) return phrase;- if (phrase == null || phrase.isEmpty()) return "";
- if (key == null || key.isEmpty()) return phrase;
- List<Integer> offsets = getEncryptationOffsets(key);
- List<Integer> phraseChars = getPhraseChars(phrase);
List<Integer> translation = new java.util.ArrayList<>();- List<Integer> traduction = new java.util.ArrayList<>();
int keyIndex = 0;- for (int i = 0; i < phrase.length(); i++) {
keyIndex = i % offsets.size();- int keyIndex = i % offsets.size();
- int current = phraseChars.get(i);
- int result = current - offsets.get(keyIndex);
- if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) {
- int offset = LowerCase_LOWER_LIMIT - result;
- result = UpperCase_UPPER_LIMIT - offset + 1;
- }
- if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) {
- result -= INTERMEDIATE_OFFSET;
- } else if (result < UpperCase_LOWER_LIMIT) {
- int offset = UpperCase_LOWER_LIMIT - result;
- result = LowerCase_UPPER_LIMIT - offset + 1;
- }
translation.add(result);keyIndex++;- traduction.add(result);
- }
return parseChars(translation);- return parseChars(traduction);
- }
- }
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import java.util.List; import java.util.Random; import java.util.stream.Collectors; class SolutionTest { @Test void basicTest() { assertEquals("moqik", Kata.encode("abcde", "abcde")); assertEquals("abcde", Kata.decode("moqik", "abcde")); assertEquals("KMOQS", Kata.encode("ABCDE", "ABCDE")); assertEquals("ABCDE", Kata.decode("KMOQS", "ABCDE")); assertEquals("GIFUKTG", Kata.encode("DEARGOD", "FGH")); assertEquals("DEARGOD", Kata.decode("GIFUKTG", "FGH")); assertEquals("ikhwmvi", Kata.encode("deargod", "fgh")); assertEquals("deargod", Kata.decode("ikhwmvi", "fgh")); assertEquals("IQlOirL", Kata.encode("ALaBamA", "hoME")); assertEquals("ALaBamA", Kata.decode("IQlOirL", "hoME")); } @Test void specialCasesTest() { assertEquals("", Kata.encode("", "")); assertEquals("TernaryLove", Kata.encode("TernaryLove", "")); assertEquals("", Kata.encode(null, "abcde")); assertEquals("", Kata.encode("", null)); } @Test void fullTestSimpleOverflow() { assertEquals("CEEpB", Kata.encode("turbo", "TUXON")); assertEquals("turbo", Kata.decode("CEEpB", "TUXON")); assertEquals("skstzCvzwj", Kata.encode("helloworld", "afgh")); assertEquals("helloworld", Kata.decode("skstzCvzwj", "afgh")); assertEquals("IKM", Kata.encode("xyz", "ijklmn")); assertEquals("xyz", Kata.decode("IKM", "ijklmn")); assertEquals("qUlWuZXovQ", Kata.encode("gOdMoRNinG", "uSA")); assertEquals("gOdMoRNinG", Kata.decode("qUlWuZXovQ", "uSA")); assertEquals("BOywIJdrzafbLMKuCnVqNt", Kata.encode("wElovETerNaRyExpsaNdIj", "dAvID")); assertEquals("wElovETerNaRyExpsaNdIj", Kata.decode("BOywIJdrzafbLMKuCnVqNt", "dAvID")); } @Test void fullTestIntermediateOverflow() { assertEquals("rhCRDjxXEVyfu", Kata.encode("hOmEsWeEtHoMe", "nOtSoSwEeT")); assertEquals("hOmEsWeEtHoMe", Kata.decode("rhCRDjxXEVyfu", "nOtSoSwEeT")); assertEquals("cyvNMxgiVt", Kata.encode("WonDErWaLl", "oASiS")); assertEquals("WonDErWaLl", Kata.decode("cyvNMxgiVt", "oASiS")); assertEquals("lyynmpA", Kata.encode("Zumbido", "wow")); assertEquals("Zumbido", Kata.decode("lyynmpA", "wow")); } private Random random = new Random(); String generateString(int lowerBound, int upperBound) { return java.util.stream.IntStream.rangeClosed(random.nextInt(lowerBound + 1), random.nextInt(upperBound + 1)) .mapToObj(i -> random.nextInt(2) == 0 ? random.nextInt(65, 91) : random.nextInt(97, 123)) .collect(StringBuilder::new, (sb, code) -> sb.append((char) code.intValue()), StringBuilder::append) .toString(); } String generatePhrase(int lowerBound, int upperBound) { return generateString(lowerBound, upperBound); } String generateKey(int lowerBound, int upperBound) { return generateString(lowerBound, upperBound); } @RepeatedTest(1500) void randomEasyModeTest() { String phrase = generatePhrase(0, 100); String key = generateKey(0, 100); assertEquals(Kata.encode(phrase, key), encode(phrase, key)); assertEquals(Kata.decode(phrase, key), decode(phrase, key)); } @RepeatedTest(1000) void randomHardModeTest() { String phrase = generatePhrase(1000, 15000); String key = generateKey(1000, 15000); assertEquals(Kata.encode(phrase, key), encode(phrase, key)); assertEquals(Kata.decode(phrase, key), decode(phrase, key)); } @RepeatedTest(50) void randomGodModeTest() { String phrase = generatePhrase(89000, 90000); String key = generateKey(79000, 80000); assertEquals(Kata.encode(phrase, key), encode(phrase, key)); assertEquals(Kata.decode(phrase, key), decode(phrase, key)); } // [[ A N S W E R ]] // <<-CONSTANTS->> private static final int UpperCase_LOWER_LIMIT = 65; private static final int UpperCase_UPPER_LIMIT = 90; private static final int LowerCase_LOWER_LIMIT = 97; private static final int LowerCase_UPPER_LIMIT = 122; private static final int INTERMEDIATE_OFFSET = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1; // <<-METHODS->> private static int getLastDigit(final int digit) { String str = String.valueOf(digit); str = str.substring(str.length() - 1, str.length()); return Integer.valueOf(str); } private static List<Integer> getEncryptationOffsets(String key) { return key.chars() .map(n -> getLastDigit(n) + key.length()) .boxed() .toList(); } private static List<Integer> getPhraseChars(String phrase) { return phrase.chars() .boxed() .collect(Collectors.toList()); } private static String parseChars(List<Integer> translation) { return translation.stream() .map(n -> (char) n.intValue()) .map(c -> Character.toString(c)) .collect(Collectors.joining()); } public static String encode(String phrase, String key) { if (phrase == null || phrase.isEmpty()) return ""; if (key == null || key.isEmpty()) return phrase; List<Integer> offsets = getEncryptationOffsets(key); List<Integer> phraseChars = getPhraseChars(phrase); List<Integer> traduction = new java.util.ArrayList<>(); for (int i = 0; i < phrase.length(); i++) { int keyIndex = i % offsets.size(); int current = phraseChars.get(i); int result = current + offsets.get(keyIndex); if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) { int offset = result - UpperCase_UPPER_LIMIT; result = LowerCase_LOWER_LIMIT + offset - 1; } if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) { result += INTERMEDIATE_OFFSET; } else if (result > LowerCase_UPPER_LIMIT) { result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1; } traduction.add(result); } return parseChars(traduction); } public static String decode(String phrase, String key) { if (phrase == null || phrase.isEmpty()) return ""; if (key == null || key.isEmpty()) return phrase; List<Integer> offsets = getEncryptationOffsets(key); List<Integer> phraseChars = getPhraseChars(phrase); List<Integer> traduction = new java.util.ArrayList<>(); for (int i = 0; i < phrase.length(); i++) { int keyIndex = i % offsets.size(); int current = phraseChars.get(i); int result = current - offsets.get(keyIndex); if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) { int offset = LowerCase_LOWER_LIMIT - result; result = UpperCase_UPPER_LIMIT - offset + 1; } if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) { result -= INTERMEDIATE_OFFSET; } else if (result < UpperCase_LOWER_LIMIT) { int offset = UpperCase_LOWER_LIMIT - result; result = LowerCase_UPPER_LIMIT - offset + 1; } traduction.add(result); } return parseChars(traduction); } }
- import static org.junit.jupiter.api.Assertions.*;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Test;
- import java.util.List;
- import java.util.Random;
- import java.util.stream.Collectors;
- class SolutionTest {
- @Test
- void basicTest() {
- assertEquals("moqik", Kata.encode("abcde", "abcde"));
- assertEquals("abcde", Kata.decode("moqik", "abcde"));
- assertEquals("KMOQS", Kata.encode("ABCDE", "ABCDE"));
- assertEquals("ABCDE", Kata.decode("KMOQS", "ABCDE"));
- assertEquals("GIFUKTG", Kata.encode("DEARGOD", "FGH"));
- assertEquals("DEARGOD", Kata.decode("GIFUKTG", "FGH"));
- assertEquals("ikhwmvi", Kata.encode("deargod", "fgh"));
- assertEquals("deargod", Kata.decode("ikhwmvi", "fgh"));
- assertEquals("IQlOirL", Kata.encode("ALaBamA", "hoME"));
- assertEquals("ALaBamA", Kata.decode("IQlOirL", "hoME"));
- }
- @Test
- void specialCasesTest() {
- assertEquals("", Kata.encode("", ""));
- assertEquals("TernaryLove", Kata.encode("TernaryLove", ""));
- assertEquals("", Kata.encode(null, "abcde"));
- assertEquals("", Kata.encode("", null));
- }
- @Test
- void fullTestSimpleOverflow() {
- assertEquals("CEEpB", Kata.encode("turbo", "TUXON"));
- assertEquals("turbo", Kata.decode("CEEpB", "TUXON"));
- assertEquals("skstzCvzwj", Kata.encode("helloworld", "afgh"));
- assertEquals("helloworld", Kata.decode("skstzCvzwj", "afgh"));
- assertEquals("IKM", Kata.encode("xyz", "ijklmn"));
- assertEquals("xyz", Kata.decode("IKM", "ijklmn"));
- assertEquals("qUlWuZXovQ", Kata.encode("gOdMoRNinG", "uSA"));
- assertEquals("gOdMoRNinG", Kata.decode("qUlWuZXovQ", "uSA"));
- assertEquals("BOywIJdrzafbLMKuCnVqNt", Kata.encode("wElovETerNaRyExpsaNdIj", "dAvID"));
- assertEquals("wElovETerNaRyExpsaNdIj", Kata.decode("BOywIJdrzafbLMKuCnVqNt", "dAvID"));
- }
- @Test
- void fullTestIntermediateOverflow() {
- assertEquals("rhCRDjxXEVyfu", Kata.encode("hOmEsWeEtHoMe", "nOtSoSwEeT"));
- assertEquals("hOmEsWeEtHoMe", Kata.decode("rhCRDjxXEVyfu", "nOtSoSwEeT"));
- assertEquals("cyvNMxgiVt", Kata.encode("WonDErWaLl", "oASiS"));
- assertEquals("WonDErWaLl", Kata.decode("cyvNMxgiVt", "oASiS"));
- assertEquals("lyynmpA", Kata.encode("Zumbido", "wow"));
- assertEquals("Zumbido", Kata.decode("lyynmpA", "wow"));
- }
String generateString(int bound) {Random random = new Random();byte[] buffer = new byte[random.nextInt(bound + 1)];random.nextBytes(buffer);return new String(buffer, java.nio.charset.Charset.forName("UTF-8"));}- private Random random = new Random();
- String generateString(int lowerBound, int upperBound) {
- return java.util.stream.IntStream.rangeClosed(random.nextInt(lowerBound + 1), random.nextInt(upperBound + 1))
- .mapToObj(i -> random.nextInt(2) == 0 ? random.nextInt(65, 91) : random.nextInt(97, 123))
- .collect(StringBuilder::new, (sb, code) -> sb.append((char) code.intValue()), StringBuilder::append)
- .toString();
- }
String generatePhrase(int bound) {return generateString(bound);- String generatePhrase(int lowerBound, int upperBound) {
- return generateString(lowerBound, upperBound);
- }
String generateKey(int bound) {return generateString(bound);- String generateKey(int lowerBound, int upperBound) {
- return generateString(lowerBound, upperBound);
- }
- @RepeatedTest(1500)
void randomTestEasyMode() {String phrase = generatePhrase(1500);String key = generateKey(1500);- void randomEasyModeTest() {
- String phrase = generatePhrase(0, 100);
- String key = generateKey(0, 100);
- assertEquals(Kata.encode(phrase, key), encode(phrase, key));
- assertEquals(Kata.decode(phrase, key), decode(phrase, key));
- }
- @RepeatedTest(1000)
void randomTestHardMode() {String phrase = generatePhrase(15000);String key = generateKey(15000);- void randomHardModeTest() {
- String phrase = generatePhrase(1000, 15000);
- String key = generateKey(1000, 15000);
- assertEquals(Kata.encode(phrase, key), encode(phrase, key));
- assertEquals(Kata.decode(phrase, key), decode(phrase, key));
- }
@RepeatedTest(101)void randomTestGodMode() {String phrase = generatePhrase(150000);String key = generateKey(150000);- @RepeatedTest(50)
- void randomGodModeTest() {
- String phrase = generatePhrase(89000, 90000);
- String key = generateKey(79000, 80000);
- assertEquals(Kata.encode(phrase, key), encode(phrase, key));
- assertEquals(Kata.decode(phrase, key), decode(phrase, key));
- }
- // [[ A N S W E R ]]
- // <<-CONSTANTS->>
- private static final int UpperCase_LOWER_LIMIT = 65;
- private static final int UpperCase_UPPER_LIMIT = 90;
- private static final int LowerCase_LOWER_LIMIT = 97;
- private static final int LowerCase_UPPER_LIMIT = 122;
- private static final int INTERMEDIATE_OFFSET = LowerCase_LOWER_LIMIT - UpperCase_UPPER_LIMIT - 1;
- // <<-METHODS->>
- private static int getLastDigit(final int digit) {
- String str = String.valueOf(digit);
- str = str.substring(str.length() - 1, str.length());
- return Integer.valueOf(str);
- }
- private static List<Integer> getEncryptationOffsets(String key) {
- return key.chars()
- .map(n -> getLastDigit(n) + key.length())
- .boxed()
- .toList();
- }
- private static List<Integer> getPhraseChars(String phrase) {
- return phrase.chars()
- .boxed()
- .collect(Collectors.toList());
- }
- private static String parseChars(List<Integer> translation) {
- return translation.stream()
- .map(n -> (char) n.intValue())
- .map(c -> Character.toString(c))
- .collect(Collectors.joining());
- }
- public static String encode(String phrase, String key) {
if (phrase == null || phrase.isEmpty() || key == null) return "";if (key.isEmpty()) return phrase;- if (phrase == null || phrase.isEmpty()) return "";
- if (key == null || key.isEmpty()) return phrase;
- List<Integer> offsets = getEncryptationOffsets(key);
- List<Integer> phraseChars = getPhraseChars(phrase);
List<Integer> translation = new java.util.ArrayList<>();- List<Integer> traduction = new java.util.ArrayList<>();
int keyIndex = 0;- for (int i = 0; i < phrase.length(); i++) {
keyIndex = i % offsets.size();- int keyIndex = i % offsets.size();
- int current = phraseChars.get(i);
- int result = current + offsets.get(keyIndex);
- if (current <= UpperCase_UPPER_LIMIT && result >= LowerCase_LOWER_LIMIT) {
- int offset = result - UpperCase_UPPER_LIMIT;
- result = LowerCase_LOWER_LIMIT + offset - 1;
- }
- if (result > UpperCase_UPPER_LIMIT && result < LowerCase_LOWER_LIMIT) {
- result += INTERMEDIATE_OFFSET;
- } else if (result > LowerCase_UPPER_LIMIT) {
- result = result - LowerCase_UPPER_LIMIT + UpperCase_LOWER_LIMIT - 1;
- }
translation.add(result);keyIndex++;- traduction.add(result);
- }
return parseChars(translation);- return parseChars(traduction);
- }
- public static String decode(String phrase, String key) {
if (phrase == null || phrase.isEmpty() || key == null) return "";if (key.isEmpty()) return phrase;- if (phrase == null || phrase.isEmpty()) return "";
- if (key == null || key.isEmpty()) return phrase;
- List<Integer> offsets = getEncryptationOffsets(key);
- List<Integer> phraseChars = getPhraseChars(phrase);
List<Integer> translation = new java.util.ArrayList<>();- List<Integer> traduction = new java.util.ArrayList<>();
int keyIndex = 0;- for (int i = 0; i < phrase.length(); i++) {
keyIndex = i % offsets.size();- int keyIndex = i % offsets.size();
- int current = phraseChars.get(i);
- int result = current - offsets.get(keyIndex);
- if (current >= LowerCase_LOWER_LIMIT && result <= UpperCase_UPPER_LIMIT) {
- int offset = LowerCase_LOWER_LIMIT - result;
- result = UpperCase_UPPER_LIMIT - offset + 1;
- }
- if (result < LowerCase_LOWER_LIMIT && result > UpperCase_UPPER_LIMIT) {
- result -= INTERMEDIATE_OFFSET;
- } else if (result < UpperCase_LOWER_LIMIT) {
- int offset = UpperCase_LOWER_LIMIT - result;
- result = LowerCase_UPPER_LIMIT - offset + 1;
- }
translation.add(result);keyIndex++;- traduction.add(result);
- }
return parseChars(translation);- return parseChars(traduction);
- }
- }
Compact again, we need the storage space!
Greeting=lambda n,rank="",formal=0:f"He{['y','llo'][formal]}, {['',f'{rank} '][bool(rank and formal)]}{n}{chr(33+13*formal)}"
def Greeting(name, rank=None, formal=False):greeting_style = "Hello" if formal else "Hey"rank_part = f"{rank} " if rank and formal else ""punctuation = '.' if formal else '!'return f"{greeting_style}, {rank_part}{name}{punctuation}"- Greeting=lambda n,rank="",formal=0:f"He{['y','llo'][formal]}, {['',f'{rank} '][bool(rank and formal)]}{n}{chr(33+13*formal)}"
"""Test equipment positions.""" from __future__ import annotations from collections import Counter, defaultdict import datetime as dt import math import numpy as np import pandas as pd from typing import Any def data_dict() -> defaultdict[str, Any]: """Return all equipment positions.""" d = defaultdict(list) d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)}) d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)}) d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)}) d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}) d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}) return d def latest_snapshot() -> dict[str, Any]: """Return a snapshot of latest equipment.""" return { "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}, "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}, "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}, } def counts() -> dict[str, int]: """Return counts per equipment.""" return { "T123": 4, "T456": 3, "T789": 3 } def speeds() -> defaultdict[str, Any]: """Return speeds of equipment.""" d = defaultdict(list) d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)}) d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)}) d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)}) d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)}) d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)}) d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)}) d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)}) return d def find_furthest_west(d: defaultdict) -> str: """ Find the name of the truck that is furthest west. That is, the truck with the smallest easting position component. """ min_x = float('inf') furthest_west = None for equipment, positions in d.items(): for pos in positions: if pos["position"]["x"] < min_x: min_x = pos["position"]["x"] furthest_west = equipment return furthest_west def get_latest_snapshot(d: defaultdict) -> dict[str, Any]: """ Return a snapshot of the latest positional updates for the equipment. """ snapshot = {} for equipment, positions in d.items(): latest_pos = max(positions, key=lambda x: x["timestamp"]) snapshot[equipment] = latest_pos return snapshot def get_counts(d: defaultdict) -> dict[str, int]: """Return a dict of trucks and the times they have provided updates.""" return {equipment: len(positions) for equipment, positions in d.items()} def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]: """Return a dict of equipment and the speeds they are travelling at.""" pass
- """Test equipment positions."""
- from __future__ import annotations
- from collections import Counter, defaultdict
- import datetime as dt
- import math
- import numpy as np
- import pandas as pd
- from typing import Any
- def data_dict() -> defaultdict[str, Any]:
- """Return all equipment positions."""
- d = defaultdict(list)
- d["T123"].append({"position": {"x": 42, "y": 24, "z": 0.42}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"position": {"x": 21.0, "y": 34, "z": 0.289}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T789"].append({"position": {"x": 17, "y": 39, "z": 0.789}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"position": {"x": 91.0, "y": 114, "z": 0.489}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T123"].append({"position": {"x": 43, "y": 25, "z": 0.43}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
- d["T789"].append({"position": {"x": 19., "y": 79, "z": 0.991}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
- d["T123"].append({"position": {"x": 46, "y": 29, "z": 0.44}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
- d["T456"].append({"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
- d["T123"].append({"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T789"].append({"position": {"x": 23., "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
- return d
- def latest_snapshot() -> dict[str, Any]:
- """Return a snapshot of latest equipment."""
- return {
- "T123": {"position": {"x": 49.0, "y": 32, "z": 0.451}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)},
- "T456": {"position": {"x": 24.0, "y": 37, "z": 0.297}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)},
- "T789": {"position": {"x": 23.0, "y": 81, "z": 1.103}, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)},
- }
- def counts() -> dict[str, int]:
- """Return counts per equipment."""
- return {
- "T123": 4,
- "T456": 3,
- "T789": 3
- }
- def speeds() -> defaultdict[str, Any]:
- """Return speeds of equipment."""
- d = defaultdict(list)
- d["T123"].append({"speed": 4.242654947082074, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T123"].append({"speed": 5.00000999999, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=2)})
- d["T123"].append({"speed": 1.4142489172702237, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=1)})
- d["T123"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T456"].append({"speed": 102.0687849638664, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=4)})
- d["T456"].append({"speed": 35.43388209045123, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=3)})
- d["T456"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- d["T789"].append({"speed": 4.473538196997986, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=7)})
- d["T789"].append({"speed": 6.6750796998987205, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=6)})
- d["T789"].append({"speed": None, "timestamp": dt.datetime(2022, 1, 1, hour=12, minute=0, second=0)})
- return d
- def find_furthest_west(d: defaultdict) -> str:
- """
- Find the name of the truck that is furthest west. That is,
- the truck with the smallest easting position component.
- """
pass- min_x = float('inf')
- furthest_west = None
- for equipment, positions in d.items():
- for pos in positions:
- if pos["position"]["x"] < min_x:
- min_x = pos["position"]["x"]
- furthest_west = equipment
- return furthest_west
- def get_latest_snapshot(d: defaultdict) -> dict[str, Any]:
- """
- Return a snapshot of the latest positional updates for the
- equipment.
- """
pass- snapshot = {}
- for equipment, positions in d.items():
- latest_pos = max(positions, key=lambda x: x["timestamp"])
- snapshot[equipment] = latest_pos
- return snapshot
- def get_counts(d: defaultdict) -> dict[str, int]:
- """Return a dict of trucks and the times they have provided updates."""
pass- return {equipment: len(positions) for equipment, positions in d.items()}
- def calculate_speeds(d: defaultdict) -> defaultdict[str, Any]:
- """Return a dict of equipment and the speeds they are travelling at."""
- pass