Skip to content

Instantly share code, notes, and snippets.

@brlafreniere
Created January 30, 2022 06:50
Show Gist options
  • Save brlafreniere/71045a6d407dc95bd50f018171272415 to your computer and use it in GitHub Desktop.
Save brlafreniere/71045a6d407dc95bd50f018171272415 to your computer and use it in GitHub Desktop.
(gdb) display zigzag_array
1: zigzag_array = {"F\000A\000N\000\000\000\000\000", "OBROE\000\000\000\000\000", "O\000J\002S\000@\003\000\000@"}
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
char * convert(char * input_str, int num_rows) {
int str_i = 0;
int row_i = 0;
int col_i = 0;
int str_len = strlen(input_str);
char zigzag_array[num_rows][str_len];
bool down = true;
// form the zigzag
while (str_i < strlen(input_str)) {
char current_char = input_str[str_i];
zigzag_array[row_i][col_i] = current_char;
// change directions if we hit the bottom row
if (row_i == num_rows-1 && down)
down = false;
// change directions if we hit the top row
if (row_i == 0 && !down)
down = true;
if (down)
row_i++;
else {
col_i++;
row_i--;
}
str_i++;
}
char result_str[str_len];
int result_i = 0;
for (int i = 0; i < num_rows; i++) {
for (int j = 0; j < str_len; j++) {
char zig_char = zigzag_array[i][j];
if (zig_char) {
result_str[result_i] = zig_char;
result_i++;
}
}
}
}
int main() {
char input_str[] = "FOOBARJONES";
int num_rows = 3;
convert(input_str, num_rows);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment