Thue-Morse: Difference between revisions

1,454 bytes added ,  7 years ago
Added a way to generate a sequence with a max length of 2^{32}-1 using bit-counting
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(Added a way to generate a sequence with a max length of 2^{32}-1 using bit-counting)
Line 195:
 
=={{header|C}}==
===C: Using string operations===
{{trans|Java}}
<lang c>#include <stdio.h>
Line 217 ⟶ 218:
{{out}}
<pre>
0110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110
</pre>
 
===C: By counting set ones in binary represenation===
<lang C>
#include <stdio.h>
 
/**
* Counts the number of bits set to 1
* @param v the number to have its bit counted
* @returns The number of bits set to 1
*/
unsigned count_bits(unsigned v) {
unsigned c = 0;
while (v) {
c += v & 1;
v >>= 1;
}
 
return c;
}
 
int main(void) {
/* i: loop iterator
* length: the length of the sequence to be printed
* ascii_base: the lower char for use when printing
*/
unsigned i, length = 0;
int ascii_base;
 
 
/* scan in sequence length */
printf("Sequence length: ");
do {
scanf("%u", &length);
} while (length == 0);
 
 
/* scan in sequence mode */
printf("(a)lpha or (b)inary: ");
do {
ascii_base = getchar();
} while ((ascii_base != 'a') && (ascii_base != 'b'));
ascii_base = ascii_base == 'b' ? '0' : 'a';
 
 
/* print the Thue-Morse sequence */
for (i = 0; i < length; ++i) {
putchar(ascii_base + count_bits(i) % 2);
}
putchar('\n');
 
return 0;
}
</lang>
{{out}}
<pre>
Sequence length: 256
(a)lpha or (b)inary: b
0110100110010110100101100110100110010110011010010110100110010110100101100110100101101001100101100110100110010110100101100110100110010110011010010110100110010110011010011001011010010110011010010110100110010110100101100110100110010110011010010110100110010110
</pre>