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 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("", "abcde")); assertEquals("", Kata.encode(null, null)); assertEquals("", Kata.encode("", null)); assertEquals("", Kata.encode(null, "")); assertEquals("IntelliJCrew",Kata.encode("IntelliJCrew", null)); assertEquals("", Kata.encode(null, "IlikeBreaksInForLoops")); } @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));- assertEquals("", Kata.encode("", ""));
- assertEquals("TernaryLove", Kata.encode("TernaryLove", ""));
- assertEquals("", Kata.encode("", "abcde"));
- assertEquals("", Kata.encode(null, null));
- assertEquals("", Kata.encode("", null));
- assertEquals("", Kata.encode(null, ""));
- assertEquals("IntelliJCrew",Kata.encode("IntelliJCrew", null));
- assertEquals("", Kata.encode(null, "IlikeBreaksInForLoops"));
- }
- @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);
- }
- }
The password game is a web game where you will write a password as it says, but it has a twist, you have to follow some insanely stupid rules to complete the perfect password.
So in this kata you will have a bunch of rules and need to make a method that validates if a String satisfies them all.
Input- A String or empty String
- The given String will not have blank spaces or line breaks
- A boolean which state if the password is strong enough to pass the game
- The maximum lenght of the password is 50 characters
- The minimum lenght of the password is 20 characters
- The length of the password must be a prime number
- Must have at least 1 lower case, 3 upper case letter and 1 special character
- The addition of each of the digits in the password has to be at least 25
- Must have the diminituve of a month
- Must have today's date
- 2 special characters can't be together
- The length of the password must be inside the password
- The months of the year for this kata are [jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec]
- The months may be in upper case, lower case or combined
- The date inside the password will have the following format YYYYMMDD
- The date numbers count as normal digits
- The special characters for this kata are ['-', '.' , '_', '@', '#', '$', '&']
import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; public class PasswordValidation { private static final String TODAY_DATE = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")); private static final String[] VALID_MONTHS = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec" }; public static boolean validatePassword(String password) { if (password.length() < 20 | password.length() > 50) return false; if (!isPrime(password.length())) return false; if (!password.contains(String.valueOf(password.length()))) return false; if (!password.contains(TODAY_DATE)) return false; if (!Arrays.stream(VALID_MONTHS).anyMatch(s -> password.toLowerCase().contains(s))) return false; if (!password.matches(("(.*[A-Z].*){3,}")) || !password.matches("(.*[a-z].*){1,}") || !password.matches("(.*[-._@#$&].*){1,}") || password.matches(".*[-._@#$&][-._@#$&].*")) return false; if (Arrays.stream(password.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; } }
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.util.Arrays;
- public class PasswordValidation {
- private static final String TODAY_DATE = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
- private static final String[] VALID_MONTHS = { "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct",
- "nov", "dec" };
- public static boolean validatePassword(String password) {
- if (password.length() < 20 | password.length() > 50)
- return false;
- if (!isPrime(password.length()))
- return false;
- if (!password.contains(String.valueOf(password.length())))
- return false;
- if (!password.contains(TODAY_DATE))
- return false;
- if (!Arrays.stream(VALID_MONTHS).anyMatch(s -> password.toLowerCase().contains(s)))
- return false;
- if (!password.matches(("(.*[A-Z].*){3,}"))
- || !password.matches("(.*[a-z].*){1,}")
- || !password.matches("(.*[-._@#$&].*){1,}")
- || password.matches(".*[-._@#$&][-._@#$&].*"))
- return false;
- if (Arrays.stream(password.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;
- }
- }
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Random; 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, 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, 47, 47, 47, 47, 47, 48, 49, 50 }; // Prime numbers between 20 & 50 private static final int[] PRIME_LENGTHS = { 23, 29, 31, 37, 41, 43, 47 }; @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_DATE + "TOdaY.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 length_pos = random.nextInt(length - 2); int date_pos = random.nextInt(length - 8); 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 (!Arrays.stream(PRIME_LENGTHS).anyMatch(n -> pass.length() == n) || !pass.contains(String.valueOf(pass.length())) || !pass.contains(TODAY_DATE) || !Arrays.stream(VALID_MONTHS).anyMatch(s -> pass.toLowerCase().contains(s)) || !pass.matches("(.*[A-Z].*){3,}") || !pass.matches("(.*[a-z].*){1,}") || !pass.matches("(.*[-._@#$&].*){1,}") || pass.matches(".*[-._@#$&][-._@#$&].*") || Arrays.stream(pass.split("")) .filter(s -> s.matches("[0-9]")).mapToInt(s -> Integer.valueOf(s)).sum() < 25) { return false; } return true; } @RepeatedTest(200) void randomTest() { String randomPass = generateRandomPass(); assertEquals(checkPass(randomPass), PasswordValidation.validatePassword(randomPass)); } }
- import static org.junit.jupiter.api.Assertions.assertEquals;
- import static org.junit.Assert.assertFalse;
- import static org.junit.Assert.assertTrue;
- import org.junit.jupiter.api.RepeatedTest;
- import org.junit.jupiter.api.Test;
- import java.time.LocalDate;
- import java.time.format.DateTimeFormatter;
- import java.util.Arrays;
- import java.util.Random;
- 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, 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, 47, 47, 47, 47, 47, 48, 49, 50 };
- // Prime numbers between 20 & 50
- private static final int[] PRIME_LENGTHS = { 23, 29, 31, 37, 41, 43, 47 };
- @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_DATE + "TOdaY.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 - 8);- int length_pos = random.nextInt(length - 2);
- int date_pos = random.nextInt(length - 8);
- 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 (!Arrays.stream(PRIME_LENGTHS).anyMatch(n -> pass.length() == n)
- || !pass.contains(String.valueOf(pass.length()))
- || !pass.contains(TODAY_DATE)
- || !Arrays.stream(VALID_MONTHS).anyMatch(s -> pass.toLowerCase().contains(s))
|| !pass.matches(("(.*[A-Z].*){3,}"))- || !pass.matches("(.*[A-Z].*){3,}")
- || !pass.matches("(.*[a-z].*){1,}")
- || !pass.matches("(.*[-._@#$&].*){1,}")
- || pass.matches(".*[-._@#$&][-._@#$&].*")
- || Arrays.stream(pass.split(""))
- .filter(s -> s.matches("[0-9]")).mapToInt(s -> Integer.valueOf(s)).sum() < 25) {
- return false;
- }
- return true;
- }
@RepeatedTest(100)- @RepeatedTest(200)
- void randomTest() {
- String randomPass = generateRandomPass();
- assertEquals(checkPass(randomPass), PasswordValidation.validatePassword(randomPass));
- }
- }