Skip to content

Commit

Permalink
Add Thue_Morse Sequence algorithm in C
Browse files Browse the repository at this point in the history
Update TrackingProgress.md
  • Loading branch information
philippossfrn committed Jan 25, 2022
1 parent c85e8e9 commit 27d1e02
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
44 changes: 44 additions & 0 deletions Thue-Morse sequence/Thue_MorseSequence.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif

#include<stdio.h>
#include <string.h>

const char* complement(const char* term) {
char* appendString = NULL;
for (int i = 0; i < strlen(term); i++) { // iterate each digit of the term and compute the complement digit
char* appendDigit;

appendDigit = term[i] == 48 ? "1" : "0"; // 48 is ascii code for "0"

if (appendString == NULL) { // First time appendString is NULL so initialize it with the first complement digit
appendString = appendDigit;
} else {
asprintf(&appendString, "%s%s",appendString, appendDigit); // concat strings
}
}

return appendString;
}

const char* calculateSequence(int num) {
if (num <= 1) {
return "0";
}
char* initTerm = "0";
for (int i = 1; i < num; i++) { // iterate through terms
asprintf(&initTerm, "%s%s",initTerm, complement(initTerm)); // concat strings
}
return initTerm;
}


void main()
{
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("%dth term of Thue Morse sequence is: \n", num);
printf("%s\n",calculateSequence(num));
}
2 changes: 1 addition & 1 deletion TrackingProgress.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@
<tr>
<td align=center><p> &#9203;</p></td>
<td><a href="./Thue-Morse sequence">Thue–Morse sequence</a></td>
<td>C++, Java, Python</td>
<td>C++, Java, Python, C</td>
</tr>
<tr>
<td align=center><p> &#9203;</p></td>
Expand Down

0 comments on commit 27d1e02

Please sign in to comment.