It's about two months since I posted this question on CodeReview. I've been working hard to improve the code posted there and came up with the following.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned long long ull;
int main(void) {
ull start=1, stop=100,cnt;
register int t,len;
char *str=calloc(33,sizeof(char));
char *Alpha="abcdefghijklmnopqrstuvwxyz", *p1, *p2;
int a_len=(int)strlen(Alpha);
for (;start<=stop;++start) {
cnt=start;
/*
This is used to construct a string from given alphabet.
The generated string must be reversed
*/
for (t = 0, len = 0; cnt; cnt = (cnt-1)/a_len, ++str, ++len, ++t)
*str = Alpha[(cnt-1) % a_len];
/*
A bit odd but working (and important!) part of this code.
As the str pointer was incremented during string generation,
we need to 'reverse' it.
*/
while ( t-- ) str--;
/*
This is used to reverse a string instead of strrev
*/
for (p1 = str, p2 = str+len-1; p2>p1; ++p1, --p2) {
*p1 ^= *p2;
*p2 ^= *p1;
*p1 ^= *p2;
}
printf("%llu --- %s\n",start,str);
}
free(str);
return 0;
}
As you could have already guessed, this code generates letter combinations. The 'reversing' of a pointer (I'm not quite sure how to call this properly) is necessary because if one doesn't do that, he'll get a SegmentationFault as he'll be trying to access unallocated memory.
Example output
1 --- a
2 --- b
3 --- c
4 --- d
5 --- e
6 --- f
7 --- g
8 --- h
9 --- i
10 --- j
< omitted >
91 --- cm
92 --- cn
93 --- co
94 --- cp
95 --- cq
96 --- cr
97 --- cs
98 --- ct
99 --- cu
100 --- cv
This works quite well but I was wondering if it is possible to do the same thing even faster, if it is possible to omit the 'pointer revering' business.
Note: this code is different from the one I linked this question to because it doesn't use a function, thus, the technique and the algorithm are very different.
while ( t-- ) str--;
. I think you are able to optimize that. \$\endgroup\$str--
inside thewhile
statement?while (t--,str--);
? \$\endgroup\$str -= len
? That also allows you to remove t completely from your code. \$\endgroup\$