Pls explain this program(lock and say sequence) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Pls explain this program(lock and say sequence)

#include <stdio.h> #include <stdlib.h>   int main() { char *a = malloc(2), *b = 0, *x, c; int cnt, len = 1;   for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) { puts(x = a); for (len = 0, cnt = 1; (c = *a); ) { if (c == *++a) cnt++; else if (c) { len += sprintf(b + len, "%d%c", cnt, c); cnt = 1; } } }   return 0; } Output be like If input is 5 1 11 //only 1 one in first line 21//two 1 in second line 1211// one 2 and one 1 in third line 111221//one 1 one 2 two 1 in fourth line

25th Jun 2019, 6:15 PM
logesh ponnusamy
logesh ponnusamy - avatar
1 Answer
+ 1
That is some crazy awful code you got here ... The for loop initialize a to "1". The "condition" for the loop to stop is also used to assign b using realloc The "iteration" of the for loop is used to assign b to a and x to b (in this order) the puts will print a value AND assign a to x Second for loop, initialize len and cnt, use the first character of a as a stopping condition and ... no iteration ... This for loop will count the number of times a character occur in a string sequence I have two hypothesis for this code ... either it was made for a code golf or to hurt people. It is not a professional code as its readability is ... awful and so does its maintainability Do not follow this guy's lead ! (If it is a code golf code and you want to do some yourself, then do not follow what I just said :p )
24th Jul 2019, 9:40 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar