Skip to content

Instantly share code, notes, and snippets.

@studentbrad
Created October 23, 2019 23:28
Show Gist options
  • Save studentbrad/a372767695089b5b1a81bb70f2655520 to your computer and use it in GitHub Desktop.
Save studentbrad/a372767695089b5b1a81bb70f2655520 to your computer and use it in GitHub Desktop.
Zigzag conversion on a string
char *zigzag_convert(char *s, int numRows)
{
int numChars = strlen(s);
if (numRows == 1) return s; // Division by zero will occur in the next line otherwise.
int numColumns = numChars / (numRows + numRows - 2) * (numRows - 1) + numChars % (numRows + numRows - 2) / numRows + numChars % (numRows + numRows - 2) % numRows;
// Allocate space for the table.
char **table = malloc(numRows * sizeof(char *));
for (int i = 0; i < numRows; i++)
{
table[i] = malloc(numColumns * sizeof(char));
}
int i; // Index indicating the row number.
int j; // Index indicating the column number.
int numCharsPlaced; // The number of characters placed either in the table or the string.
bool writeDownward; // The direction characters are being added to the table.
// Ensure all characters are initially NULL.
for (i = 0; i < numRows; i++)
{
for (j = 0; j < numColumns; j++)
{
table[i][j] = NULL;
}
}
i = 0;
j = 0;
numCharsPlaced = 0;
writeDownward = true;
// Add all characters from the string to the table.
while(numCharsPlaced != numChars)
{
if (i == numRows)
{
writeDownward = false;
i -= 2;
j++;
}
if (i == 0)
{
writeDownward = true;
}
if (writeDownward)
{
table[i++][j] = s[numCharsPlaced++];
}
else
{
table[i--][j++] = s[numCharsPlaced++];
}
}
numCharsPlaced = 0;
// Add all characters from the table to the string.
for (i = 0; i < numRows; i++)
{
for (j = 0; j < numColumns; j++)
{
if (table[i][j])
{
s[numCharsPlaced++] = table[i][j];
}
}
}
return s;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment