Skip to content

Commit

Permalink
Updated 2 solutions.
Browse files Browse the repository at this point in the history
  • Loading branch information
RodneyShag committed Nov 24, 2018
1 parent c1fd679 commit 68a50a2
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 3 deletions.
9 changes: 7 additions & 2 deletions 30 Days of Code/Day 19 - Interfaces/Solution.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,17 @@ class Calculator implements AdvancedArithmetic {
public int divisorSum(int n) {
int sum = 0;
int sqrt = (int) Math.sqrt(n);
for (int i = 1; i <= sqrt; i++) {

// Small optimization: if n is odd, we can't have even numbers as divisors
int stepSize = (n % 2 == 1) ? 2 : 1;

for (int i = 1; i <= sqrt; i += stepSize) {
if (n % i == 0) { // if "i" is a divisor
sum += i + n/i; // add both divisors
}
}
/* If sqrt is a divisor, we should only count it once */

// If sqrt is a divisor, we should only count it once
if (sqrt * sqrt == n) {
sum -= sqrt;
}
Expand Down
33 changes: 32 additions & 1 deletion Java/Strings/Java Regex 2 - Duplicate Words/Solution.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,42 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
### Regex
I used this regular expression: "\b(\w+)(?:\W+\1\b)+"
When using this regular expression in Java, we have to "escape" the backslash characters with additional backslashes (as done in the code above).
\w ----> A word character: [a-zA-Z_0-9] <br/>
\W ----> A non-word character: [^\w]<br/>
\b ----> A word boundary <br/>
\1 ----> Matches whatever was matched in the 1st group of parentheses, which in this case is the (\w+) <br/>
+ ----> Match whatever it's placed after 1 or more times
The \b boundaries are needed for special cases such as "Bob and Andy" (we don't want to match "and" twice). Another special case is "My thesis is great" (we don't want to match "is" twice).
### Groups
input = input.replaceAll(m.group(), m.group(1))
The line of code above replaces the entire match with the first group in the match.
m.group() is the entire match <br/>
m.group(i) is the ith match. So m.group(1) is the 1st match (which is enclosed in the 1st set of parentheses)
The ?: is added to make it a "non-capturing group", for slightly faster performance.
10/20/18 - Looks like the problem statement changed a bit, and digits should no longer be in the regular expression. User @4godspeed has an updated solution: https://www.hackerrank.com/challenges/duplicate-word/forum/comments/503715 that may work.
*/

public class DuplicateWords {

public static void main(String[] args) {

String regex = "\\b(\\w+)(\\W+\\1\\b)+";
String regex = "\\b(\\w+)(?:\\W+\\1\\b)+";
Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);

Scanner in = new Scanner(System.in);
Expand Down

0 comments on commit 68a50a2

Please sign in to comment.