Skip to content

Commit b648bf7

Browse files
committed
reduce mutable state
1 parent 54991cf commit b648bf7

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

src/main/java/com/thealgorithms/strings/zigZagPattern/ZigZagPattern.java

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9,31 +9,30 @@ private ZigZagPattern() {
99
* Encodes a given string into a zig-zag pattern.
1010
*
1111
* @param s the input string to be encoded
12-
* @param numRows the number of rows in the zig-zag pattern
13-
* @return the encoded string in zig-zag pattern format
12+
* @param numRows the number of rows in the zigzag pattern
13+
* @return the encoded string in zigzag pattern format
1414
*/
1515
public static String encode(String s, int numRows) {
1616
if (numRows < 2 || s.length() < numRows) {
1717
return s;
1818
}
1919

20-
char[] result = new char[s.length()];
21-
int index = 0;
22-
23-
// Cycle length for zigzag traversal
20+
StringBuilder result = new StringBuilder(s.length());
2421
int cycleLength = 2 * numRows - 2;
2522

2623
for (int row = 0; row < numRows; row++) {
2724
for (int j = row; j < s.length(); j += cycleLength) {
28-
result[index++] = s.charAt(j);
25+
result.append(s.charAt(j));
2926

30-
int diagonal = j + cycleLength - 2 * row;
31-
if (row > 0 && row < numRows - 1 && diagonal < s.length()) {
32-
result[index++] = s.charAt(diagonal);
27+
if (row > 0 && row < numRows - 1) {
28+
int diagonal = j + cycleLength - 2 * row;
29+
if (diagonal < s.length()) {
30+
result.append(s.charAt(diagonal));
31+
}
3332
}
3433
}
3534
}
3635

37-
return new String(result);
36+
return result.toString();
3837
}
3938
}

src/test/java/com/thealgorithms/strings/zigZagPattern/ZigZagPatternTest.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,9 @@ public void testZigZagPattern() {
1111
String input2 = "javaIsAProgrammingLanguage";
1212
Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
1313
Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
14+
// Edge cases
15+
Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row
16+
Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string
17+
Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string
1418
}
1519
}

0 commit comments

Comments
 (0)