complete second assignment

This commit is contained in:
amirM.t
2026-04-22 19:20:43 +03:30
parent e73ac6115f
commit 596e964956
2 changed files with 226 additions and 32 deletions
+108 -12
View File
@@ -20,11 +20,27 @@ public class BonusExercises {
- Each segment (between dots) must follow same hyphen rules
*/
public boolean validateEmail(String email) {
String regex = ""; // todo
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
if (email == null) return false;
return matcher.matches();
// Explanation:
// ^ start
// (?!\\.) - cannot start with dot
// (?!.*\\.{2}) - cannot contain consecutive dots
// [A-Za-z0-9._%+-]+ - allowed local chars
// (?<!\\.) - cannot end with dot
// @
// (?!-)[A-Za-z0-9-]+(?<!-) - first domain label, no leading/trailing hyphen
// (?:\\.(?!-)[A-Za-z0-9-]+(?<!-))* - other domain labels same rule
// $ end
//
// rejects underscores in domain labels
String regex = "^(?!\\.)" +
"(?!.*\\.{2})" +
"[A-Za-z0-9._%+-]+" +
"(?<!\\.)@" +
"(?!-)[A-Za-z0-9-]+(?<!-)(?:\\.(?!-)[A-Za-z0-9-]+(?<!-))*$";
return email.matches(regex);
}
/*
@@ -38,11 +54,36 @@ public class BonusExercises {
If no match for a date is found in the string, return null.
*/
public String findDate(String string) {
// todo
public String findDate(String string)
{
if (string == null)
return null;
String day = "(0[1-9]|[12][0-9]|3[01])";
String month = "(0[1-9]|1[0-2])";
String year = "\\d{4}";
String regex =
"\\b(?:" +
year + "-" + month + "-" + day + // YYYY-MM-DD
"|" +
year + "/" + month + "/" + day + // YYYY/MM/DD
"|" +
day + "/" + month + "/" + year + // DD/MM/YYYY
"|" +
month + "/" + day + "/" + year + // MM/DD/YYYY
")\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);
if (matcher.find())
return matcher.group();
return null;
}
/*
given a string, implement the method to detect all valid passwords
then, it should return the count of them
@@ -53,10 +94,44 @@ public class BonusExercises {
- at least one number and at least a special char "!@#$%^&*"
- has no white-space in it
*/
public int findValidPasswords(String string) {
// todo
return -1;
public int findValidPasswords(String string)
{
if (string == null || string.isEmpty())
return 0;
// Regex for a valid password based on the specified conditions:
// ^ - Start of the string
// (?=.*[A-Z]) - Positive lookahead for at least one uppercase letter
// (?=.*[a-z]) - Positive lookahead for at least one lowercase letter
// (?=.*\\d) - Positive lookahead for at least one digit (\\d is equivalent to [0-9])
// (?=.*[!@#$%^&*]) - Positive lookahead for at least one special character from the set
// \\S{8,} - Matches at least 8 non-whitespace characters
// $ - End of the string
String passwordRegex = "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[!@#$%^&*])\\S{8,}$";
Pattern passwordPattern = Pattern.compile(passwordRegex);
int validPasswordCount = 0;
// Split the input text into potential password tokens.
// \\S+ matches one or more non-whitespace characters.
Matcher tokenMatcher = Pattern.compile("\\S+").matcher(string);
while (tokenMatcher.find()) {
String potentialPassword = tokenMatcher.group();
// The prompt implies that tokens from the input string are directly considered as passwords.
// If there was a need to strip leading/trailing punctuation as in the previous context,
// that logic would go here. However, based on the current prompt, we use the token as-is.
if (passwordPattern.matcher(potentialPassword).matches()) {
validPasswordCount++;
}
}
return validPasswordCount;
}
/*
you should return a list of *words* which are palindromic
@@ -64,13 +139,34 @@ public class BonusExercises {
note: your implementation should be case-insensitive, e.g. Aba -> is palindrome
*/
public List<String> findPalindromes(String string) {
public List<String> findPalindromes(String string)
{
List<String> list = new ArrayList<>();
// todo
if (string == null) return list;
Matcher matcher = Pattern.compile("\\b[A-Za-z]{3,}\\b").matcher(string);
while (matcher.find())
{
String word = matcher.group();
boolean isPalindrome = new StringBuilder(word).reverse().toString().equalsIgnoreCase(word);
if (isPalindrome)
list.add(word);
}
return list;
}
public static void main(String[] args) {
// you can test your code here
BonusExercises b = new BonusExercises();
System.out.println(b.validateEmail("user.name+tag@sub-domain.co.uk")); // true
System.out.println(b.validateEmail(".bad@domain.com")); // false
System.out.println(b.findDate("Today's date is 2024-07-15.")); // 2024-07-15
System.out.println(b.findDate("event on 12/09/2023 in US format")); // 12/09/2023
System.out.println(b.findValidPasswords("Abcdef1! strongP@ss2 WeakPass noSpacePass3!"));
System.out.println(b.findPalindromes("Level noon Kayak test civic radar rotor deed pop"));
}
}
+107 -9
View File
@@ -1,3 +1,6 @@
import java.util.ArrayList;
import java.util.List;
public class MainExercises
{
/*
@@ -18,12 +21,30 @@ public class MainExercises
the output has to be a two-dimensional array of characters, so don't just print the triangle!
*/
public char[][] generateTriangle(int n) {
public char[][] generateTriangle(int n)
{
if (n <= 0)
return new char[0][0];
// todo
return null;
char[][] triangle = new char[n][];
for (int row = 0; row < n; row++)
{
triangle[row] = new char[row + 1];
for (int col = 0; col < row + 1; col++)
{
if((row == col) || (row == n-1) || (col == 0))
triangle[row][col] = '*';
else
triangle[row][col] = ' ';
}
}
return triangle;
}
@@ -57,11 +78,57 @@ public class MainExercises
- Number of rows: matrix.length
- Number of columns: matrix[0].length (if rectangular)
*/
public int[] spiralTraversal(int[][] matrix) {
// todo
return null;
public int[] spiralTraversal(int[][] matrix)
{
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
return new int[0];
int rows = matrix.length;
int cols = matrix[0].length;
int[] result = new int[rows * cols];
int index = 0;
int top = 0, bottom = rows - 1;
int left = 0, right = cols - 1;
while (top <= bottom && left <= right)
{
// move right
for (int c = left; c <= right; c++)
result[index++] = matrix[top][c];
top++;
// move down
for (int r = top; r <= bottom; r++)
result[index++] = matrix[r][right];
right--;
if (top <= bottom)
{
// move left
for (int c = right; c >= left; c--)
result[index++] = matrix[bottom][c];
bottom--;
}
if (left <= right)
{
// move up
for (int r = bottom; r >= top; r--)
result[index++] = matrix[r][left];
left++;
}
}
return result;
}
/*
integer partitioning is a combinatorics problem in discreet maths
the problem is to generate sum numbers which their summation is the input number
@@ -90,10 +157,41 @@ public class MainExercises
body to use them instead of arrays.
*/
public int[][] intPartitions(int n) {
// todo
return null;
public int[][] intPartitions(int n)
{
List<List<Integer>> result = new ArrayList<>();
generatePartitions(n, n, new ArrayList<>(), result);
int[][] arr = new int[result.size()][];
for (int i = 0; i < result.size(); i++)
{
List<Integer> part = result.get(i);
arr[i] = new int[part.size()];
for (int j = 0; j < part.size(); j++)
arr[i][j] = part.get(j);
}
return arr;
}
private void generatePartitions(int remaining, int max, List<Integer> current, List<List<Integer>> result)
{
if (remaining == 0)
{
result.add(new ArrayList<>(current));
return;
}
for (int i = Math.min(max, remaining); i >= 1; i--)
{
current.add(i);
generatePartitions(remaining - i, i, current, result);
current.remove(current.size() - 1);
}
}
public static void main()