Storing input into a character array

B

Ben Bacarisse

Bert said:
What's a data structure and how (have I created)/(am I using) one?

Loosely speaking, a data structure is a collection of data will some
pattern of access. You have made three arrays: one for the top row,
one 2D arrays for the middles rows, and one for the bottom row. Now,
as it happens, you don't need any of that storage but, if you did, I
am saying that you program is likely to be simpler if you just stored
all the rows together in one 2D array. It was an incidental remark.
I think you'll get the best boost from going another way altogether.
 
B

Ben Bacarisse

Bert said:
Have you done it yet?

I'd done it when I wrote before. The delay was down to worrying about
posting solutions to homework-type problems.
I'm just practising past problems for my own
benefit.

Then this may be of little use. It is decidedly "compact" because I
wanted to ensure that, if this was homework, my solution would not be
useful as an answer.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void zigzag_decode(int nrows, const char *input)
{
int length = strlen(input);
char output[length + 1];
for (int i = 0, row = 0; i < length; row++) {
output[row] = input[i++];
int skip[] = {nrows - 1 - row, row};
for (int j = 0, p = row; (p += 2 * skip[j]) < length; j = !j)
if (skip[j])
output[p] = input[i++];
}
output[length] = 0;
puts(output);
}

int main(int argc, char **argv)
{
if (argc == 3) {
int nr = atoi(argv[1]);
if (nr > 1)
zigzag_decode(nr, argv[2]);
else fprintf(stderr, "Number of rows must be > 1.\n");
}
else fprintf(stderr, "Try: zigzag no-of-rows input-sequence\n");
return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top