complete second assignment #1

Merged
reyhne merged 1 commits from develop into main 2026-04-23 13:11:45 +00:00
2 changed files with 226 additions and 32 deletions
Showing only changes of commit 596e964956 - Show all commits
+119 -23
View File
@@ -20,11 +20,27 @@ public class BonusExercises {
- Each segment (between dots) must follow same hyphen rules - Each segment (between dots) must follow same hyphen rules
*/ */
public boolean validateEmail(String email) { public boolean validateEmail(String email) {
String regex = ""; // todo if (email == null) return false;
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(email);
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,39 +54,119 @@ public class BonusExercises {
If no match for a date is found in the string, return null. If no match for a date is found in the string, return null.
*/ */
public String findDate(String string) { public String findDate(String string)
// todo {
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; return null;
} }
/*
given a string, implement the method to detect all valid passwords
then, it should return the count of them
a valid password has the following properties: /*
- at least 8 characters given a string, implement the method to detect all valid passwords
- has to include at least one uppercase letter, and at least a lowercase then, it should return the count of them
- at least one number and at least a special char "!@#$%^&*"
- has no white-space in it a valid password has the following properties:
*/ - at least 8 characters
public int findValidPasswords(String string) { - has to include at least one uppercase letter, and at least a lowercase
// todo - at least one number and at least a special char "!@#$%^&*"
return -1; - has no white-space in it
*/
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 you should return a list of *words* which are palindromic
by word we mean at least 3 letters with no whitespace in it by word we mean at least 3 letters with no whitespace in it
note: your implementation should be case-insensitive, e.g. Aba -> is palindrome 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<>(); 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; return list;
} }
public static void main(String[] args) { 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 public class MainExercises
{ {
/* /*
@@ -18,15 +21,33 @@ public class MainExercises
the output has to be a two-dimensional array of characters, so don't just print the triangle! 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 char[][] triangle = new char[n][];
return null;
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;
} }
/* /*
SPIRAL TRAVERSAL OF A RECTANGULAR MATRIX SPIRAL TRAVERSAL OF A RECTANGULAR MATRIX
@@ -57,11 +78,57 @@ public class MainExercises
- Number of rows: matrix.length - Number of rows: matrix.length
- Number of columns: matrix[0].length (if rectangular) - Number of columns: matrix[0].length (if rectangular)
*/ */
public int[] spiralTraversal(int[][] matrix) { public int[] spiralTraversal(int[][] matrix)
// todo {
return null; 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 integer partitioning is a combinatorics problem in discreet maths
the problem is to generate sum numbers which their summation is the input number the problem is to generate sum numbers which their summation is the input number
@@ -90,11 +157,42 @@ public class MainExercises
body to use them instead of arrays. body to use them instead of arrays.
*/ */
public int[][] intPartitions(int n) { public int[][] intPartitions(int n)
// todo {
return null; 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() public static void main()
{ {