Skip to content

Commit 5ba8a8d

Browse files
authored
Merge branch 'master' into added-mos-algorithm-dice-thrower
2 parents f8f16e7 + 506b6d1 commit 5ba8a8d

File tree

8 files changed

+939
-0
lines changed

8 files changed

+939
-0
lines changed

DIRECTORY.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@
9494
- 📄 [AnyBaseToAnyBase](src/main/java/com/thealgorithms/conversions/AnyBaseToAnyBase.java)
9595
- 📄 [AnyBaseToDecimal](src/main/java/com/thealgorithms/conversions/AnyBaseToDecimal.java)
9696
- 📄 [AnytoAny](src/main/java/com/thealgorithms/conversions/AnytoAny.java)
97+
- 📄 [Base64](src/main/java/com/thealgorithms/conversions/Base64.java)
9798
- 📄 [BinaryToDecimal](src/main/java/com/thealgorithms/conversions/BinaryToDecimal.java)
9899
- 📄 [BinaryToHexadecimal](src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java)
99100
- 📄 [BinaryToOctal](src/main/java/com/thealgorithms/conversions/BinaryToOctal.java)
@@ -839,6 +840,7 @@
839840
- 📄 [AffineConverterTest](src/test/java/com/thealgorithms/conversions/AffineConverterTest.java)
840841
- 📄 [AnyBaseToDecimalTest](src/test/java/com/thealgorithms/conversions/AnyBaseToDecimalTest.java)
841842
- 📄 [AnytoAnyTest](src/test/java/com/thealgorithms/conversions/AnytoAnyTest.java)
843+
- 📄 [Base64Test](src/test/java/com/thealgorithms/conversions/Base64Test.java)
842844
- 📄 [BinaryToDecimalTest](src/test/java/com/thealgorithms/conversions/BinaryToDecimalTest.java)
843845
- 📄 [BinaryToHexadecimalTest](src/test/java/com/thealgorithms/conversions/BinaryToHexadecimalTest.java)
844846
- 📄 [BinaryToOctalTest](src/test/java/com/thealgorithms/conversions/BinaryToOctalTest.java)
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
package com.thealgorithms.conversions;
2+
3+
import java.nio.charset.StandardCharsets;
4+
import java.util.ArrayList;
5+
import java.util.List;
6+
7+
/**
8+
* Base64 is a group of binary-to-text encoding schemes that represent binary data
9+
* in an ASCII string format by translating it into a radix-64 representation.
10+
* Each base64 digit represents exactly 6 bits of data.
11+
*
12+
* Base64 encoding is commonly used when there is a need to encode binary data
13+
* that needs to be stored and transferred over media that are designed to deal
14+
* with textual data.
15+
*
16+
* Wikipedia Reference: https://en.wikipedia.org/wiki/Base64
17+
* Author: Nithin U.
18+
* Github: https://github.com/NithinU2802
19+
*/
20+
21+
public final class Base64 {
22+
23+
// Base64 character set
24+
private static final String BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
25+
private static final char PADDING_CHAR = '=';
26+
27+
private Base64() {
28+
}
29+
30+
/**
31+
* Encodes the given byte array to a Base64 encoded string.
32+
*
33+
* @param input the byte array to encode
34+
* @return the Base64 encoded string
35+
* @throws IllegalArgumentException if input is null
36+
*/
37+
public static String encode(byte[] input) {
38+
if (input == null) {
39+
throw new IllegalArgumentException("Input cannot be null");
40+
}
41+
42+
if (input.length == 0) {
43+
return "";
44+
}
45+
46+
StringBuilder result = new StringBuilder();
47+
int padding = 0;
48+
49+
// Process input in groups of 3 bytes
50+
for (int i = 0; i < input.length; i += 3) {
51+
// Get up to 3 bytes
52+
int byte1 = input[i] & 0xFF;
53+
int byte2 = (i + 1 < input.length) ? (input[i + 1] & 0xFF) : 0;
54+
int byte3 = (i + 2 < input.length) ? (input[i + 2] & 0xFF) : 0;
55+
56+
// Calculate padding needed
57+
if (i + 1 >= input.length) {
58+
padding = 2;
59+
} else if (i + 2 >= input.length) {
60+
padding = 1;
61+
}
62+
63+
// Combine 3 bytes into a 24-bit number
64+
int combined = (byte1 << 16) | (byte2 << 8) | byte3;
65+
66+
// Extract four 6-bit groups
67+
result.append(BASE64_CHARS.charAt((combined >> 18) & 0x3F));
68+
result.append(BASE64_CHARS.charAt((combined >> 12) & 0x3F));
69+
result.append(BASE64_CHARS.charAt((combined >> 6) & 0x3F));
70+
result.append(BASE64_CHARS.charAt(combined & 0x3F));
71+
}
72+
73+
// Replace padding characters
74+
if (padding > 0) {
75+
result.setLength(result.length() - padding);
76+
for (int i = 0; i < padding; i++) {
77+
result.append(PADDING_CHAR);
78+
}
79+
}
80+
81+
return result.toString();
82+
}
83+
84+
/**
85+
* Encodes the given string to a Base64 encoded string using UTF-8 encoding.
86+
*
87+
* @param input the string to encode
88+
* @return the Base64 encoded string
89+
* @throws IllegalArgumentException if input is null
90+
*/
91+
public static String encode(String input) {
92+
if (input == null) {
93+
throw new IllegalArgumentException("Input cannot be null");
94+
}
95+
96+
return encode(input.getBytes(StandardCharsets.UTF_8));
97+
}
98+
99+
/**
100+
* Decodes the given Base64 encoded string to a byte array.
101+
*
102+
* @param input the Base64 encoded string to decode
103+
* @return the decoded byte array
104+
* @throws IllegalArgumentException if input is null or contains invalid Base64 characters
105+
*/
106+
public static byte[] decode(String input) {
107+
if (input == null) {
108+
throw new IllegalArgumentException("Input cannot be null");
109+
}
110+
111+
if (input.isEmpty()) {
112+
return new byte[0];
113+
}
114+
115+
// Strict RFC 4648 compliance: length must be a multiple of 4
116+
if (input.length() % 4 != 0) {
117+
throw new IllegalArgumentException("Invalid Base64 input length; must be multiple of 4");
118+
}
119+
120+
// Validate padding: '=' can only appear at the end (last 1 or 2 chars)
121+
int firstPadding = input.indexOf('=');
122+
if (firstPadding != -1 && firstPadding < input.length() - 2) {
123+
throw new IllegalArgumentException("Padding '=' can only appear at the end (last 1 or 2 characters)");
124+
}
125+
126+
List<Byte> result = new ArrayList<>();
127+
128+
// Process input in groups of 4 characters
129+
for (int i = 0; i < input.length(); i += 4) {
130+
// Get up to 4 characters
131+
int char1 = getBase64Value(input.charAt(i));
132+
int char2 = getBase64Value(input.charAt(i + 1));
133+
int char3 = input.charAt(i + 2) == '=' ? 0 : getBase64Value(input.charAt(i + 2));
134+
int char4 = input.charAt(i + 3) == '=' ? 0 : getBase64Value(input.charAt(i + 3));
135+
136+
// Combine four 6-bit groups into a 24-bit number
137+
int combined = (char1 << 18) | (char2 << 12) | (char3 << 6) | char4;
138+
139+
// Extract three 8-bit bytes
140+
result.add((byte) ((combined >> 16) & 0xFF));
141+
if (input.charAt(i + 2) != '=') {
142+
result.add((byte) ((combined >> 8) & 0xFF));
143+
}
144+
if (input.charAt(i + 3) != '=') {
145+
result.add((byte) (combined & 0xFF));
146+
}
147+
}
148+
149+
// Convert List<Byte> to byte[]
150+
byte[] resultArray = new byte[result.size()];
151+
for (int i = 0; i < result.size(); i++) {
152+
resultArray[i] = result.get(i);
153+
}
154+
155+
return resultArray;
156+
}
157+
158+
/**
159+
* Decodes the given Base64 encoded string to a string using UTF-8 encoding.
160+
*
161+
* @param input the Base64 encoded string to decode
162+
* @return the decoded string
163+
* @throws IllegalArgumentException if input is null or contains invalid Base64 characters
164+
*/
165+
public static String decodeToString(String input) {
166+
if (input == null) {
167+
throw new IllegalArgumentException("Input cannot be null");
168+
}
169+
170+
byte[] decodedBytes = decode(input);
171+
return new String(decodedBytes, StandardCharsets.UTF_8);
172+
}
173+
174+
/**
175+
* Gets the numeric value of a Base64 character.
176+
*
177+
* @param c the Base64 character
178+
* @return the numeric value (0-63)
179+
* @throws IllegalArgumentException if character is not a valid Base64 character
180+
*/
181+
private static int getBase64Value(char c) {
182+
if (c >= 'A' && c <= 'Z') {
183+
return c - 'A';
184+
} else if (c >= 'a' && c <= 'z') {
185+
return c - 'a' + 26;
186+
} else if (c >= '0' && c <= '9') {
187+
return c - '0' + 52;
188+
} else if (c == '+') {
189+
return 62;
190+
} else if (c == '/') {
191+
return 63;
192+
} else {
193+
throw new IllegalArgumentException("Invalid Base64 character: " + c);
194+
}
195+
}
196+
}
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
package com.thealgorithms.conversions;
2+
3+
import java.util.Locale;
4+
import java.util.Map;
5+
6+
/**
7+
* A utility class to convert between different units of time.
8+
*
9+
* <p>This class supports conversions between the following units:
10+
* <ul>
11+
* <li>seconds</li>
12+
* <li>minutes</li>
13+
* <li>hours</li>
14+
* <li>days</li>
15+
* <li>weeks</li>
16+
* <li>months (approximated as 30.44 days)</li>
17+
* <li>years (approximated as 365.25 days)</li>
18+
* </ul>
19+
*
20+
* <p>The conversion is based on predefined constants in seconds.
21+
* Results are rounded to three decimal places for consistency.
22+
*
23+
* <p>This class is final and cannot be instantiated.
24+
*
25+
* @see <a href="https://en.wikipedia.org/wiki/Unit_of_time">Wikipedia: Unit of time</a>
26+
*/
27+
public final class TimeConverter {
28+
29+
private TimeConverter() {
30+
// Prevent instantiation
31+
}
32+
33+
/**
34+
* Supported time units with their equivalent in seconds.
35+
*/
36+
private enum TimeUnit {
37+
SECONDS(1.0),
38+
MINUTES(60.0),
39+
HOURS(3600.0),
40+
DAYS(86400.0),
41+
WEEKS(604800.0),
42+
MONTHS(2629800.0), // 30.44 days
43+
YEARS(31557600.0); // 365.25 days
44+
45+
private final double seconds;
46+
47+
TimeUnit(double seconds) {
48+
this.seconds = seconds;
49+
}
50+
51+
public double toSeconds(double value) {
52+
return value * seconds;
53+
}
54+
55+
public double fromSeconds(double secondsValue) {
56+
return secondsValue / seconds;
57+
}
58+
}
59+
60+
private static final Map<String, TimeUnit> UNIT_LOOKUP
61+
= Map.ofEntries(Map.entry("seconds", TimeUnit.SECONDS), Map.entry("minutes", TimeUnit.MINUTES), Map.entry("hours", TimeUnit.HOURS), Map.entry("days", TimeUnit.DAYS), Map.entry("weeks", TimeUnit.WEEKS), Map.entry("months", TimeUnit.MONTHS), Map.entry("years", TimeUnit.YEARS));
62+
63+
/**
64+
* Converts a time value from one unit to another.
65+
*
66+
* @param timeValue the numeric value of time to convert; must be non-negative
67+
* @param unitFrom the unit of the input value (e.g., "minutes", "hours")
68+
* @param unitTo the unit to convert into (e.g., "seconds", "days")
69+
* @return the converted value in the target unit, rounded to three decimals
70+
* @throws IllegalArgumentException if {@code timeValue} is negative
71+
* @throws IllegalArgumentException if either {@code unitFrom} or {@code unitTo} is not supported
72+
*/
73+
public static double convertTime(double timeValue, String unitFrom, String unitTo) {
74+
if (timeValue < 0) {
75+
throw new IllegalArgumentException("timeValue must be a non-negative number.");
76+
}
77+
78+
TimeUnit from = resolveUnit(unitFrom);
79+
TimeUnit to = resolveUnit(unitTo);
80+
81+
double secondsValue = from.toSeconds(timeValue);
82+
double converted = to.fromSeconds(secondsValue);
83+
84+
return Math.round(converted * 1000.0) / 1000.0;
85+
}
86+
87+
private static TimeUnit resolveUnit(String unit) {
88+
if (unit == null) {
89+
throw new IllegalArgumentException("Unit cannot be null.");
90+
}
91+
TimeUnit resolved = UNIT_LOOKUP.get(unit.toLowerCase(Locale.ROOT));
92+
if (resolved == null) {
93+
throw new IllegalArgumentException("Invalid unit '" + unit + "'. Supported units are: " + UNIT_LOOKUP.keySet());
94+
}
95+
return resolved;
96+
}
97+
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
import java.util.HashMap;
4+
5+
/**
6+
* Finds the minimum window substring in 's' that contains all characters of 't'.
7+
*
8+
* Worst-case performance O(n)
9+
* Best-case performance O(n)
10+
* Average performance O(n)
11+
* Worst-case space complexity O(1)
12+
*
13+
* @author https://github.com/Chiefpatwal
14+
*/
15+
public final class MinimumWindowSubstring {
16+
// Prevent instantiation
17+
private MinimumWindowSubstring() {
18+
}
19+
20+
/**
21+
* Finds the minimum window substring of 's' containing all characters of 't'.
22+
*
23+
* @param s The input string to search within.
24+
* @param t The string with required characters.
25+
* @return The minimum window substring, or empty string if not found.
26+
*/
27+
public static String minWindow(String s, String t) {
28+
if (s.length() < t.length()) {
29+
return "";
30+
}
31+
32+
HashMap<Character, Integer> tFreq = new HashMap<>();
33+
for (char c : t.toCharArray()) {
34+
tFreq.put(c, tFreq.getOrDefault(c, 0) + 1);
35+
}
36+
37+
HashMap<Character, Integer> windowFreq = new HashMap<>();
38+
int left = 0;
39+
int right = 0;
40+
int minLen = Integer.MAX_VALUE;
41+
int count = 0;
42+
String result = "";
43+
44+
while (right < s.length()) {
45+
char c = s.charAt(right);
46+
windowFreq.put(c, windowFreq.getOrDefault(c, 0) + 1);
47+
48+
if (tFreq.containsKey(c) && windowFreq.get(c).intValue() <= tFreq.get(c).intValue()) {
49+
count++;
50+
}
51+
52+
while (count == t.length()) {
53+
if (right - left + 1 < minLen) {
54+
minLen = right - left + 1;
55+
result = s.substring(left, right + 1);
56+
}
57+
58+
char leftChar = s.charAt(left);
59+
windowFreq.put(leftChar, windowFreq.get(leftChar) - 1);
60+
if (tFreq.containsKey(leftChar) && windowFreq.get(leftChar) < tFreq.get(leftChar)) {
61+
count--;
62+
}
63+
left++;
64+
}
65+
right++;
66+
}
67+
return result;
68+
}
69+
}

0 commit comments

Comments
 (0)