Skip to content

improve zig-zag-pattern #6128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
package com.thealgorithms.strings.zigZagPattern;

final class ZigZagPattern {

private ZigZagPattern() {
}

/**
* Encodes a given string into a zig-zag pattern.
*
* @param s the input string to be encoded
* @param numRows the number of rows in the zigzag pattern
* @return the encoded string in zigzag pattern format
*/
public static String encode(String s, int numRows) {
if (numRows < 2 || s.length() < numRows) {
return s;
}
int start = 0;
int index = 0;
int height = 1;
int depth = numRows;
char[] zigZagedArray = new char[s.length()];
while (depth != 0) {
int pointer = start;
int heightSpace = 2 + ((height - 2) * 2);
int depthSpace = 2 + ((depth - 2) * 2);
boolean bool = true;
while (pointer < s.length()) {
zigZagedArray[index++] = s.charAt(pointer);
if (heightSpace == 0) {
pointer += depthSpace;
} else if (depthSpace == 0) {
pointer += heightSpace;
} else if (bool) {
pointer += depthSpace;
bool = false;
} else {
pointer += heightSpace;
bool = true;

StringBuilder result = new StringBuilder(s.length());
int cycleLength = 2 * numRows - 2;

for (int row = 0; row < numRows; row++) {
for (int j = row; j < s.length(); j += cycleLength) {
result.append(s.charAt(j));

if (row > 0 && row < numRows - 1) {
int diagonal = j + cycleLength - 2 * row;
if (diagonal < s.length()) {
result.append(s.charAt(diagonal));
}
}
}
height++;
depth--;
start++;
}
return new String(zigZagedArray);

return result.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@
public class ZigZagPatternTest {

@Test
public void palindrome() {
public void testZigZagPattern() {
String input1 = "HelloWorldFromJava";
String input2 = "javaIsAProgrammingLanguage";
Assertions.assertEquals(ZigZagPattern.encode(input1, 4), "HooeWrrmalolFJvlda");
Assertions.assertEquals(ZigZagPattern.encode(input2, 4), "jAaLgasPrmgaaevIrgmnnuaoig");
// Edge cases
Assertions.assertEquals("ABC", ZigZagPattern.encode("ABC", 1)); // Single row
Assertions.assertEquals("A", ZigZagPattern.encode("A", 2)); // numRows > length of string
Assertions.assertEquals("", ZigZagPattern.encode("", 3)); // Empty string
}
}
Loading