Friday, 18 July 2008

Zigzag in C

Here is the zigzag decoder in C

//=======================================================
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {

const int ArraySize= 10001 ;
char cryptStr[ArraySize];
int rowlen,r,newrow;
char array[ArraySize];

if ( argc < 3 ){
printf("%s\n","zigzag_d rowlen cryptmessage");
} else {

rowlen = atoi(argv[1]) ;
strcpy(cryptStr,argv[2]);
//adjust for zero-numbering
rowlen-- ;

//init the array
for (r=0;r <=ArraySize ;r++){ array[r]=0; }

int rowIndex =0;
int tempIndex=0;
int arrayLen = strlen(cryptStr)-1;
r=0;
newrow=0;

while(r <= arrayLen ){
if (newrow == 1 ) {
// new row
rowIndex++;
tempIndex = rowIndex;
array[tempIndex] = cryptStr[r];
if (rowIndex == rowlen) {
tempIndex = tempIndex+2*rowlen;
} else {
tempIndex = tempIndex+(2*(rowlen-rowIndex));
}
r++;
newrow=0;
} else {

if((rowIndex > 0 ) ) { //don't do on first row
if(newrow==0) {
array[tempIndex] = cryptStr[r];
r++;
tempIndex = tempIndex+2*rowlen-(2*(rowlen-rowIndex));
if (tempIndex >arrayLen) { newrow =1; }
}
}

if(rowIndex != rowlen) { //don't do on last row
if(newrow==0){
array[tempIndex] = cryptStr[r];
r++;
tempIndex = tempIndex+(2*(rowlen-rowIndex));
if (tempIndex > arrayLen) { newrow =1 ; }
}
}
}
}

printf("%s\n", array);
}
}
//=====================================================================

No comments: