Skip to content

Commit ef681e8

Browse files
authored
DEV: Implementing Alternative String Arrange (#6551)
1 parent fb12971 commit ef681e8

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.strings;
2+
3+
/**
4+
* This class provides a method to arrange two strings by alternating their characters.
5+
* If one string is longer, the remaining characters of the longer string are appended at the end.
6+
* <p>
7+
* Example:
8+
* Input: "abc", "12345"
9+
* Output: "a1b2c345"
10+
* <p>
11+
* Input: "abcd", "12"
12+
* Output: "a1b2cd"
13+
*
14+
* @author Milad Sadeghi
15+
*/
16+
public final class AlternativeStringArrange {
17+
18+
// Private constructor to prevent instantiation
19+
private AlternativeStringArrange() {
20+
}
21+
22+
/**
23+
* Arranges two strings by alternating their characters.
24+
*
25+
* @param firstString the first input string
26+
* @param secondString the second input string
27+
* @return a new string with characters from both strings arranged alternately
28+
*/
29+
public static String arrange(String firstString, String secondString) {
30+
StringBuilder result = new StringBuilder();
31+
int length1 = firstString.length();
32+
int length2 = secondString.length();
33+
int minLength = Math.min(length1, length2);
34+
35+
for (int i = 0; i < minLength; i++) {
36+
result.append(firstString.charAt(i));
37+
result.append(secondString.charAt(i));
38+
}
39+
40+
if (length1 > length2) {
41+
result.append(firstString.substring(minLength));
42+
} else if (length2 > length1) {
43+
result.append(secondString.substring(minLength));
44+
}
45+
46+
return result.toString();
47+
}
48+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.strings;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
5+
import java.util.stream.Stream;
6+
import org.junit.jupiter.params.ParameterizedTest;
7+
import org.junit.jupiter.params.provider.MethodSource;
8+
9+
class AlternativeStringArrangeTest {
10+
11+
// Method to provide test data
12+
private static Stream<Object[]> provideTestData() {
13+
return Stream.of(new Object[] {"abc", "12345", "a1b2c345"}, new Object[] {"abcd", "12", "a1b2cd"}, new Object[] {"", "123", "123"}, new Object[] {"abc", "", "abc"}, new Object[] {"a", "1", "a1"}, new Object[] {"ab", "12", "a1b2"}, new Object[] {"abcdef", "123", "a1b2c3def"},
14+
new Object[] {"ab", "123456", "a1b23456"});
15+
}
16+
17+
// Parameterized test using the provided test data
18+
@ParameterizedTest(name = "{0} and {1} should return {2}")
19+
@MethodSource("provideTestData")
20+
void arrangeTest(String input1, String input2, String expected) {
21+
assertEquals(expected, AlternativeStringArrange.arrange(input1, input2));
22+
}
23+
}

0 commit comments

Comments
 (0)