You may have seen this sequence on the Internet, in one of those “guess which number goes next?” type of posts:
1 11 21 1211 ...
So, which number comes next? I suppose it’s possible to divine a solution mathematically, but this sequence is known as a Look-and-Say sequence.
The first value is one. Verbally, this value is described as “one one,” or 11. The value 11 is described as “two ones,” or 21. The value 21 is described as “one two, one one,” or 1211. And so it goes.
Despite my math ignorance, mathematicians have examined the Look-and-Say sequence and extrapolated all sorts of interesting things. Well, interesting things for them. You can read more about the ugly details on Wikipedia. But I want to code this sequence.
My goal is to plow through a value left-to-right, identifying and counting repeating digits. To start, I convert the value into a string. Then I process the string tallying repeating letters and outputting the results. Here is the code:
2024_09_14-Lesson.c
#include <stdio.h> int main() { const int size = 32; char number[size],*n,c; int start,count; /* fetch the starting value */ printf("Value: "); scanf("%d",&start); /* convert `start` to a string */ snprintf(number,size,"%d",start); /* process the string `number` */ n = number; /* initialize the pointer */ while(*n) /* loop through the string */ { count = 0; /* digit count */ c = *n; /* save the current digit */ while( *n==c ) /* loop while the digits match */ { count++; n++; } /* output the digit count and the digit */ printf("%d%c",count,c); } putchar('\n'); return 0; }
The outer while loop churns through the value stored in string number
, working it left-to-right. The nested while loop repeats as long as the same digit occurs in the string. Variable count
keeps track of how many times this digit repeats.
When the inner loop stops, meaning that the digit has changed, the value is output, count and digit. The outer while loop then continues plowing through the string.
The result of this code is that a string is output, one that builds as each repeating digit is tallied. Here’s a sample run:
Value: 123
111213
You must run the program successively to calculate a Look-and-Say series, which is what I eventually want. But my first goal was to get an algorithm down for counting digits and outputting the result. My next step, to process a s sequence, took more effort than I anticipated. My journey continues with next week’s Lesson.