title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Determine if a string has all unique characters
C
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
#include<stdbool.h> #include<string.h> #include<stdlib.h> #include<stdio.h> typedef struct positionList{ int position; struct positionList *next; }positionList; typedef struct letterList{ char letter; int repititions; positionList* positions; struct letterList *next; }letterList; letterList* letterSet; bool duplicatesFound = false; void checkAndUpdateLetterList(char c,int pos){ bool letterOccurs = false; letterList *letterIterator,*newLetter; positionList *positionIterator,*newPosition; if(letterSet==NULL){ letterSet = (letterList*)malloc(sizeof(letterList)); letterSet->letter = c; letterSet->repititions = 0; letterSet->positions = (positionList*)malloc(sizeof(positionList)); letterSet->positions->position = pos; letterSet->positions->next = NULL; letterSet->next = NULL; } else{ letterIterator = letterSet; while(letterIterator!=NULL){ if(letterIterator->letter==c){ letterOccurs = true; duplicatesFound = true; letterIterator->repititions++; positionIterator = letterIterator->positions; while(positionIterator->next!=NULL) positionIterator = positionIterator->next; newPosition = (positionList*)malloc(sizeof(positionList)); newPosition->position = pos; newPosition->next = NULL; positionIterator->next = newPosition; } if(letterOccurs==false && letterIterator->next==NULL) break; else letterIterator = letterIterator->next; } if(letterOccurs==false){ newLetter = (letterList*)malloc(sizeof(letterList)); newLetter->letter = c; newLetter->repititions = 0; newLetter->positions = (positionList*)malloc(sizeof(positionList)); newLetter->positions->position = pos; newLetter->positions->next = NULL; newLetter->next = NULL; letterIterator->next = newLetter; } } } void printLetterList(){ positionList* positionIterator; letterList* letterIterator = letterSet; while(letterIterator!=NULL){ if(letterIterator->repititions>0){ printf("\n'%c' (0x%x) at positions :",letterIterator->letter,letterIterator->letter); positionIterator = letterIterator->positions; while(positionIterator!=NULL){ printf("%3d",positionIterator->position + 1); positionIterator = positionIterator->next; } } letterIterator = letterIterator->next; } printf("\n"); } int main(int argc,char** argv) { int i,len; if(argc>2){ printf("Usage : %s <Test string>\n",argv[0]); return 0; } if(argc==1||strlen(argv[1])==1){ printf("\"%s\" - Length %d - Contains only unique characters.\n",argc==1?"":argv[1],argc==1?0:1); return 0; } len = strlen(argv[1]); for(i=0;i<len;i++){ checkAndUpdateLetterList(argv[1][i],i); } printf("\"%s\" - Length %d - %s",argv[1],len,duplicatesFound==false?"Contains only unique characters.\n":"Contains the following duplicate characters :"); if(duplicatesFound==true) printLetterList(); return 0; }
Determine if a string is collapsible
C
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; /* Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library. Comment this out if testing on a compiler where it is already defined. */ int strcmpi(char* str1,char* str2){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Determine if a string is squeezable
C
Determine if a character string is ''squeezable''. And if so, squeeze the string (by removing any number of a ''specified'' ''immediately repeated'' character). This task is very similar to the task '''Determine if a character string is collapsible''' except that only a specified character is ''squeezed'' instead of any character that is ''immediately repeated''. If a character string has a specified ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). A specified ''immediately repeated'' character is any specified character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''squeeze'''.} ;Examples: In the following character string with a specified ''immediately repeated'' character of '''e''': The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''e''' is an specified repeated character, indicated by an underscore (above), even though they (the characters) appear elsewhere in the character string. So, after ''squeezing'' the string, the result would be: The better the 4-whel drive, the further you'll be from help when ya get stuck! Another example: In the following character string, using a specified immediately repeated character '''s''': headmistressship The "squeezed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate a ''specified immediately repeated'' character and ''squeeze'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the specified repeated character (to be searched for and possibly ''squeezed''): :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: immediately string repeated number character ( | a blank, a minus, a seven, a period) ++ 1 |+-----------------------------------------------------------------------+ ' ' <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | '-' 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| '7' 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | '.' 5 | --- Harry S Truman | (below) <###### has many repeated blanks +------------------------------------------------------------------------+ | | | For the 5th string (Truman's signature line), use each of these specified immediately repeated characters: * a blank * a minus * a lowercase '''r''' Note: there should be seven results shown, one each for the 1st four strings, and three results for the 5th string.
#include<string.h> #include<stdlib.h> #include<stdio.h> #define COLLAPSE 0 #define SQUEEZE 1 typedef struct charList{ char c; struct charList *next; } charList; /* Implementing strcmpi, the case insensitive string comparator, as it is not part of the C Standard Library. Comment this out if testing on a compiler where it is already defined. */ int strcmpi(char str1[100],char str2[100]){ int len1 = strlen(str1), len2 = strlen(str2), i; if(len1!=len2){ return 1; } else{ for(i=0;i<len1;i++){ if((str1[i]>='A'&&str1[i]<='Z')&&(str2[i]>='a'&&str2[i]<='z')&&(str2[i]-65!=str1[i])) return 1; else if((str2[i]>='A'&&str2[i]<='Z')&&(str1[i]>='a'&&str1[i]<='z')&&(str1[i]-65!=str2[i])) return 1; else if(str1[i]!=str2[i]) return 1; } } return 0; } charList *strToCharList(char* str){ int len = strlen(str),i; charList *list, *iterator, *nextChar; list = (charList*)malloc(sizeof(charList)); list->c = str[0]; list->next = NULL; iterator = list; for(i=1;i<len;i++){ nextChar = (charList*)malloc(sizeof(charList)); nextChar->c = str[i]; nextChar->next = NULL; iterator->next = nextChar; iterator = nextChar; } return list; } char* charListToString(charList* list){ charList* iterator = list; int count = 0,i; char* str; while(iterator!=NULL){ count++; iterator = iterator->next; } str = (char*)malloc((count+1)*sizeof(char)); iterator = list; for(i=0;i<count;i++){ str[i] = iterator->c; iterator = iterator->next; } free(list); str[i] = '\0'; return str; } char* processString(char str[100],int operation, char squeezeChar){ charList *strList = strToCharList(str),*iterator = strList, *scout; if(operation==SQUEEZE){ while(iterator!=NULL){ if(iterator->c==squeezeChar){ scout = iterator->next; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } else{ while(iterator!=NULL && iterator->next!=NULL){ if(iterator->c == (iterator->next)->c){ scout = iterator->next; squeezeChar = iterator->c; while(scout!=NULL && scout->c==squeezeChar){ iterator->next = scout->next; scout->next = NULL; free(scout); scout = iterator->next; } } iterator = iterator->next; } } return charListToString(strList); } void printResults(char originalString[100], char finalString[100], int operation, char squeezeChar){ if(operation==SQUEEZE){ printf("Specified Operation : SQUEEZE\nTarget Character : %c",squeezeChar); } else printf("Specified Operation : COLLAPSE"); printf("\nOriginal %c%c%c%s%c%c%c\nLength : %d",174,174,174,originalString,175,175,175,(int)strlen(originalString)); printf("\nFinal %c%c%c%s%c%c%c\nLength : %d\n",174,174,174,finalString,175,175,175,(int)strlen(finalString)); } int main(int argc, char** argv){ int operation; char squeezeChar; if(argc<3||argc>4){ printf("Usage : %s <SQUEEZE|COLLAPSE> <String to be processed> <Character to be squeezed, if operation is SQUEEZE>\n",argv[0]); return 0; } if(strcmpi(argv[1],"SQUEEZE")==0 && argc!=4){ scanf("Please enter characted to be squeezed : %c",&squeezeChar); operation = SQUEEZE; } else if(argc==4){ operation = SQUEEZE; squeezeChar = argv[3][0]; } else if(strcmpi(argv[1],"COLLAPSE")==0){ operation = COLLAPSE; } if(strlen(argv[2])<2){ printResults(argv[2],argv[2],operation,squeezeChar); } else{ printResults(argv[2],processString(argv[2],operation,squeezeChar),operation,squeezeChar); } return 0; }
Dice game probabilities
C
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
#include <stdio.h> #include <stdint.h> typedef uint32_t uint; typedef uint64_t ulong; ulong ipow(const uint x, const uint y) { ulong result = 1; for (uint i = 1; i <= y; i++) result *= x; return result; } uint min(const uint x, const uint y) { return (x < y) ? x : y; } void throw_die(const uint n_sides, const uint n_dice, const uint s, uint counts[]) { if (n_dice == 0) { counts[s]++; return; } for (uint i = 1; i < n_sides + 1; i++) throw_die(n_sides, n_dice - 1, s + i, counts); } double beating_probability(const uint n_sides1, const uint n_dice1, const uint n_sides2, const uint n_dice2) { const uint len1 = (n_sides1 + 1) * n_dice1; uint C1[len1]; for (uint i = 0; i < len1; i++) C1[i] = 0; throw_die(n_sides1, n_dice1, 0, C1); const uint len2 = (n_sides2 + 1) * n_dice2; uint C2[len2]; for (uint j = 0; j < len2; j++) C2[j] = 0; throw_die(n_sides2, n_dice2, 0, C2); const double p12 = (double)(ipow(n_sides1, n_dice1) * ipow(n_sides2, n_dice2)); double tot = 0; for (uint i = 0; i < len1; i++) for (uint j = 0; j < min(i, len2); j++) tot += (double)C1[i] * C2[j] / p12; return tot; } int main() { printf("%1.16f\n", beating_probability(4, 9, 6, 6)); printf("%1.16f\n", beating_probability(10, 5, 7, 6)); return 0; }
Digital root
C
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
#include <stdio.h> int droot(long long int x, int base, int *pers) { int d = 0; if (pers) for (*pers = 0; x >= base; x = d, (*pers)++) for (d = 0; x; d += x % base, x /= base); else if (x && !(d = x % (base - 1))) d = base - 1; return d; } int main(void) { int i, d, pers; long long x[] = {627615, 39390, 588225, 393900588225LL}; for (i = 0; i < 4; i++) { d = droot(x[i], 10, &pers); printf("%lld: pers %d, root %d\n", x[i], pers, d); } return 0; }
Disarium numbers
C
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
#include <stdio.h> #include <stdlib.h> #include <math.h> int power (int base, int exponent) { int result = 1; for (int i = 1; i <= exponent; i++) { result *= base; } return result; } int is_disarium (int num) { int n = num; int sum = 0; int len = n <= 9 ? 1 : floor(log10(n)) + 1; while (n > 0) { sum += power(n % 10, len); n /= 10; len--; } return num == sum; } int main() { int count = 0; int i = 0; while (count < 19) { if (is_disarium(i)) { printf("%d ", i); count++; } i++; } printf("%s\n", "\n"); }
Display a linear combination
C
Display a finite linear combination in an infinite vector basis (e_1, e_2,\ldots). Write a function that, when given a finite list of scalars (\alpha^1,\alpha^2,\ldots), creates a string representing the linear combination \sum_i\alpha^i e_i in an explicit format often used in mathematics, that is: :\alpha^{i_1}e_{i_1}\pm|\alpha^{i_2}|e_{i_2}\pm|\alpha^{i_3}|e_{i_3}\pm\ldots where \alpha^{i_k}\neq 0 The output must comply to the following rules: * don't show null terms, unless the whole combination is null. ::::::: '''e(1)''' is fine, '''e(1) + 0*e(3)''' or '''e(1) + 0''' is wrong. * don't show scalars when they are equal to one or minus one. ::::::: '''e(3)''' is fine, '''1*e(3)''' is wrong. * don't prefix by a minus sign if it follows a preceding term. Instead you use subtraction. ::::::: '''e(4) - e(5)''' is fine, '''e(4) + -e(5)''' is wrong. Show here output for the following lists of scalars: 1) 1, 2, 3 2) 0, 1, 2, 3 3) 1, 0, 3, 4 4) 1, 2, 0 5) 0, 0, 0 6) 0 7) 1, 1, 1 8) -1, -1, -1 9) -1, -2, 0, -3 10) -1
#include<stdlib.h> #include<stdio.h> #include<math.h> /*Optional, but better if included as fabs, labs and abs functions are being used. */ int main(int argC, char* argV[]) { int i,zeroCount= 0,firstNonZero = -1; double* vector; if(argC == 1){ printf("Usage : %s <Vector component coefficients seperated by single space>",argV[0]); } else{ printf("Vector for ["); for(i=1;i<argC;i++){ printf("%s,",argV[i]); } printf("\b] -> "); vector = (double*)malloc((argC-1)*sizeof(double)); for(i=1;i<=argC;i++){ vector[i-1] = atof(argV[i]); if(vector[i-1]==0.0) zeroCount++; if(vector[i-1]!=0.0 && firstNonZero==-1) firstNonZero = i-1; } if(zeroCount == argC){ printf("0"); } else{ for(i=0;i<argC;i++){ if(i==firstNonZero && vector[i]==1) printf("e%d ",i+1); else if(i==firstNonZero && vector[i]==-1) printf("- e%d ",i+1); else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])>0.0) printf("- %lf e%d ",fabs(vector[i]),i+1); else if(i==firstNonZero && vector[i]<0 && fabs(vector[i])-abs(vector[i])==0.0) printf("- %ld e%d ",labs(vector[i]),i+1); else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])>0.0) printf("%lf e%d ",vector[i],i+1); else if(i==firstNonZero && vector[i]>0 && fabs(vector[i])-abs(vector[i])==0.0) printf("%ld e%d ",vector[i],i+1); else if(fabs(vector[i])==1.0 && i!=0) printf("%c e%d ",(vector[i]==-1)?'-':'+',i+1); else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])>0.0) printf("%c %lf e%d ",(vector[i]<0)?'-':'+',fabs(vector[i]),i+1); else if(i!=0 && vector[i]!=0 && fabs(vector[i])-abs(vector[i])==0.0) printf("%c %ld e%d ",(vector[i]<0)?'-':'+',labs(vector[i]),i+1); } } } free(vector); return 0; }
Diversity prediction theorem
C
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
#include<string.h> #include<stdlib.h> #include<stdio.h> float mean(float* arr,int size){ int i = 0; float sum = 0; while(i != size) sum += arr[i++]; return sum/size; } float variance(float reference,float* arr, int size){ int i=0; float* newArr = (float*)malloc(size*sizeof(float)); for(;i<size;i++) newArr[i] = (reference - arr[i])*(reference - arr[i]); return mean(newArr,size); } float* extractData(char* str, int *len){ float* arr; int i=0,count = 1; char* token; while(str[i]!=00){ if(str[i++]==',') count++; } arr = (float*)malloc(count*sizeof(float)); *len = count; token = strtok(str,","); i = 0; while(token!=NULL){ arr[i++] = atof(token); token = strtok(NULL,","); } return arr; } int main(int argC,char* argV[]) { float* arr,reference,meanVal; int len; if(argC!=3) printf("Usage : %s <reference value> <observations separated by commas>"); else{ arr = extractData(argV[2],&len); reference = atof(argV[1]); meanVal = mean(arr,len); printf("Average Error : %.9f\n",variance(reference,arr,len)); printf("Crowd Error : %.9f\n",(reference - meanVal)*(reference - meanVal)); printf("Diversity : %.9f",variance(meanVal,arr,len)); } return 0; }
Doomsday rule
C
About the task John Conway (1937-2020), was a mathematician who also invented several mathematically oriented computer pastimes, such as the famous Game of Life cellular automaton program. Dr. Conway invented a simple algorithm for finding the day of the week, given any date. The algorithm was based on calculating the distance of a given date from certain "anchor days" which follow a pattern for the day of the week upon which they fall. ; Algorithm The formula is calculated assuming that Sunday is 0, Monday 1, and so forth with Saturday 7, and doomsday = (Tuesday(or 2) + 5(y mod 4) + 4(y mod 100) + 6(y mod 400)) % 7 which, for 2021, is 0 (Sunday). To calculate the day of the week, we then count days from a close doomsday, with these as charted here by month, then add the doomsday for the year, then get the remainder after dividing by 7. This should give us the number corresponding to the day of the week for that date. Month Doomsday Dates for Month -------------------------------------------- January (common years) 3, 10, 17, 24, 31 January (leap years) 4, 11, 18, 25 February (common years) 7, 14, 21, 28 February (leap years) 1, 8, 15, 22, 29 March 7, 14, 21, 28 April 4, 11, 18, 25 May 2, 9, 16, 23, 30 June 6, 13, 20, 27 July 4, 11, 18, 25 August 1, 8, 15, 22, 29 September 5, 12, 19, 26 October 3, 10, 17, 24, 31 November 7, 14, 21, 28 December 5, 12, 19, 26 ; Task Given the following dates: * 1800-01-06 (January 6, 1800) * 1875-03-29 (March 29, 1875) * 1915-12-07 (December 7, 1915) * 1970-12-23 (December 23, 1970) * 2043-05-14 (May 14, 2043) * 2077-02-12 (February 12, 2077) * 2101-04-02 (April 2, 2101) Use Conway's Doomsday rule to calculate the day of the week for each date. ; see also * Doomsday rule * Tomorrow is the Day After Doomsday (p.28)
#include <stdio.h> #include <stdint.h> #include <stdbool.h> typedef struct { uint16_t year; uint8_t month; uint8_t day; } Date; bool leap(uint16_t year) { return year%4==0 && (year%100!=0 || year%400==0); } const char *weekday(Date date) { static const uint8_t leapdoom[] = {4,1,7,2,4,6,4,1,5,3,7,5}; static const uint8_t normdoom[] = {3,7,7,4,2,6,4,1,5,3,7,5}; static const char *days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; unsigned c = date.year/100, r = date.year%100; unsigned s = r/12, t = r%12; unsigned c_anchor = (5 * (c%4) + 2) % 7; unsigned doom = (s + t + (t/4) + c_anchor) % 7; unsigned anchor = (leap(date.year) ? leapdoom : normdoom)[date.month-1]; return days[(doom+date.day-anchor+7)%7]; } int main(void) { const char *past = "was", *future = "will be"; const char *months[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; const Date dates[] = { {1800,1,6}, {1875,3,29}, {1915,12,7}, {1970,12,23}, {2043,5,14}, {2077,2,12}, {2101,4,2} }; int i; for (i=0; i < sizeof(dates)/sizeof(Date); i++) { printf("%s %d, %d %s on a %s.\n", months[dates[i].month], dates[i].day, dates[i].year, dates[i].year > 2021 ? future : past, weekday(dates[i])); } return 0; }
Dot product
C
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
#include <stdio.h> #include <stdlib.h> int dot_product(int *, int *, size_t); int main(void) { int a[3] = {1, 3, -5}; int b[3] = {4, -2, -1}; printf("%d\n", dot_product(a, b, sizeof(a) / sizeof(a[0]))); return EXIT_SUCCESS; } int dot_product(int *a, int *b, size_t n) { int sum = 0; size_t i; for (i = 0; i < n; i++) { sum += a[i] * b[i]; } return sum; }
Draw a clock
C
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
// clockrosetta.c - https://rosettacode.org/wiki/Draw_a_clock // # Makefile // CFLAGS = -O3 -Wall -Wfatal-errors -Wpedantic -Werror // LDLIBS = -lX11 -lXext -lm // all: clockrosetta #define SIZE 500 #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/select.h> #include <time.h> #include <X11/extensions/Xdbe.h> #include <math.h> static XdbeBackBuffer dbewindow = 0; static Display *display; static Window window; static int needseg = 1; static double d2r; static XSegment seg[61]; static GC gc; static int mw = SIZE / 2; static int mh = SIZE / 2; static void draw(void) { struct tm *ptm; int i; double angle; double delta; int radius = (mw < mh ? mw : mh) - 2; XPoint pt[3]; double onetwenty = 3.1415926 * 2 / 3; XdbeSwapInfo swapi; time_t newtime; if(dbewindow == 0) { dbewindow = XdbeAllocateBackBufferName(display, window, XdbeBackground); XClearWindow(display, window); } time(&newtime); ptm = localtime(&newtime); if(needseg) { d2r = atan2(1.0, 0.0) / 90.0; for(i = 0; i < 60; i++) { angle = (double)i * 6.0 * d2r; delta = i % 5 ? 0.97 : 0.9; seg[i].x1 = mw + radius * delta * sin(angle); seg[i].y1 = mh - radius * delta * cos(angle); seg[i].x2 = mw + radius * sin(angle); seg[i].y2 = mh - radius * cos(angle); } needseg = 0; } angle = (double)(ptm->tm_sec) * 6.0 * d2r; seg[60].x1 = mw; seg[60].y1 = mh; seg[60].x2 = mw + radius * 0.9 * sin(angle); seg[60].y2 = mh - radius * 0.9 * cos(angle); XDrawSegments(display, dbewindow, gc, seg, 61); angle = (double)ptm->tm_min * 6.0 * d2r; pt[0].x = mw + radius * 3 / 4 * sin(angle); pt[0].y = mh - radius * 3 / 4 * cos(angle); pt[1].x = mw + 6 * sin(angle + onetwenty); pt[1].y = mh - 6 * cos(angle + onetwenty); pt[2].x = mw + 6 * sin(angle - onetwenty); pt[2].y = mh - 6 * cos(angle - onetwenty); XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin); angle = (double)(ptm->tm_hour * 60 + ptm->tm_min) / 2.0 * d2r; pt[0].x = mw + radius / 2 * sin(angle); pt[0].y = mh - radius / 2 * cos(angle); pt[1].x = mw + 6 * sin(angle + onetwenty); pt[1].y = mh - 6 * cos(angle + onetwenty); pt[2].x = mw + 6 * sin(angle - onetwenty); pt[2].y = mh - 6 * cos(angle - onetwenty); XFillPolygon(display, dbewindow, gc, pt, 3, Nonconvex, CoordModeOrigin); swapi.swap_window = window; swapi.swap_action = XdbeBackground; XdbeSwapBuffers(display, &swapi, 1); } int main(int argc, char *argv[]) { Atom wm_both_protocols[1]; Atom wm_delete; Atom wm_protocols; Window root; XEvent event; XSetWindowAttributes attr; fd_set fd; int exposed = 0; int more = 1; struct timeval tv; display = XOpenDisplay(NULL); if(display == NULL) { fprintf(stderr,"Error: The display cannot be opened\n"); exit(1); } root = DefaultRootWindow(display); wm_delete = XInternAtom(display, "WM_DELETE_WINDOW", False); wm_protocols = XInternAtom(display, "WM_PROTOCOLS", False); attr.background_pixel = 0x000000; attr.event_mask = KeyPress | KeyRelease | ButtonPressMask | ButtonReleaseMask | ExposureMask; window = XCreateWindow(display, root, 0, 0, SIZE, SIZE, 0, CopyFromParent, InputOutput, CopyFromParent, CWBackPixel | CWEventMask, &attr ); XStoreName(display, window, "Clock for RosettaCode"); wm_both_protocols[0] = wm_delete; XSetWMProtocols(display, window, wm_both_protocols, 1); gc = XCreateGC(display, window, 0, NULL); XSetForeground(display, gc, 0xFFFF80); XMapWindow(display, window); while(more) { if(QLength(display) > 0) { XNextEvent(display, &event); } else { int maxfd = ConnectionNumber(display); XFlush(display); FD_ZERO(&fd); FD_SET(ConnectionNumber(display), &fd); event.type = LASTEvent; tv.tv_sec = 0; tv.tv_usec = 250000; if(select(maxfd + 1, &fd, NULL, NULL, &tv) > 0) { if(FD_ISSET(ConnectionNumber(display), &fd)) { XNextEvent(display, &event); } } } switch(event.type) { case Expose: exposed = 1; draw(); break; case ButtonRelease: case KeyRelease: more = 0; case ButtonPress: // ignore case KeyPress: // ignore break; case LASTEvent: // the timeout comes here if(exposed) draw(); break; case ConfigureNotify: mw = event.xconfigure.width / 2; mh = event.xconfigure.height / 2; needseg = 1; break; case ClientMessage: // for close request from WM if(event.xclient.window == window && event.xclient.message_type == wm_protocols && event.xclient.format == 32 && event.xclient.data.l[0] == wm_delete) { more = 0; } break; // default: // printf("unexpected event.type %d\n", event.type);; } } XCloseDisplay(display); exit(0); } // END
Draw a rotating cube
C
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. ;Related tasks * Draw a cuboid * write language name in 3D ASCII
#include<gl/freeglut.h> double rot = 0; float matCol[] = {1,0,0,0}; void display(){ glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glPushMatrix(); glRotatef(30,1,1,0); glRotatef(rot,0,1,1); glMaterialfv(GL_FRONT,GL_DIFFUSE,matCol); glutWireCube(1); glPopMatrix(); glFlush(); } void onIdle(){ rot += 0.1; glutPostRedisplay(); } void reshape(int w,int h){ float ar = (float) w / (float) h ; glViewport(0,0,(GLsizei)w,(GLsizei)h); glTranslatef(0,0,-10); glMatrixMode(GL_PROJECTION); gluPerspective(70,(GLfloat)w/(GLfloat)h,1,12); glLoadIdentity(); glFrustum ( -1.0, 1.0, -1.0, 1.0, 10.0, 100.0 ) ; glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void init(){ float pos[] = {1,1,1,0}; float white[] = {1,1,1,0}; float shini[] = {70}; glClearColor(.5,.5,.5,0); glShadeModel(GL_SMOOTH); glLightfv(GL_LIGHT0,GL_AMBIENT,white); glLightfv(GL_LIGHT0,GL_DIFFUSE,white); glMaterialfv(GL_FRONT,GL_SHININESS,shini); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); } int main(int argC, char* argV[]) { glutInit(&argC,argV); glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB|GLUT_DEPTH); glutInitWindowSize(600,500); glutCreateWindow("Rossetta's Rotating Cube"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(onIdle); glutMainLoop(); return 0; }
Draw a sphere
C
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> const char *shades = ".:!*oe&#%@"; double light[3] = { 30, 30, -50 }; void normalize(double * v) { double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); v[0] /= len; v[1] /= len; v[2] /= len; } double dot(double *x, double *y) { double d = x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; return d < 0 ? -d : 0; } void draw_sphere(double R, double k, double ambient) { int i, j, intensity; double b; double vec[3], x, y; for (i = floor(-R); i <= ceil(R); i++) { x = i + .5; for (j = floor(-2 * R); j <= ceil(2 * R); j++) { y = j / 2. + .5; if (x * x + y * y <= R * R) { vec[0] = x; vec[1] = y; vec[2] = sqrt(R * R - x * x - y * y); normalize(vec); b = pow(dot(light, vec), k) + ambient; intensity = (1 - b) * (sizeof(shades) - 1); if (intensity < 0) intensity = 0; if (intensity >= sizeof(shades) - 1) intensity = sizeof(shades) - 2; putchar(shades[intensity]); } else putchar(' '); } putchar('\n'); } } int main() { normalize(light); draw_sphere(20, 4, .1); draw_sphere(10, 2, .4); return 0; }
Dutch national flag problem
C
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
#include <stdio.h> //printf() #include <stdlib.h> //srand(), rand(), RAND_MAX, qsort() #include <stdbool.h> //true, false #include <time.h> //time() #define NUMBALLS 5 //NUMBALLS>1 int compar(const void *a, const void *b){ char c1=*(const char*)a, c2=*(const char*)b; //first cast void* to char*, then dereference return c1-c2; } _Bool issorted(char *balls){ int i,state; state=0; for(i=0;i<NUMBALLS;i++){ if(balls[i]<state)return false; if(balls[i]>state)state=balls[i]; } return true; } void printout(char *balls){ int i; char str[NUMBALLS+1]; for(i=0;i<NUMBALLS;i++)str[i]=balls[i]==0?'r':balls[i]==1?'w':'b'; printf("%s\n",str); } int main(void) { char balls[NUMBALLS]; //0=r, 1=w, 2=b int i; srand(time(NULL)); //not a good seed but good enough for the example rand(); //rand() always starts with the same values for certain seeds, making // testing pretty irritating // Generate balls for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3; while(issorted(balls)){ //enforce that we start with non-sorted balls printf("Accidentally still sorted: "); printout(balls); for(i=0;i<NUMBALLS;i++)balls[i]=(double)rand()/RAND_MAX*3; } printf("Non-sorted: "); printout(balls); qsort(balls,NUMBALLS,sizeof(char),compar); //sort them using quicksort (stdlib) if(issorted(balls)){ //unnecessary check but task enforces it printf("Sorted: "); printout(balls); } else { printf("Sort failed: "); printout(balls); } return 0; }
Egyptian division
C
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <assert.h> uint64_t egyptian_division(uint64_t dividend, uint64_t divisor, uint64_t *remainder) { // remainder is an out parameter, pass NULL if you do not need the remainder static uint64_t powers[64]; static uint64_t doublings[64]; int i; for(i = 0; i < 64; i++) { powers[i] = 1 << i; doublings[i] = divisor << i; if(doublings[i] > dividend) break; } uint64_t answer = 0; uint64_t accumulator = 0; for(i = i - 1; i >= 0; i--) { // If the current value of the accumulator added to the // doublings cell would be less than or equal to the // dividend then add it to the accumulator if(accumulator + doublings[i] <= dividend) { accumulator += doublings[i]; answer += powers[i]; } } if(remainder) *remainder = dividend - accumulator; return answer; } void go(uint64_t a, uint64_t b) { uint64_t x, y; x = egyptian_division(a, b, &y); printf("%llu / %llu = %llu remainder %llu\n", a, b, x, y); assert(a == b * x + y); } int main(void) { go(580, 32); }
Elementary cellular automaton
C
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
#include <stdio.h> #include <limits.h> typedef unsigned long long ull; #define N (sizeof(ull) * CHAR_BIT) #define B(x) (1ULL << (x)) void evolve(ull state, int rule) { int i; ull st; printf("Rule %d:\n", rule); do { st = state; for (i = N; i--; ) putchar(st & B(i) ? '#' : '.'); putchar('\n'); for (state = i = 0; i < N; i++) if (rule & B(7 & (st>>(i-1) | st<<(N+1-i)))) state |= B(i); } while (st != state); } int main(int argc, char **argv) { evolve(B(N/2), 90); evolve(B(N/4)|B(N - N/4), 30); // well, enjoy the fireworks return 0; }
Elementary cellular automaton/Random number generator
C
Mathematica software for its default random number generator. Steven Wolfram's recommendation for random number generation from rule 30 consists in extracting successive bits in a fixed position in the array of cells, as the automaton changes state. The purpose of this task is to demonstrate this. With the code written in the most significant. You can pick which ever length you want for the initial array but it should be visible in the code so that your output can be reproduced with an other language. For extra-credits, you will make this algorithm run as fast as possible in your language, for instance with an extensive use of bitwise logic. ;Reference: * Cellular automata: Is Rule 30 random? (PDF).
#include <stdio.h> #include <limits.h> typedef unsigned long long ull; #define N (sizeof(ull) * CHAR_BIT) #define B(x) (1ULL << (x)) void evolve(ull state, int rule) { int i, p, q, b; for (p = 0; p < 10; p++) { for (b = 0, q = 8; q--; ) { ull st = state; b |= (st&1) << q; for (state = i = 0; i < N; i++) if (rule & B(7 & (st>>(i-1) | st<<(N+1-i)))) state |= B(i); } printf(" %d", b); } putchar('\n'); return; } int main(void) { evolve(1, 30); return 0; }
Elliptic curve arithmetic
C
digital signatures. The purpose of this task is to implement a simplified (without modular arithmetic) version of the elliptic curve arithmetic which is required by the elliptic curve DSA protocol. In a nutshell, an elliptic curve is a bi-dimensional curve defined by the following relation between the '''x''' and '''y''' coordinates of any point on the curve: :::: y^2 = x^3 + a x + b '''a''' and '''b''' are arbitrary parameters that define the specific curve which is used. For this particular task, we'll use the following parameters: :::: a=0, b=7 The most interesting thing about elliptic curves is the fact that it is possible to define a group structure on it. To do so we define an internal composition rule with an additive notation '''+''', such that for any three distinct points '''P''', '''Q''' and '''R''' on the curve, whenever these points are aligned, we have: :::: P + Q + R = 0 Here '''0''' (zero) is the ''infinity point'', for which the '''x''' and '''y''' values are not defined. It's basically the same kind of point which defines the horizon in projective geometry. We'll also assume here that this infinity point is unique and defines the neutral element of the addition. This was not the definition of the addition, but only its desired property. For a more accurate definition, we proceed as such: Given any three aligned points '''P''', '''Q''' and '''R''', we define the sum '''S = P + Q''' as the point (possibly the infinity point) such that '''S''', '''R''' and the infinity point are aligned. Considering the symmetry of the curve around the x-axis, it's easy to convince oneself that two points '''S''' and '''R''' can be aligned with the infinity point if and only if '''S''' and '''R''' are symmetric of one another towards the x-axis (because in that case there is no other candidate than the infinity point to complete the alignment triplet). '''S''' is thus defined as the symmetric of '''R''' towards the '''x''' axis. The task consists in defining the addition which, for any two points of the curve, returns the sum of these two points. You will pick two random points on the curve, compute their sum and show that the symmetric of the sum is aligned with the two initial points. You will use the '''a''' and '''b''' parameters of secp256k1, i.e. respectively zero and seven. ''Hint'': You might need to define a "doubling" function, that returns '''P+P''' for any given point '''P'''. ''Extra credit'': define the full elliptic curve arithmetic (still not modular, though) by defining a "multiply" function that returns, for any point '''P''' and integer '''n''', the point '''P + P + ... + P''' ('''n''' times).
#include <stdio.h> #include <math.h> #define C 7 typedef struct { double x, y; } pt; pt zero(void) { return (pt){ INFINITY, INFINITY }; } // should be INFINITY, but numeric precision is very much in the way int is_zero(pt p) { return p.x > 1e20 || p.x < -1e20; } pt neg(pt p) { return (pt){ p.x, -p.y }; } pt dbl(pt p) { if (is_zero(p)) return p; pt r; double L = (3 * p.x * p.x) / (2 * p.y); r.x = L * L - 2 * p.x; r.y = L * (p.x - r.x) - p.y; return r; } pt add(pt p, pt q) { if (p.x == q.x && p.y == q.y) return dbl(p); if (is_zero(p)) return q; if (is_zero(q)) return p; pt r; double L = (q.y - p.y) / (q.x - p.x); r.x = L * L - p.x - q.x; r.y = L * (p.x - r.x) - p.y; return r; } pt mul(pt p, int n) { int i; pt r = zero(); for (i = 1; i <= n; i <<= 1) { if (i & n) r = add(r, p); p = dbl(p); } return r; } void show(const char *s, pt p) { printf("%s", s); printf(is_zero(p) ? "Zero\n" : "(%.3f, %.3f)\n", p.x, p.y); } pt from_y(double y) { pt r; r.x = pow(y * y - C, 1.0/3); r.y = y; return r; } int main(void) { pt a, b, c, d; a = from_y(1); b = from_y(2); show("a = ", a); show("b = ", b); show("c = a + b = ", c = add(a, b)); show("d = -c = ", d = neg(c)); show("c + d = ", add(c, d)); show("a + b + d = ", add(a, add(b, d))); show("a * 12345 = ", mul(a, 12345)); return 0; }
Empty directory
C
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
#include <stdio.h> #include <dirent.h> #include <string.h> int dir_empty(const char *path) { struct dirent *ent; int ret = 1; DIR *d = opendir(path); if (!d) { fprintf(stderr, "%s: ", path); perror(""); return -1; } while ((ent = readdir(d))) { if (!strcmp(ent->d_name, ".") || !(strcmp(ent->d_name, ".."))) continue; ret = 0; break; } closedir(d); return ret; } int main(int c, char **v) { int ret = 0, i; if (c < 2) return -1; for (i = 1; i < c; i++) { ret = dir_empty(v[i]); if (ret >= 0) printf("%s: %sempty\n", v[i], ret ? "" : "not "); } return 0; }
Empty string
C
Languages may have features for dealing specifically with empty strings (those containing no characters). ;Task: ::* Demonstrate how to assign an empty string to a variable. ::* Demonstrate how to check that a string is empty. ::* Demonstrate how to check that a string is not empty.
#include <string.h> /* ... */ /* assign an empty string */ const char *str = ""; /* to test a null string */ if (str) { ... } /* to test if string is empty */ if (str[0] == '\0') { ... } /* or equivalently use strlen function strlen will seg fault on NULL pointer, so check first */ if ( (str == NULL) || (strlen(str) == 0)) { ... } /* or compare to a known empty string, same thing. "== 0" means strings are equal */ if (strcmp(str, "") == 0) { ... }
Entropy/Narcissist
C
Write a computer program that computes and shows its own [[entropy]]. ;Related Tasks: :* [[Fibonacci_word]] :* [[Entropy]]
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <math.h> #define MAXLEN 961 //maximum string length int makehist(char *S,int *hist,int len){ int wherechar[256]; int i,histlen; histlen=0; for(i=0;i<256;i++)wherechar[i]=-1; for(i=0;i<len;i++){ if(wherechar[(int)S[i]]==-1){ wherechar[(int)S[i]]=histlen; histlen++; } hist[wherechar[(int)S[i]]]++; } return histlen; } double entropy(int *hist,int histlen,int len){ int i; double H; H=0; for(i=0;i<histlen;i++){ H-=(double)hist[i]/len*log2((double)hist[i]/len); } return H; } int main(void){ char S[MAXLEN]; int len,*hist,histlen; double H; FILE *f; f=fopen("entropy.c","r"); for(len=0;!feof(f);len++)S[len]=fgetc(f); S[--len]='\0'; hist=(int*)calloc(len,sizeof(int)); histlen=makehist(S,hist,len); //hist now has no order (known to the program) but that doesn't matter H=entropy(hist,histlen,len); printf("%lf\n",H); return 0; }
Equilibrium index
C
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
#include <stdio.h> #include <stdlib.h> int list[] = {-7, 1, 5, 2, -4, 3, 0}; int eq_idx(int *a, int len, int **ret) { int i, sum, s, cnt; /* alloc long enough: if we can afford the original list, * we should be able to afford to this. Beats a potential * million realloc() calls. Even if memory is a real concern, * there's no garantee the result is shorter than the input anyway */ cnt = s = sum = 0; *ret = malloc(sizeof(int) * len); for (i = 0; i < len; i++) sum += a[i]; for (i = 0; i < len; i++) { if (s * 2 + a[i] == sum) { (*ret)[cnt] = i; cnt++; } s += a[i]; } /* uncouraged way to use realloc since it can leak memory, for example */ *ret = realloc(*ret, cnt * sizeof(int)); return cnt; } int main() { int i, cnt, *idx; cnt = eq_idx(list, sizeof(list) / sizeof(int), &idx); printf("Found:"); for (i = 0; i < cnt; i++) printf(" %d", idx[i]); printf("\n"); return 0; }
Euler's identity
C
{{Wikipedia|Euler's_identity}} In mathematics, ''Euler's identity'' is the equality: ei\pi + 1 = 0 where e is Euler's number, the base of natural logarithms, ''i'' is the imaginary unit, which satisfies ''i''2 = -1, and \pi is pi, the ratio of the circumference of a circle to its diameter. Euler's identity is often cited as an example of deep mathematical beauty. Three of the basic arithmetic operations occur exactly once each: addition, multiplication, and exponentiation. The identity also links five fundamental mathematical constants: The number 0. The number 1. The number \pi (\pi = 3.14159+), The number e (e = 2.71828+), which occurs widely in mathematical analysis. The number ''i'', the imaginary unit of the complex numbers. ;Task Show in your language that Euler's identity is true. As much as possible and practical, mimic the Euler's identity equation. Most languages are limited to IEEE 754 floating point calculations so will have some error in the calculation. If that is the case, or there is some other limitation, show that ei\pi + 1 is ''approximately'' equal to zero and show the amount of error in the calculation. If your language is capable of symbolic calculations, show that ei\pi + 1 is ''exactly'' equal to zero for bonus kudos points.
#include <stdio.h> #include <math.h> #include <complex.h> #include <wchar.h> #include <locale.h> int main() { wchar_t pi = L'\u03c0'; /* Small pi symbol */ wchar_t ae = L'\u2245'; /* Approximately equals symbol */ double complex e = cexp(M_PI * I) + 1.0; setlocale(LC_CTYPE, ""); printf("e ^ %lci + 1 = [%.16f, %.16f] %lc 0\n", pi, creal(e), cimag(e), ae); return 0; }
Euler's sum of powers conjecture
C
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
// Alexander Maximov, July 2nd, 2015 #include <stdio.h> #include <time.h> typedef long long mylong; void compute(int N, char find_only_one_solution) { const int M = 30; /* x^5 == x modulo M=2*3*5 */ int a, b, c, d, e; mylong s, t, max, *p5 = (mylong*)malloc(sizeof(mylong)*(N+M)); for(s=0; s < N; ++s) p5[s] = s * s, p5[s] *= p5[s] * s; for(max = p5[N - 1]; s < (N + M); p5[s++] = max + 1); for(a = 1; a < N; ++a) for(b = a + 1; b < N; ++b) for(c = b + 1; c < N; ++c) for(d = c + 1, e = d + ((t = p5[a] + p5[b] + p5[c]) % M); ((s = t + p5[d]) <= max); ++d, ++e) { for(e -= M; p5[e + M] <= s; e += M); /* jump over M=30 values for e>d */ if(p5[e] == s) { printf("%d %d %d %d %d\r\n", a, b, c, d, e); if(find_only_one_solution) goto onexit; } } onexit: free(p5); } int main(void) { int tm = clock(); compute(250, 0); printf("time=%d milliseconds\r\n", (int)((clock() - tm) * 1000 / CLOCKS_PER_SEC)); return 0; }
Even or odd
C
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
mpz_t x; ... if (mpz_even_p(x)) { /* x is even */ } if (mpz_odd_p(x)) { /* x is odd */ }
Evolutionary algorithm
C
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
#include <stdio.h> #include <stdlib.h> #include <string.h> const char target[] = "METHINKS IT IS LIKE A WEASEL"; const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ "; #define CHOICE (sizeof(tbl) - 1) #define MUTATE 15 #define COPIES 30 /* returns random integer from 0 to n - 1 */ int irand(int n) { int r, rand_max = RAND_MAX - (RAND_MAX % n); while((r = rand()) >= rand_max); return r / (rand_max / n); } /* number of different chars between a and b */ int unfitness(const char *a, const char *b) { int i, sum = 0; for (i = 0; a[i]; i++) sum += (a[i] != b[i]); return sum; } /* each char of b has 1/MUTATE chance of differing from a */ void mutate(const char *a, char *b) { int i; for (i = 0; a[i]; i++) b[i] = irand(MUTATE) ? a[i] : tbl[irand(CHOICE)]; b[i] = '\0'; } int main() { int i, best_i, unfit, best, iters = 0; char specimen[COPIES][sizeof(target) / sizeof(char)]; /* init rand string */ for (i = 0; target[i]; i++) specimen[0][i] = tbl[irand(CHOICE)]; specimen[0][i] = 0; do { for (i = 1; i < COPIES; i++) mutate(specimen[0], specimen[i]); /* find best fitting string */ for (best_i = i = 0; i < COPIES; i++) { unfit = unfitness(target, specimen[i]); if(unfit < best || !i) { best = unfit; best_i = i; } } if (best_i) strcpy(specimen[0], specimen[best_i]); printf("iter %d, score %d: %s\n", iters++, best, specimen[0]); } while (best); return 0; }
Executable library
C
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. '''Task detail''' * Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the [[Hailstone sequence]] for that number. * The library, when executed directly should satisfy the remaining requirements of the [[Hailstone sequence]] task: :: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 :: 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. * Create a second executable to calculate the following: ** Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 <= n < 100,000. * Explain any extra setup/run steps needed to complete the task. '''Notes:''' * It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed ''not'' to be present in the runtime environment. * Interpreters are present in the runtime environment.
#include <stdio.h> #include <stdlib.h> long hailstone(long n, long **seq) { long len = 0, buf_len = 4; if (seq) *seq = malloc(sizeof(long) * buf_len); while (1) { if (seq) { if (len >= buf_len) { buf_len *= 2; *seq = realloc(*seq, sizeof(long) * buf_len); } (*seq)[len] = n; } len ++; if (n == 1) break; if (n & 1) n = 3 * n + 1; else n >>= 1; } return len; } void free_sequence(long * s) { free(s); } const char my_interp[] __attribute__((section(".interp"))) = "/lib/ld-linux.so.2"; /* "ld-linux.so.2" should be whatever you use on your platform */ int hail_main() /* entry point when running along, see compiler command line */ { long i, *seq; long len = hailstone(27, &seq); printf("27 has %ld numbers in sequence:\n", len); for (i = 0; i < len; i++) { printf("%ld ", seq[i]); } printf("\n"); free_sequence(seq); exit(0); }
Execute HQ9+
C
Implement a ''' [[HQ9+]] ''' interpreter or compiler.
void runCode(const char *code) { int c_len = strlen(code); int i, bottles; unsigned accumulator=0; for(i=0;i<c_len;i++) { switch(code[i]) { case 'Q': printf("%s\n", code); break; case 'H': printf("Hello, world!\n"); break; case '9': //Nice bottles song alg. from RC :) bottles = 99; do { printf("%d bottles of beer on the wall\n", bottles); printf("%d bottles of beer\n", bottles); printf("Take one down, pass it around\n"); printf("%d bottles of beer on the wall\n\n", --bottles); } while( bottles > 0 ); break; case '+': //Am I the only one finding this one weird? :o accumulator++; break; } } };
Exponentiation order
C
This task will demonstrate the order of exponentiation ('''xy''') when there are multiple exponents. (Many programming languages, especially those with extended-precision integer arithmetic, usually support one of **, ^, | or some such for exponentiation.) ;Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification): ::::* 5**3**2 ::::* (5**3)**2 ::::* 5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. ;See also: * MathWorld entry: exponentiation ;Related tasks: * exponentiation operator * arbitrary-precision integers (included) * [[Exponentiation with infix operators in (or operating on) the base]]
#include<stdio.h> #include<math.h> int main() { printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2)); printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2))); return 0; }
Extend your language
C
{{Control Structures}}Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on ''two'' conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword '''if2'''. It is similar to '''if''', but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#include <stdio.h> #define if2(a, b) switch(((a)) + ((b)) * 2) { case 3: #define else00 break; case 0: /* both false */ #define else10 break; case 1: /* true, false */ #define else01 break; case 2: /* false, true */ #define else2 break; default: /* anything not metioned */ #define fi2 } /* stupid end bracket */ int main() { int i, j; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { printf("%d %d: ", i, j); if2 (i == 1, j == 1) printf("both\n"); else10 printf("left\n"); else01 printf("right\n"); else00 { /* <-- bracket is optional, flaw */, printf("neither\n"); if2 (i == 2, j == 2) printf("\tis 22"); printf("\n"); /* flaw: this is part of if2! */ else2 printf("\tnot 22\n"); fi2 } fi2 } return 0; }
Extreme floating point values
C
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. ;See also: * What Every Computer Scientist Should Know About Floating-Point Arithmetic ;Related tasks: * [[Infinity]] * [[Detect division by zero]] * [[Literals/Floating point]]
Note: Under the C standard, division by zero (of any type) is undefined behavior. : The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined. : -- C99 standard, section 6.5.5 paragraph 5 Floating-point division by zero in the following examples to obtain infinity or NaN are dependent on implementation-specific behavior.
FASTA format
C
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { FILE * fp; char * line = NULL; size_t len = 0; ssize_t read; fp = fopen("fasta.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); int state = 0; while ((read = getline(&line, &len, fp)) != -1) { /* Delete trailing newline */ if (line[read - 1] == '\n') line[read - 1] = 0; /* Handle comment lines*/ if (line[0] == '>') { if (state == 1) printf("\n"); printf("%s: ", line+1); state = 1; } else { /* Print everything else */ printf("%s", line); } } printf("\n"); fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); }
Fairshare between two and more
C
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
#include <stdio.h> #include <stdlib.h> int turn(int base, int n) { int sum = 0; while (n != 0) { int rem = n % base; n = n / base; sum += rem; } return sum % base; } void fairshare(int base, int count) { int i; printf("Base %2d:", base); for (i = 0; i < count; i++) { int t = turn(base, i); printf(" %2d", t); } printf("\n"); } void turnCount(int base, int count) { int *cnt = calloc(base, sizeof(int)); int i, minTurn, maxTurn, portion; if (NULL == cnt) { printf("Failed to allocate space to determine the spread of turns.\n"); return; } for (i = 0; i < count; i++) { int t = turn(base, i); cnt[t]++; } minTurn = INT_MAX; maxTurn = INT_MIN; portion = 0; for (i = 0; i < base; i++) { if (cnt[i] > 0) { portion++; } if (cnt[i] < minTurn) { minTurn = cnt[i]; } if (cnt[i] > maxTurn) { maxTurn = cnt[i]; } } printf(" With %d people: ", base); if (0 == minTurn) { printf("Only %d have a turn\n", portion); } else if (minTurn == maxTurn) { printf("%d\n", minTurn); } else { printf("%d or %d\n", minTurn, maxTurn); } free(cnt); } int main() { fairshare(2, 25); fairshare(3, 25); fairshare(5, 25); fairshare(11, 25); printf("How many times does each get a turn in 50000 iterations?\n"); turnCount(191, 50000); turnCount(1377, 50000); turnCount(49999, 50000); turnCount(50000, 50000); turnCount(50001, 50000); return 0; }
Farey sequence
C
The Farey sequence ''' ''F''n''' of order '''n''' is the sequence of completely reduced fractions between '''0''' and '''1''' which, when in lowest terms, have denominators less than or equal to '''n''', arranged in order of increasing size. The ''Farey sequence'' is sometimes incorrectly called a ''Farey series''. Each Farey sequence: :::* starts with the value '''0''' (zero), denoted by the fraction \frac{0}{1} :::* ends with the value '''1''' (unity), denoted by the fraction \frac{1}{1}. The Farey sequences of orders '''1''' to '''5''' are: :::: {\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1} : :::: {\bf\it{F}}_2 = \frac{0}{1}, \frac{1}{2}, \frac{1}{1} : :::: {\bf\it{F}}_3 = \frac{0}{1}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{1}{1} : :::: {\bf\it{F}}_4 = \frac{0}{1}, \frac{1}{4}, \frac{1}{3}, \frac{1}{2}, \frac{2}{3}, \frac{3}{4}, \frac{1}{1} : :::: {\bf\it{F}}_5 = \frac{0}{1}, \frac{1}{5}, \frac{1}{4}, \frac{1}{3}, \frac{2}{5}, \frac{1}{2}, \frac{3}{5}, \frac{2}{3}, \frac{3}{4}, \frac{4}{5}, \frac{1}{1} ;Task * Compute and show the Farey sequence for orders '''1''' through '''11''' (inclusive). * Compute and display the ''number'' of fractions in the Farey sequence for order '''100''' through '''1,000''' (inclusive) by hundreds. * Show the fractions as '''n/d''' (using the solidus [or slash] to separate the numerator from the denominator). The length (the number of fractions) of a Farey sequence asymptotically approaches: ::::::::::: 3 x n2 / \pi2 ;See also: * OEIS sequence A006842 numerators of Farey series of order 1, 2, *** * OEIS sequence A006843 denominators of Farey series of order 1, 2, *** * OEIS sequence A005728 number of fractions in Farey series of order n * MathWorld entry Farey sequence * Wikipedia entry Farey sequence
#include <stdio.h> #include <stdlib.h> #include <string.h> void farey(int n) { typedef struct { int d, n; } frac; frac f1 = {0, 1}, f2 = {1, n}, t; int k; printf("%d/%d %d/%d", 0, 1, 1, n); while (f2.n > 1) { k = (n + f1.n) / f2.n; t = f1, f1 = f2, f2 = (frac) { f2.d * k - t.d, f2.n * k - t.n }; printf(" %d/%d", f2.d, f2.n); } putchar('\n'); } typedef unsigned long long ull; ull *cache; size_t ccap; ull farey_len(int n) { if (n >= ccap) { size_t old = ccap; if (!ccap) ccap = 16; while (ccap <= n) ccap *= 2; cache = realloc(cache, sizeof(ull) * ccap); memset(cache + old, 0, sizeof(ull) * (ccap - old)); } else if (cache[n]) return cache[n]; ull len = (ull)n*(n + 3) / 2; int p, q = 0; for (p = 2; p <= n; p = q) { q = n/(n/p) + 1; len -= farey_len(n/p) * (q - p); } cache[n] = len; return len; } int main(void) { int n; for (n = 1; n <= 11; n++) { printf("%d: ", n); farey(n); } for (n = 100; n <= 1000; n += 100) printf("%d: %llu items\n", n, farey_len(n)); n = 10000000; printf("\n%d: %llu items\n", n, farey_len(n)); return 0; }
Fast Fourier transform
C
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
#include <stdio.h> #include <math.h> #include <complex.h> double PI; typedef double complex cplx; void _fft(cplx buf[], cplx out[], int n, int step) { if (step < n) { _fft(out, buf, n, step * 2); _fft(out + step, buf + step, n, step * 2); for (int i = 0; i < n; i += 2 * step) { cplx t = cexp(-I * PI * i / n) * out[i + step]; buf[i / 2] = out[i] + t; buf[(i + n)/2] = out[i] - t; } } } void fft(cplx buf[], int n) { cplx out[n]; for (int i = 0; i < n; i++) out[i] = buf[i]; _fft(buf, out, n, 1); } void show(const char * s, cplx buf[]) { printf("%s", s); for (int i = 0; i < 8; i++) if (!cimag(buf[i])) printf("%g ", creal(buf[i])); else printf("(%g, %g) ", creal(buf[i]), cimag(buf[i])); } int main() { PI = atan2(1, 1) * 4; cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0}; show("Data: ", buf); fft(buf, 8); show("\nFFT : ", buf); return 0; }
Fibonacci n-step number sequences
C
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
/* The function anynacci determines the n-arity of the sequence from the number of seed elements. 0 ended arrays are used since C does not have a way of determining the length of dynamic and function-passed integer arrays.*/ #include<stdlib.h> #include<stdio.h> int * anynacci (int *seedArray, int howMany) { int *result = malloc (howMany * sizeof (int)); int i, j, initialCardinality; for (i = 0; seedArray[i] != 0; i++); initialCardinality = i; for (i = 0; i < initialCardinality; i++) result[i] = seedArray[i]; for (i = initialCardinality; i < howMany; i++) { result[i] = 0; for (j = i - initialCardinality; j < i; j++) result[i] += result[j]; } return result; } int main () { int fibo[] = { 1, 1, 0 }, tribo[] = { 1, 1, 2, 0 }, tetra[] = { 1, 1, 2, 4, 0 }, luca[] = { 2, 1, 0 }; int *fibonacci = anynacci (fibo, 10), *tribonacci = anynacci (tribo, 10), *tetranacci = anynacci (tetra, 10), *lucas = anynacci(luca, 10); int i; printf ("\nFibonacci\tTribonacci\tTetranacci\tLucas\n"); for (i = 0; i < 10; i++) printf ("\n%d\t\t%d\t\t%d\t\t%d", fibonacci[i], tribonacci[i], tetranacci[i], lucas[i]); return 0; }
Fibonacci word
C
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> void print_headings() { printf("%2s", "N"); printf(" %10s", "Length"); printf(" %-20s", "Entropy"); printf(" %-40s", "Word"); printf("\n"); } double calculate_entropy(int ones, int zeros) { double result = 0; int total = ones + zeros; result -= (double) ones / total * log2((double) ones / total); result -= (double) zeros / total * log2((double) zeros / total); if (result != result) { // NAN result = 0; } return result; } void print_entropy(char *word) { int ones = 0; int zeros = 0; int i; for (i = 0; word[i]; i++) { char c = word[i]; switch (c) { case '0': zeros++; break; case '1': ones++; break; } } double entropy = calculate_entropy(ones, zeros); printf(" %-20.18f", entropy); } void print_word(int n, char *word) { printf("%2d", n); printf(" %10ld", strlen(word)); print_entropy(word); if (n < 10) { printf(" %-40s", word); } else { printf(" %-40s", "..."); } printf("\n"); } int main(int argc, char *argv[]) { print_headings(); char *last_word = malloc(2); strcpy(last_word, "1"); char *current_word = malloc(2); strcpy(current_word, "0"); print_word(1, last_word); int i; for (i = 2; i <= 37; i++) { print_word(i, current_word); char *next_word = malloc(strlen(current_word) + strlen(last_word) + 1); strcpy(next_word, current_word); strcat(next_word, last_word); free(last_word); last_word = current_word; current_word = next_word; } free(last_word); free(current_word); return 0; }
File extension is in extensions list
C
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''. It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the [[Extract file extension]] task. ;Related tasks: * [[Extract file extension]] * [[String matching]]
/* * File extension is in extensions list (dots allowed). * * This problem is trivial because the so-called extension is simply the end * part of the name. */ #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <locale.h> #include <string.h> #ifdef _Bool #include <stdbool.h> #else #define bool int #define true 1 #define false 0 #endif /* * The implemented algorithm is not the most efficient one: for N extensions * of length M it has the cost O(N * M). */ int checkFileExtension(char* fileName, char* fileExtensions) { char* fileExtension = fileExtensions; if ( *fileName ) { while ( *fileExtension ) { int fileNameLength = strlen(fileName); int extensionLength = strlen(fileExtension); if ( fileNameLength >= extensionLength ) { char* a = fileName + fileNameLength - extensionLength; char* b = fileExtension; while ( *a && toupper(*a++) == toupper(*b++) ) ; if ( !*a ) return true; } fileExtension += extensionLength + 1; } } return false; } void printExtensions(char* extensions) { while( *extensions ) { printf("%s\n", extensions); extensions += strlen(extensions) + 1; } } bool test(char* fileName, char* extension, bool expectedResult) { bool result = checkFileExtension(fileName,extension); bool returnValue = result == expectedResult; printf("%20s result: %-5s expected: %-5s test %s\n", fileName, result ? "true" : "false", expectedResult ? "true" : "false", returnValue ? "passed" : "failed" ); return returnValue; } int main(void) { static char extensions[] = ".zip\0.rar\0.7z\0.gz\0.archive\0.A##\0.tar.bz2\0"; setlocale(LC_ALL,""); printExtensions(extensions); printf("\n"); if ( test("MyData.a##", extensions,true ) && test("MyData.tar.Gz", extensions,true ) && test("MyData.gzip", extensions,false) && test("MyData.7z.backup", extensions,false) && test("MyData...", extensions,false) && test("MyData", extensions,false) && test("MyData_v1.0.tar.bz2",extensions,true ) && test("MyData_v1.0.bz2", extensions,false) && test("filename", extensions,false) ) printf("\n%s\n", "All tests passed."); else printf("\n%s\n", "Last test failed."); printf("\n%s\n", "press enter"); getchar(); return 0; }
File size distribution
C
Beginning from the current directory, or optionally from a directory specified as a command-line argument, determine how many files there are of various sizes in a directory hierarchy. My suggestion is to sort by logarithmn of file size, since a few bytes here or there, or even a factor of two or three, may not be that significant. Don't forget that empty files may exist, to serve as a marker. Is your file system predominantly devoted to a large number of smaller files, or a smaller number of huge files?
#include<windows.h> #include<string.h> #include<stdio.h> #define MAXORDER 25 int main(int argC, char* argV[]) { char str[MAXORDER],commandString[1000],*startPath; long int* fileSizeLog = (long int*)calloc(sizeof(long int),MAXORDER),max; int i,j,len; double scale; FILE* fp; if(argC==1) printf("Usage : %s <followed by directory to start search from(. for current dir), followed by \n optional parameters (T or G) to show text or graph output>",argV[0]); else{ if(strchr(argV[1],' ')!=NULL){ len = strlen(argV[1]); startPath = (char*)malloc((len+2)*sizeof(char)); startPath[0] = '\"'; startPath[len+1]='\"'; strncpy(startPath+1,argV[1],len); startPath[len+2] = argV[1][len]; sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",startPath); } else if(strlen(argV[1])==1 && argV[1][0]=='.') strcpy(commandString,"forfiles /s /c \"cmd /c echo @fsize\" 2>&1"); else sprintf(commandString,"forfiles /p %s /s /c \"cmd /c echo @fsize\" 2>&1",argV[1]); fp = popen(commandString,"r"); while(fgets(str,100,fp)!=NULL){ if(str[0]=='0') fileSizeLog[0]++; else fileSizeLog[strlen(str)]++; } if(argC==2 || (argC==3 && (argV[2][0]=='t'||argV[2][0]=='T'))){ for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes : %Ld",i,fileSizeLog[i]); } } else if(argC==3 && (argV[2][0]=='g'||argV[2][0]=='G')){ CONSOLE_SCREEN_BUFFER_INFO csbi; int val = GetConsoleScreenBufferInfo(GetStdHandle( STD_OUTPUT_HANDLE ),&csbi); if(val) { max = fileSizeLog[0]; for(i=1;i<MAXORDER;i++) (fileSizeLog[i]>max)?max=fileSizeLog[i]:max; (max < csbi.dwSize.X)?(scale=1):(scale=(1.0*(csbi.dwSize.X-50))/max); for(i=0;i<MAXORDER;i++){ printf("\nSize Order < 10^%2d bytes |",i); for(j=0;j<(int)(scale*fileSizeLog[i]);j++) printf("%c",219); printf("%Ld",fileSizeLog[i]); } } } return 0; } }
Find limit of recursion
C
{{selection|Short Circuit|Console Program Basics}} ;Task: Find the limit of recursion.
#include <stdio.h> char * base; void get_diff() { char x; if (base - &x < 200) printf("%p %d\n", &x, base - &x); } void recur() { get_diff(); recur(); } int main() { char v = 32; printf("pos of v: %p\n", base = &v); recur(); return 0; }
Find palindromic numbers in both binary and ternary bases
C
* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'': :::* base 2 :::* base 3 * Display '''0''' (zero) as the first number found, even though some other definitions ignore it. * Optionally, show the decimal number found in its binary and ternary form. * Show all output here. It's permissible to assume the first two numbers and simply list them. ;See also * Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
#include <stdio.h> typedef unsigned long long xint; int is_palin2(xint n) { xint x = 0; if (!(n&1)) return !n; while (x < n) x = x<<1 | (n&1), n >>= 1; return n == x || n == x>>1; } xint reverse3(xint n) { xint x = 0; while (n) x = x*3 + (n%3), n /= 3; return x; } void print(xint n, xint base) { putchar(' '); // printing digits backwards, but hey, it's a palindrome do { putchar('0' + (n%base)), n /= base; } while(n); printf("(%lld)", base); } void show(xint n) { printf("%llu", n); print(n, 2); print(n, 3); putchar('\n'); } xint min(xint a, xint b) { return a < b ? a : b; } xint max(xint a, xint b) { return a > b ? a : b; } int main(void) { xint lo, hi, lo2, hi2, lo3, hi3, pow2, pow3, i, n; int cnt; show(0); cnt = 1; lo = 0; hi = pow2 = pow3 = 1; while (1) { for (i = lo; i < hi; i++) { n = (i * 3 + 1) * pow3 + reverse3(i); if (!is_palin2(n)) continue; show(n); if (++cnt >= 7) return 0; } if (i == pow3) pow3 *= 3; else pow2 *= 4; while (1) { while (pow2 <= pow3) pow2 *= 4; lo2 = (pow2 / pow3 - 1) / 3; hi2 = (pow2 * 2 / pow3 - 1) / 3 + 1; lo3 = pow3 / 3; hi3 = pow3; if (lo2 >= hi3) pow3 *= 3; else if (lo3 >= hi2) pow2 *= 4; else { lo = max(lo2, lo3); hi = min(hi2, hi3); break; } } } return 0; }
Find the intersection of a line with a plane
C
Finding the intersection of an infinite ray with a plane in 3D is an important topic in collision detection. ;Task: Find the point of intersection for the infinite ray with direction (0, -1, -1) passing through position (0, 0, 10) with the infinite plane with a normal vector of (0, 0, 1) and which passes through [0, 0, 5].
#include<stdio.h> typedef struct{ double x,y,z; }vector; vector addVectors(vector a,vector b){ return (vector){a.x+b.x,a.y+b.y,a.z+b.z}; } vector subVectors(vector a,vector b){ return (vector){a.x-b.x,a.y-b.y,a.z-b.z}; } double dotProduct(vector a,vector b){ return a.x*b.x + a.y*b.y + a.z*b.z; } vector scaleVector(double l,vector a){ return (vector){l*a.x,l*a.y,l*a.z}; } vector intersectionPoint(vector lineVector, vector linePoint, vector planeNormal, vector planePoint){ vector diff = subVectors(linePoint,planePoint); return addVectors(addVectors(diff,planePoint),scaleVector(-dotProduct(diff,planeNormal)/dotProduct(lineVector,planeNormal),lineVector)); } int main(int argC,char* argV[]) { vector lV,lP,pN,pP,iP; if(argC!=5) printf("Usage : %s <line direction, point on line, normal to plane and point on plane given as (x,y,z) tuples separated by space>"); else{ sscanf(argV[1],"(%lf,%lf,%lf)",&lV.x,&lV.y,&lV.z); sscanf(argV[3],"(%lf,%lf,%lf)",&pN.x,&pN.y,&pN.z); if(dotProduct(lV,pN)==0) printf("Line and Plane do not intersect, either parallel or line is on the plane"); else{ sscanf(argV[2],"(%lf,%lf,%lf)",&lP.x,&lP.y,&lP.z); sscanf(argV[4],"(%lf,%lf,%lf)",&pP.x,&pP.y,&pP.z); iP = intersectionPoint(lV,lP,pN,pP); printf("Intersection point is (%lf,%lf,%lf)",iP.x,iP.y,iP.z); } } return 0; }
Find the intersection of two lines
C
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ double x,y; }point; double lineSlope(point a,point b){ if(a.x-b.x == 0.0) return NAN; else return (a.y-b.y)/(a.x-b.x); } point extractPoint(char* str){ int i,j,start,end,length; char* holder; point c; for(i=0;str[i]!=00;i++){ if(str[i]=='(') start = i; if(str[i]==','||str[i]==')') { end = i; length = end - start; holder = (char*)malloc(length*sizeof(char)); for(j=0;j<length-1;j++) holder[j] = str[start + j + 1]; holder[j] = 00; if(str[i]==','){ start = i; c.x = atof(holder); } else c.y = atof(holder); } } return c; } point intersectionPoint(point a1,point a2,point b1,point b2){ point c; double slopeA = lineSlope(a1,a2), slopeB = lineSlope(b1,b2); if(slopeA==slopeB){ c.x = NAN; c.y = NAN; } else if(isnan(slopeA) && !isnan(slopeB)){ c.x = a1.x; c.y = (a1.x-b1.x)*slopeB + b1.y; } else if(isnan(slopeB) && !isnan(slopeA)){ c.x = b1.x; c.y = (b1.x-a1.x)*slopeA + a1.y; } else{ c.x = (slopeA*a1.x - slopeB*b1.x + b1.y - a1.y)/(slopeA - slopeB); c.y = slopeB*(c.x - b1.x) + b1.y; } return c; } int main(int argC,char* argV[]) { point c; if(argC < 5) printf("Usage : %s <four points specified as (x,y) separated by a space>",argV[0]); else{ c = intersectionPoint(extractPoint(argV[1]),extractPoint(argV[2]),extractPoint(argV[3]),extractPoint(argV[4])); if(isnan(c.x)) printf("The lines do not intersect, they are either parallel or co-incident."); else printf("Point of intersection : (%lf,%lf)",c.x,c.y); } return 0; }
Find the last Sunday of each month
C
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ;Related tasks * [[Day of the week]] * [[Five weekends]] * [[Last Friday of each month]]
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (argc < 2 || (y = atoi(argv[1])) <= 1752) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + 97 * (y - 1) / 400 + 4; for(m = 0; m < 12; m++) { w = (w + days[m]) % 7; printf("%d-%02d-%d\n", y, m + 1,days[m] - w); } return 0; }
Find the missing permutation
C
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
#include <stdio.h> #define N 4 const char *perms[] = { "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB", }; int main() { int i, j, n, cnt[N]; char miss[N]; for (n = i = 1; i < N; i++) n *= i; /* n = (N-1)!, # of occurrence */ for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cnt[j] = 0; /* count how many times each letter occur at position i */ for (j = 0; j < sizeof(perms)/sizeof(const char*); j++) cnt[perms[j][i] - 'A']++; /* letter not occurring (N-1)! times is the missing one */ for (j = 0; j < N && cnt[j] == n; j++); miss[i] = j + 'A'; } printf("Missing: %.*s\n", N, miss); return 0; }
First perfect square in base n with n unique digits
C
Find the first perfect square in a given base '''N''' that has at least '''N''' digits and exactly '''N''' ''significant unique'' digits when expressed in base '''N'''. E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432'''). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. ;Task * Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated. * (optional) Do the same for bases '''13''' through '''16'''. * (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math) ;See also: ;* OEIS A260182: smallest square that is pandigital in base n. ;Related task ;* [[Casting out nines]]
#include <stdio.h> #include <string.h> #define BUFF_SIZE 32 void toBaseN(char buffer[], long long num, int base) { char *ptr = buffer; char *tmp; // write it backwards while (num >= 1) { int rem = num % base; num /= base; *ptr++ = "0123456789ABCDEF"[rem]; } *ptr-- = 0; // now reverse it to be written forwards for (tmp = buffer; tmp < ptr; tmp++, ptr--) { char c = *tmp; *tmp = *ptr; *ptr = c; } } int countUnique(char inBuf[]) { char buffer[BUFF_SIZE]; int count = 0; int pos, nxt; strcpy_s(buffer, BUFF_SIZE, inBuf); for (pos = 0; buffer[pos] != 0; pos++) { if (buffer[pos] != 1) { count++; for (nxt = pos + 1; buffer[nxt] != 0; nxt++) { if (buffer[nxt] == buffer[pos]) { buffer[nxt] = 1; } } } } return count; } void find(int base) { char nBuf[BUFF_SIZE]; char sqBuf[BUFF_SIZE]; long long n, s; for (n = 2; /*blank*/; n++) { s = n * n; toBaseN(sqBuf, s, base); if (strlen(sqBuf) >= base && countUnique(sqBuf) == base) { toBaseN(nBuf, n, base); toBaseN(sqBuf, s, base); //printf("Base %d : Num %lld Square %lld\n", base, n, s); printf("Base %d : Num %8s Square %16s\n", base, nBuf, sqBuf); break; } } } int main() { int i; for (i = 2; i <= 15; i++) { find(i); } return 0; }
Flatten a list
C
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] ;Related task: * [[Tree traversal]]
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct list_t list_t, *list; struct list_t{ int is_list, ival; /* ival is either the integer value or list length */ list *lst; }; list new_list() { list x = malloc(sizeof(list_t)); x->ival = 0; x->is_list = 1; x->lst = 0; return x; } void append(list parent, list child) { parent->lst = realloc(parent->lst, sizeof(list) * (parent->ival + 1)); parent->lst[parent->ival++] = child; } list from_string(char *s, char **e, list parent) { list ret = 0; if (!parent) parent = new_list(); while (*s != '\0') { if (*s == ']') { if (e) *e = s + 1; return parent; } if (*s == '[') { ret = new_list(); ret->is_list = 1; ret->ival = 0; append(parent, ret); from_string(s + 1, &s, ret); continue; } if (*s >= '0' && *s <= '9') { ret = new_list(); ret->is_list = 0; ret->ival = strtol(s, &s, 10); append(parent, ret); continue; } s++; } if (e) *e = s; return parent; } void show_list(list l) { int i; if (!l) return; if (!l->is_list) { printf("%d", l->ival); return; } printf("["); for (i = 0; i < l->ival; i++) { show_list(l->lst[i]); if (i < l->ival - 1) printf(", "); } printf("]"); } list flatten(list from, list to) { int i; list t; if (!to) to = new_list(); if (!from->is_list) { t = new_list(); *t = *from; append(to, t); } else for (i = 0; i < from->ival; i++) flatten(from->lst[i], to); return to; } void delete_list(list l) { int i; if (!l) return; if (l->is_list && l->ival) { for (i = 0; i < l->ival; i++) delete_list(l->lst[i]); free(l->lst); } free(l); } int main() { list l = from_string("[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []", 0, 0); printf("Nested: "); show_list(l); printf("\n"); list flat = flatten(l, 0); printf("Flattened: "); show_list(flat); /* delete_list(l); delete_list(flat); */ return 0; }
Flipping bits game
C
The game: Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once (as one move). In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column. ;Task: Create a program to score for the Flipping bits game. # The game should create an original random target configuration and a starting configuration. # Ensure that the starting position is ''never'' the target position. # The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position). # The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a '''3x3''' array of bits.
#include <stdio.h> #include <stdlib.h> int i, j; void fliprow(int **b, int sz, int n) { for(i = 0; i < sz; i++) b[n+1][i] = !b[n+1][i]; } void flipcol(int **b, int sz, int n) { for(i = 1; i <= sz; i++) b[i][n] = !b[i][n]; } void initt(int **t, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) t[i][j] = rand()%2; } void initb(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) b[i][j] = t[i][j]; for(i = 1; i <= sz; i++) fliprow(b, sz, rand()%sz+1); for(i = 0; i < sz; i++) flipcol(b, sz, rand()%sz); } void printb(int **b, int sz) { printf(" "); for(i = 0; i < sz; i++) printf(" %d", i); printf("\n"); for(i = 1; i <= sz; i++) { printf("%d", i-1); for(j = 0; j < sz; j++) printf(" %d", b[i][j]); printf("\n"); } printf("\n"); } int eq(int **t, int **b, int sz) { for(i = 1; i <= sz; i++) for(j = 0; j < sz; j++) if(b[i][j] != t[i][j]) return 0; return 1; } void main() { int sz = 3; int eql = 0; int mov = 0; int **t = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) t[i] = malloc(sz*sizeof(int)); int **b = malloc(sz*(sizeof(int)+1)); for(i = 1; i <= sz; i++) b[i] = malloc(sz*sizeof(int)); char roc; int n; initt(t, sz); initb(t, b, sz); while(eq(t, b, sz)) initb(t, b, sz); while(!eql) { printf("Target: \n"); printb(t, sz); printf("Board: \n"); printb(b, sz); printf("What to flip: "); scanf(" %c", &roc); scanf(" %d", &n); switch(roc) { case 'r': fliprow(b, sz, n); break; case 'c': flipcol(b, sz, n); break; default: perror("Please specify r or c and an number"); break; } printf("Moves Taken: %d\n", ++mov); if(eq(t, b, sz)) { printf("You win!\n"); eql = 1; } } }
Floyd's triangle
C
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
#include <stdio.h> void t(int n) { int i, j, c, len; i = n * (n - 1) / 2; for (len = c = 1; c < i; c *= 10, len++); c -= i; // c is the col where width changes #define SPEED_MATTERS 0 #if SPEED_MATTERS // in case we really, really wanted to print huge triangles often char tmp[32], s[4096], *p; sprintf(tmp, "%*d", len, 0); inline void inc_numstr(void) { int k = len; redo: if (!k--) return; if (tmp[k] == '9') { tmp[k] = '0'; goto redo; } if (++tmp[k] == '!') tmp[k] = '1'; } for (p = s, i = 1; i <= n; i++) { for (j = 1; j <= i; j++) { inc_numstr(); __builtin_memcpy(p, tmp + 1 - (j >= c), len - (j < c)); p += len - (j < c); *(p++) = (i - j)? ' ' : '\n'; if (p - s + len >= 4096) { fwrite(s, 1, p - s, stdout); p = s; } } } fwrite(s, 1, p - s, stdout); #else // NO_IT_DOESN'T int num; for (num = i = 1; i <= n; i++) for (j = 1; j <= i; j++) printf("%*d%c", len - (j < c), num++, i - j ? ' ':'\n'); #endif } int main(void) { t(5), t(14); // maybe not // t(10000); return 0; }
Four bit adder
C
"''Simulate''" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two gate. ; Finally a half adder can be made using an ''xor'' gate and an ''and'' gate. The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. '''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones. {| |+Schematics of the "constructive blocks" !(Xor gate with ANDs, ORs and NOTs) ! (A half adder) ! (A full adder) ! (A 4-bit adder) |- |Xor gate done with ands, ors and nots |A half adder |A full adder |A 4-bit adder |} Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
#include <stdio.h> typedef char pin_t; #define IN const pin_t * #define OUT pin_t * #define PIN(X) pin_t _##X; pin_t *X = & _##X; #define V(X) (*(X)) /* a NOT that does not soil the rest of the host of the single bit */ #define NOT(X) (~(X)&1) /* a shortcut to "implement" a XOR using only NOT, AND and OR gates, as task requirements constrain */ #define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y))) void halfadder(IN a, IN b, OUT s, OUT c) { V(s) = XOR(V(a), V(b)); V(c) = V(a) & V(b); } void fulladder(IN a, IN b, IN ic, OUT s, OUT oc) { PIN(ps); PIN(pc); PIN(tc); halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc); halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc); V(oc) = V(tc) | V(pc); } void fourbitsadder(IN a0, IN a1, IN a2, IN a3, IN b0, IN b1, IN b2, IN b3, OUT o0, OUT o1, OUT o2, OUT o3, OUT overflow) { PIN(zero); V(zero) = 0; PIN(tc0); PIN(tc1); PIN(tc2); fulladder(/*INPUT*/a0, b0, zero, /*OUTPUT*/o0, tc0); fulladder(/*INPUT*/a1, b1, tc0, /*OUTPUT*/o1, tc1); fulladder(/*INPUT*/a2, b2, tc1, /*OUTPUT*/o2, tc2); fulladder(/*INPUT*/a3, b3, tc2, /*OUTPUT*/o3, overflow); } int main() { PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(overflow); V(a3) = 0; V(b3) = 1; V(a2) = 0; V(b2) = 1; V(a1) = 1; V(b1) = 1; V(a0) = 0; V(b0) = 0; fourbitsadder(a0, a1, a2, a3, /* INPUT */ b0, b1, b2, b3, s0, s1, s2, s3, /* OUTPUT */ overflow); printf("%d%d%d%d + %d%d%d%d = %d%d%d%d, overflow = %d\n", V(a3), V(a2), V(a1), V(a0), V(b3), V(b2), V(b1), V(b0), V(s3), V(s2), V(s1), V(s0), V(overflow)); return 0; }
Function prototype
C
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. ;Task: Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: * An explanation of any placement restrictions for prototype declarations * A prototype declaration for a function that does not require arguments * A prototype declaration for a function that requires two arguments * A prototype declaration for a function that utilizes varargs * A prototype declaration for a function that utilizes optional arguments * A prototype declaration for a function that utilizes named parameters * Example of prototype declarations for subroutines or procedures (if these differ from functions) * An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
int noargs(void); /* Declare a function with no argument that returns an integer */ int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */ int twoargs(int ,int); /* Parameter names are optional in a prototype definition */ int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */ int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */
Fusc sequence
C
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
#include<limits.h> #include<stdio.h> int fusc(int n){ if(n==0||n==1) return n; else if(n%2==0) return fusc(n/2); else return fusc((n-1)/2) + fusc((n+1)/2); } int numLen(int n){ int sum = 1; while(n>9){ n = n/10; sum++; } return sum; } void printLargeFuscs(int limit){ int i,f,len,maxLen = 1; printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit); for(i=0;i<=limit;i++){ f = fusc(i); len = numLen(f); if(len>maxLen){ maxLen = len; printf("\n%5d%12d",i,f); } } } int main() { int i; printf("Index-------Value"); for(i=0;i<61;i++) printf("\n%5d%12d",i,fusc(i)); printLargeFuscs(INT_MAX); return 0; }
Gapful numbers
C
Numbers (positive integers expressed in base ten) that are (evenly) divisible by the number formed by the first and last digit are known as '''gapful numbers'''. ''Evenly divisible'' means divisible with no remainder. All one- and two-digit numbers have this property and are trivially excluded. Only numbers >= '''100''' will be considered for this Rosetta Code task. ;Example: '''187''' is a '''gapful''' number because it is evenly divisible by the number '''17''' which is formed by the first and last decimal digits of '''187'''. About 7.46% of positive integers are ''gapful''. ;Task: :* Generate and show all sets of numbers (below) on one line (horizontally) with a title, here on this page :* Show the first '''30''' gapful numbers :* Show the first '''15''' gapful numbers >= '''1,000,000''' :* Show the first '''10''' gapful numbers >= '''1,000,000,000''' ;Related tasks: :* Harshad or Niven series. :* palindromic gapful numbers. :* largest number divisible by its digits. ;Also see: :* The OEIS entry: A108343 gapful numbers. :* numbersaplenty gapful numbers
#include<stdio.h> void generateGaps(unsigned long long int start,int count){ int counter = 0; unsigned long long int i = start; char str[100]; printf("\nFirst %d Gapful numbers >= %llu :\n",count,start); while(counter<count){ sprintf(str,"%llu",i); if((i%(10*(str[0]-'0') + i%10))==0L){ printf("\n%3d : %llu",counter+1,i); counter++; } i++; } } int main() { unsigned long long int i = 100; int count = 0; char str[21]; generateGaps(100,30); printf("\n"); generateGaps(1000000,15); printf("\n"); generateGaps(1000000000,15); printf("\n"); return 0; }
Gaussian elimination
C
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
#include <stdio.h> #include <stdlib.h> #include <math.h> #define mat_elem(a, y, x, n) (a + ((y) * (n) + (x))) void swap_row(double *a, double *b, int r1, int r2, int n) { double tmp, *p1, *p2; int i; if (r1 == r2) return; for (i = 0; i < n; i++) { p1 = mat_elem(a, r1, i, n); p2 = mat_elem(a, r2, i, n); tmp = *p1, *p1 = *p2, *p2 = tmp; } tmp = b[r1], b[r1] = b[r2], b[r2] = tmp; } void gauss_eliminate(double *a, double *b, double *x, int n) { #define A(y, x) (*mat_elem(a, y, x, n)) int i, j, col, row, max_row,dia; double max, tmp; for (dia = 0; dia < n; dia++) { max_row = dia, max = A(dia, dia); for (row = dia + 1; row < n; row++) if ((tmp = fabs(A(row, dia))) > max) max_row = row, max = tmp; swap_row(a, b, dia, max_row, n); for (row = dia + 1; row < n; row++) { tmp = A(row, dia) / A(dia, dia); for (col = dia+1; col < n; col++) A(row, col) -= tmp * A(dia, col); A(row, dia) = 0; b[row] -= tmp * b[dia]; } } for (row = n - 1; row >= 0; row--) { tmp = b[row]; for (j = n - 1; j > row; j--) tmp -= x[j] * A(row, j); x[row] = tmp / A(row, row); } #undef A } int main(void) { double a[] = { 1.00, 0.00, 0.00, 0.00, 0.00, 0.00, 1.00, 0.63, 0.39, 0.25, 0.16, 0.10, 1.00, 1.26, 1.58, 1.98, 2.49, 3.13, 1.00, 1.88, 3.55, 6.70, 12.62, 23.80, 1.00, 2.51, 6.32, 15.88, 39.90, 100.28, 1.00, 3.14, 9.87, 31.01, 97.41, 306.02 }; double b[] = { -0.01, 0.61, 0.91, 0.99, 0.60, 0.02 }; double x[6]; int i; gauss_eliminate(a, b, x, 6); for (i = 0; i < 6; i++) printf("%g\n", x[i]); return 0; }
Generate Chess960 starting position
C
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
#include<stdlib.h> #include<locale.h> #include<wchar.h> #include<stdio.h> #include<time.h> char rank[9]; int pos[8]; void swap(int i,int j){ int temp = pos[i]; pos[i] = pos[j]; pos[j] = temp; } void generateFirstRank(){ int kPos,qPos,bPos1,bPos2,rPos1,rPos2,nPos1,nPos2,i; for(i=0;i<8;i++){ rank[i] = 'e'; pos[i] = i; } do{ kPos = rand()%8; rPos1 = rand()%8; rPos2 = rand()%8; }while((rPos1-kPos<=0 && rPos2-kPos<=0)||(rPos1-kPos>=0 && rPos2-kPos>=0)||(rPos1==rPos2 || kPos==rPos1 || kPos==rPos2)); rank[pos[rPos1]] = 'R'; rank[pos[kPos]] = 'K'; rank[pos[rPos2]] = 'R'; swap(rPos1,7); swap(rPos2,6); swap(kPos,5); do{ bPos1 = rand()%5; bPos2 = rand()%5; }while(((pos[bPos1]-pos[bPos2])%2==0)||(bPos1==bPos2)); rank[pos[bPos1]] = 'B'; rank[pos[bPos2]] = 'B'; swap(bPos1,4); swap(bPos2,3); do{ qPos = rand()%3; nPos1 = rand()%3; }while(qPos==nPos1); rank[pos[qPos]] = 'Q'; rank[pos[nPos1]] = 'N'; for(i=0;i<8;i++) if(rank[i]=='e'){ rank[i] = 'N'; break; } } void printRank(){ int i; #ifdef _WIN32 printf("%s\n",rank); #else { setlocale(LC_ALL,""); printf("\n"); for(i=0;i<8;i++){ if(rank[i]=='K') printf("%lc",(wint_t)9812); else if(rank[i]=='Q') printf("%lc",(wint_t)9813); else if(rank[i]=='R') printf("%lc",(wint_t)9814); else if(rank[i]=='B') printf("%lc",(wint_t)9815); if(rank[i]=='N') printf("%lc",(wint_t)9816); } } #endif } int main() { int i; srand((unsigned)time(NULL)); for(i=0;i<9;i++){ generateFirstRank(); printRank(); } return 0; }
Generator/Exponential
C
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
#include <inttypes.h> /* int64_t, PRId64 */ #include <stdlib.h> /* exit() */ #include <stdio.h> /* printf() */ #include <libco.h> /* co_{active,create,delete,switch}() */ /* A generator that yields values of type int64_t. */ struct gen64 { cothread_t giver; /* this cothread calls yield64() */ cothread_t taker; /* this cothread calls next64() */ int64_t given; void (*free)(struct gen64 *); void *garbage; }; /* Yields a value. */ inline void yield64(struct gen64 *gen, int64_t value) { gen->given = value; co_switch(gen->taker); } /* Returns the next value that the generator yields. */ inline int64_t next64(struct gen64 *gen) { gen->taker = co_active(); co_switch(gen->giver); return gen->given; } static void gen64_free(struct gen64 *gen) { co_delete(gen->giver); } struct gen64 *entry64; /* * Creates a cothread for the generator. The first call to next64(gen) * will enter the cothread; the entry function must copy the pointer * from the global variable struct gen64 *entry64. * * Use gen->free(gen) to free the cothread. */ inline void gen64_init(struct gen64 *gen, void (*entry)(void)) { if ((gen->giver = co_create(4096, entry)) == NULL) { /* Perhaps malloc() failed */ fputs("co_create: Cannot create cothread\n", stderr); exit(1); } gen->free = gen64_free; entry64 = gen; } /* * Generates the powers 0**m, 1**m, 2**m, .... */ void powers(struct gen64 *gen, int64_t m) { int64_t base, exponent, n, result; for (n = 0;; n++) { /* * This computes result = base**exponent, where * exponent is a nonnegative integer. The result * is the product of repeated squares of base. */ base = n; exponent = m; for (result = 1; exponent != 0; exponent >>= 1) { if (exponent & 1) result *= base; base *= base; } yield64(gen, result); } /* NOTREACHED */ } /* stuff for squares_without_cubes() */ #define ENTRY(name, code) static void name(void) { code; } ENTRY(enter_squares, powers(entry64, 2)) ENTRY(enter_cubes, powers(entry64, 3)) struct swc { struct gen64 cubes; struct gen64 squares; void (*old_free)(struct gen64 *); }; static void swc_free(struct gen64 *gen) { struct swc *f = gen->garbage; f->cubes.free(&f->cubes); f->squares.free(&f->squares); f->old_free(gen); } /* * Generates the squares 0**2, 1**2, 2**2, ..., but removes the squares * that equal the cubes 0**3, 1**3, 2**3, .... */ void squares_without_cubes(struct gen64 *gen) { struct swc f; int64_t c, s; gen64_init(&f.cubes, enter_cubes); c = next64(&f.cubes); gen64_init(&f.squares, enter_squares); s = next64(&f.squares); /* Allow other cothread to free this generator. */ f.old_free = gen->free; gen->garbage = &f; gen->free = swc_free; for (;;) { while (c < s) c = next64(&f.cubes); if (c != s) yield64(gen, s); s = next64(&f.squares); } /* NOTREACHED */ } ENTRY(enter_squares_without_cubes, squares_without_cubes(entry64)) /* * Look at the sequence of numbers that are squares but not cubes. * Drop the first 20 numbers, then print the next 10 numbers. */ int main() { struct gen64 gen; int i; gen64_init(&gen, enter_squares_without_cubes); for (i = 0; i < 20; i++) next64(&gen); for (i = 0; i < 9; i++) printf("%" PRId64 ", ", next64(&gen)); printf("%" PRId64 "\n", next64(&gen)); gen.free(&gen); /* Free memory. */ return 0; }
Get system command output
C
Task Execute a system command and get its output into the program. The output may be stored in any kind of collection (array, list, etc.). ;Related task * Execute a system command
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { if (argc < 2) return 1; FILE *fd; fd = popen(argv[1], "r"); if (!fd) return 1; char buffer[256]; size_t chread; /* String to store entire command contents in */ size_t comalloc = 256; size_t comlen = 0; char *comout = malloc(comalloc); /* Use fread so binary data is dealt with correctly */ while ((chread = fread(buffer, 1, sizeof(buffer), fd)) != 0) { if (comlen + chread >= comalloc) { comalloc *= 2; comout = realloc(comout, comalloc); } memmove(comout + comlen, buffer, chread); comlen += chread; } /* We can now work with the output as we please. Just print * out to confirm output is as expected */ fwrite(comout, 1, comlen, stdout); free(comout); pclose(fd); return 0; }
Globally replace text in several files
C
Replace every occurring instance of a piece of text in a group of text files with another one. For this task we want to replace the text "'''Goodbye London!'''" with "'''Hello New York!'''" for a list of files.
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <err.h> #include <string.h> char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len) { ptrdiff_t i; char *start = buf; while (start + len < buf_end) { for (i = 0; i < len; i++) if (start[i] != pat[i]) break; if (i == len) return (char *)start; start++; } return 0; } int replace(const char *from, const char *to, const char *fname) { #define bail(msg) { warn(msg" '%s'", fname); goto done; } struct stat st; int ret = 0; char *buf = 0, *start, *end; size_t len = strlen(from), nlen = strlen(to); int fd = open(fname, O_RDWR); if (fd == -1) bail("Can't open"); if (fstat(fd, &st) == -1) bail("Can't stat"); if (!(buf = malloc(st.st_size))) bail("Can't alloc"); if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read"); start = buf; end = find_match(start, buf + st.st_size, from, len); if (!end) goto done; /* no match found, don't change file */ ftruncate(fd, 0); lseek(fd, 0, 0); do { write(fd, start, end - start); /* write content before match */ write(fd, to, nlen); /* write replacement of match */ start = end + len; /* skip to end of match */ /* find match again */ end = find_match(start, buf + st.st_size, from, len); } while (end); /* write leftover after last match */ if (start < buf + st.st_size) write(fd, start, buf + st.st_size - start); done: if (fd != -1) close(fd); if (buf) free(buf); return ret; } int main() { const char *from = "Goodbye, London!"; const char *to = "Hello, New York!"; const char * files[] = { "test1.txt", "test2.txt", "test3.txt" }; int i; for (i = 0; i < sizeof(files)/sizeof(char*); i++) replace(from, to, files[i]); return 0; }
Gotchas
C
Definition In programming, a '''gotcha''' is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome. ;Task Give an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools.
if(a=b){} //assigns to "a" the value of "b". Then, if "a" is nonzero, the code in the curly braces is run. if(a==b){} //runs the code in the curly braces if and only if the value of "a" equals the value of "b".
Greatest subsequential sum
C
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
#include "stdio.h" typedef struct Range { int start, end, sum; } Range; Range maxSubseq(const int sequence[], const int len) { int maxSum = 0, thisSum = 0, i = 0; int start = 0, end = -1, j; for (j = 0; j < len; j++) { thisSum += sequence[j]; if (thisSum < 0) { i = j + 1; thisSum = 0; } else if (thisSum > maxSum) { maxSum = thisSum; start = i; end = j; } } Range r; if (start <= end && start >= 0 && end >= 0) { r.start = start; r.end = end + 1; r.sum = maxSum; } else { r.start = 0; r.end = 0; r.sum = 0; } return r; } int main(int argc, char **argv) { int a[] = {-1 , -2 , 3 , 5 , 6 , -2 , -1 , 4 , -4 , 2 , -1}; int alength = sizeof(a)/sizeof(a[0]); Range r = maxSubseq(a, alength); printf("Max sum = %d\n", r.sum); int i; for (i = r.start; i < r.end; i++) printf("%d ", a[i]); printf("\n"); return 0; }
Greedy algorithm for Egyptian fractions
C
An Egyptian fraction is the sum of distinct unit fractions such as: :::: \tfrac{1}{2} + \tfrac{1}{3} + \tfrac{1}{16} \,(= \tfrac{43}{48}) Each fraction in the expression has a numerator equal to '''1''' (unity) and a denominator that is a positive integer, and all the denominators are distinct (i.e., no repetitions). Fibonacci's Greedy algorithm for Egyptian fractions expands the fraction \tfrac{x}{y} to be represented by repeatedly performing the replacement :::: \frac{x}{y} = \frac{1}{\lceil y/x\rceil} + \frac{(-y)\!\!\!\!\mod x}{y\lceil y/x\rceil} (simplifying the 2nd term in this replacement as necessary, and where \lceil x \rceil is the ''ceiling'' function). For this task, Proper and improper fractions must be able to be expressed. Proper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that a < b, and improper fractions are of the form \tfrac{a}{b} where a and b are positive integers, such that ''a'' >= ''b''. (See the REXX programming example to view one method of expressing the whole number part of an improper fraction.) For improper fractions, the integer part of any improper fraction should be first isolated and shown preceding the Egyptian unit fractions, and be surrounded by square brackets [''n'']. ;Task requirements: * show the Egyptian fractions for: \tfrac{43}{48} and \tfrac{5}{121} and \tfrac{2014}{59} * for all proper fractions, \tfrac{a}{b} where a and b are positive one-or two-digit (decimal) integers, find and show an Egyptian fraction that has: ::* the largest number of terms, ::* the largest denominator. * for all one-, two-, and three-digit integers, find and show (as above). {extra credit} ;Also see: * Wolfram MathWorld(tm) entry: Egyptian fraction
#include <stdbool.h> #include <stdint.h> #include <stdio.h> typedef int64_t integer; struct Pair { integer md; int tc; }; integer mod(integer x, integer y) { return ((x % y) + y) % y; } integer gcd(integer a, integer b) { if (0 == a) return b; if (0 == b) return a; if (a == b) return a; if (a > b) return gcd(a - b, b); return gcd(a, b - a); } void write0(bool show, char *str) { if (show) { printf(str); } } void write1(bool show, char *format, integer a) { if (show) { printf(format, a); } } void write2(bool show, char *format, integer a, integer b) { if (show) { printf(format, a, b); } } struct Pair egyptian(integer x, integer y, bool show) { struct Pair ret; integer acc = 0; bool first = true; ret.tc = 0; ret.md = 0; write2(show, "Egyptian fraction for %lld/%lld: ", x, y); while (x > 0) { integer z = (y + x - 1) / x; if (z == 1) { acc++; } else { if (acc > 0) { write1(show, "%lld + ", acc); first = false; acc = 0; ret.tc++; } else if (first) { first = false; } else { write0(show, " + "); } if (z > ret.md) { ret.md = z; } write1(show, "1/%lld", z); ret.tc++; } x = mod(-y, x); y = y * z; } if (acc > 0) { write1(show, "%lld", acc); ret.tc++; } write0(show, "\n"); return ret; } int main() { struct Pair p; integer nm = 0, dm = 0, dmn = 0, dmd = 0, den = 0;; int tm, i, j; egyptian(43, 48, true); egyptian(5, 121, true); // final term cannot be represented correctly egyptian(2014, 59, true); tm = 0; for (i = 1; i < 100; i++) { for (j = 1; j < 100; j++) { p = egyptian(i, j, false); if (p.tc > tm) { tm = p.tc; nm = i; dm = j; } if (p.md > den) { den = p.md; dmn = i; dmd = j; } } } printf("Term max is %lld/%lld with %d terms.\n", nm, dm, tm); // term max is correct printf("Denominator max is %lld/%lld\n", dmn, dmd); // denominator max is not correct egyptian(dmn, dmd, true); // enough digits cannot be represented without bigint return 0; }
Hailstone sequence
C
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
#include <stdio.h> #include <stdlib.h> int hailstone(int n, int *arry) { int hs = 1; while (n!=1) { hs++; if (arry) *arry++ = n; n = (n&1) ? (3*n+1) : (n/2); } if (arry) *arry++ = n; return hs; } int main() { int j, hmax = 0; int jatmax, n; int *arry; for (j=1; j<100000; j++) { n = hailstone(j, NULL); if (hmax < n) { hmax = n; jatmax = j; } } n = hailstone(27, NULL); arry = malloc(n*sizeof(int)); n = hailstone(27, arry); printf("[ %d, %d, %d, %d, ...., %d, %d, %d, %d] len=%d\n", arry[0],arry[1],arry[2],arry[3], arry[n-4], arry[n-3], arry[n-2], arry[n-1], n); printf("Max %d at j= %d\n", hmax, jatmax); free(arry); return 0; }
Harshad or Niven series
C
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
#include <stdio.h> static int digsum(int n) { int sum = 0; do { sum += n % 10; } while (n /= 10); return sum; } int main(void) { int n, done, found; for (n = 1, done = found = 0; !done; ++n) { if (n % digsum(n) == 0) { if (found++ < 20) printf("%d ", n); if (n > 1000) done = printf("\n%d\n", n); } } return 0; }
Haversine formula
C
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
#include <stdio.h> #include <stdlib.h> #include <math.h> #define R 6371 #define TO_RAD (3.1415926536 / 180) double dist(double th1, double ph1, double th2, double ph2) { double dx, dy, dz; ph1 -= ph2; ph1 *= TO_RAD, th1 *= TO_RAD, th2 *= TO_RAD; dz = sin(th1) - sin(th2); dx = cos(ph1) * cos(th1) - cos(th2); dy = sin(ph1) * cos(th1); return asin(sqrt(dx * dx + dy * dy + dz * dz) / 2) * 2 * R; } int main() { double d = dist(36.12, -86.67, 33.94, -118.4); /* Americans don't know kilometers */ printf("dist: %.1f km (%.1f mi.)\n", d, d / 1.609344); return 0; }
Hello world/Line printer
C
Cause a line printer attached to the computer to print a line containing the message: Hello World! ;Note: A line printer is not the same as standard output. A line printer was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
#include <stdio.h> int main() { FILE *lp; lp = fopen("/dev/lp0","w"); fprintf(lp,"Hello world!\n"); fclose(lp); return 0; }
Heronian triangles
C
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
#include<stdlib.h> #include<stdio.h> #include<math.h> typedef struct{ int a,b,c; int perimeter; double area; }triangle; typedef struct elem{ triangle t; struct elem* next; }cell; typedef cell* list; void addAndOrderList(list *a,triangle t){ list iter,temp; int flag = 0; if(*a==NULL){ *a = (list)malloc(sizeof(cell)); (*a)->t = t; (*a)->next = NULL; } else{ temp = (list)malloc(sizeof(cell)); iter = *a; while(iter->next!=NULL){ if(((iter->t.area<t.area)||(iter->t.area==t.area && iter->t.perimeter<t.perimeter)||(iter->t.area==t.area && iter->t.perimeter==t.perimeter && iter->t.a<=t.a)) && (iter->next==NULL||(t.area<iter->next->t.area || t.perimeter<iter->next->t.perimeter || t.a<iter->next->t.a))){ temp->t = t; temp->next = iter->next; iter->next = temp; flag = 1; break; } iter = iter->next; } if(flag!=1){ temp->t = t; temp->next = NULL; iter->next = temp; } } } int gcd(int a,int b){ if(b!=0) return gcd(b,a%b); return a; } void calculateArea(triangle *t){ (*t).perimeter = (*t).a + (*t).b + (*t).c; (*t).area = sqrt(0.5*(*t).perimeter*(0.5*(*t).perimeter - (*t).a)*(0.5*(*t).perimeter - (*t).b)*(0.5*(*t).perimeter - (*t).c)); } list generateTriangleList(int maxSide,int *count){ int a,b,c; triangle t; list herons = NULL; *count = 0; for(a=1;a<=maxSide;a++){ for(b=1;b<=a;b++){ for(c=1;c<=b;c++){ if(c+b > a && gcd(gcd(a,b),c)==1){ t = (triangle){a,b,c}; calculateArea(&t); if(t.area/(int)t.area == 1){ addAndOrderList(&herons,t); (*count)++; } } } } } return herons; } void printList(list a,int limit,int area){ list iter = a; int count = 1; printf("\nDimensions\tPerimeter\tArea"); while(iter!=NULL && count!=limit+1){ if(area==-1 ||(area==iter->t.area)){ printf("\n%d x %d x %d\t%d\t\t%d",iter->t.a,iter->t.b,iter->t.c,iter->t.perimeter,(int)iter->t.area); count++; } iter = iter->next; } } int main(int argC,char* argV[]) { int count; list herons = NULL; if(argC!=4) printf("Usage : %s <Max side, max triangles to print and area, -1 for area to ignore>",argV[0]); else{ herons = generateTriangleList(atoi(argV[1]),&count); printf("Triangles found : %d",count); (atoi(argV[3])==-1)?printf("\nPrinting first %s triangles.",argV[2]):printf("\nPrinting triangles with area %s square units.",argV[3]); printList(herons,atoi(argV[2]),atoi(argV[3])); free(herons); } return 0; }
Hofstadter-Conway $10,000 sequence
C
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
#include <stdio.h> #include <stdlib.h> int a_list[1<<20 + 1]; int doSqnc( int m) { int max_df = 0; int p2_max = 2; int v, n; int k1 = 2; int lg2 = 1; double amax = 0; a_list[0] = -50000; a_list[1] = a_list[2] = 1; v = a_list[2]; for (n=3; n <= m; n++) { v = a_list[n] = a_list[v] + a_list[n-v]; if ( amax < v*1.0/n) amax = v*1.0/n; if ( 0 == (k1&n)) { printf("Maximum between 2^%d and 2^%d was %f\n", lg2,lg2+1, amax); amax = 0; lg2++; } k1 = n; } return 1; }
Hofstadter Figure-Figure sequences
C
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
#include <stdio.h> #include <stdlib.h> // simple extensible array stuff typedef unsigned long long xint; typedef struct { size_t len, alloc; xint *buf; } xarray; xarray rs, ss; void setsize(xarray *a, size_t size) { size_t n = a->alloc; if (!n) n = 1; while (n < size) n <<= 1; if (a->alloc < n) { a->buf = realloc(a->buf, sizeof(xint) * n); if (!a->buf) abort(); a->alloc = n; } } void push(xarray *a, xint v) { while (a->alloc <= a->len) setsize(a, a->alloc * 2); a->buf[a->len++] = v; } // sequence stuff void RS_append(void); xint R(int n) { while (n > rs.len) RS_append(); return rs.buf[n - 1]; } xint S(int n) { while (n > ss.len) RS_append(); return ss.buf[n - 1]; } void RS_append() { int n = rs.len; xint r = R(n) + S(n); xint s = S(ss.len); push(&rs, r); while (++s < r) push(&ss, s); push(&ss, r + 1); // pesky 3 } int main(void) { push(&rs, 1); push(&ss, 2); int i; printf("R(1 .. 10):"); for (i = 1; i <= 10; i++) printf(" %llu", R(i)); char seen[1001] = { 0 }; for (i = 1; i <= 40; i++) seen[ R(i) ] = 1; for (i = 1; i <= 960; i++) seen[ S(i) ] = 1; for (i = 1; i <= 1000 && seen[i]; i++); if (i <= 1000) { fprintf(stderr, "%d not seen\n", i); abort(); } puts("\nfirst 1000 ok"); return 0; }
Hofstadter Q sequence
C
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
#include <stdio.h> #include <stdlib.h> #define N 100000 int main() { int i, flip, *q = (int*)malloc(sizeof(int) * N) - 1; q[1] = q[2] = 1; for (i = 3; i <= N; i++) q[i] = q[i - q[i - 1]] + q[i - q[i - 2]]; for (i = 1; i <= 10; i++) printf("%d%c", q[i], i == 10 ? '\n' : ' '); printf("%d\n", q[1000]); for (flip = 0, i = 1; i < N; i++) flip += q[i] > q[i + 1]; printf("flips: %d\n", flip); return 0; }
Honeycombs
C
The task is to produce a matrix of 20 hexagon shaped widgets in a honeycomb arrangement. The matrix should be arranged in such a manner that there are five columns of four hexagons. The hexagons in columns one, three and five are aligned horizontally, whereas the hexagons in columns two and four occupy a lower position within the arrangement. Each hexagon should be the same colour, and should display a unique randomly selected single capital letter on the front. The application should now wait for the user to select a hexagon, either by using a pointing device, or by pressing a key that carries a corresponding letter on a hexagon. For platforms that support pointing devices and keyboards, the application should support both methods of selection. A record of the chosen letters should be maintained and the code should be suitably commented, at the point where the the selected letter has been determined. The selected hexagon should now change colour on the display. The cycle repeats until the user has chosen all of the letters. Note that each letter can only be selected once and previously selected hexagons retain their colour after selection. The program terminates when all letters have been chosen. Optionally: output the list of selected letters and show the last selected letter, cater for a different number of columns or a different number of hexagons in each column, cater for two players, (turns alternate and the hexagons change a different colour depending on whether they were selected by player one or player two and records of both players selections are maintained.) [[image:honeycomb.gif]]
/* Program for gtk3 */ /* discovery: essential to use consistent documentation */ /* compilation on linux: */ /* $ a=./hexagon && make -k "CFLAGS=$( pkg-config --cflags gtk+-3.0 )" "LOADLIBES=$( pkg-config --libs gtk+-3.0 )" $a && $a --gtk-debug=all */ /* search for to do */ /* The keyboard and mouse callbacks increment the "selected" status, */ /* of the matching hexagon, */ /* then invalidate the drawing window which triggers a draw event. */ /* The draw callback redraws the screen and tests for completion, */ /* upon which the program spits back the characters selected and exits */ #include<math.h> #include<string.h> #include<stdlib.h> #include<gtk/gtk.h> static GdkPixbuf*create_pixbuf(const gchar*filename) { GdkPixbuf*pixbuf; GError*error = NULL; pixbuf = gdk_pixbuf_new_from_file(filename, &error); if(!pixbuf) { fprintf(stderr,"\n%s\n", error->message); g_error_free(error); } return pixbuf; } #define NGON struct ngon NGON { double Cx,Cy, r; int sides, selected; char c; }; GRand*random_numbers = NULL; #define R 20 #define TAU (2*M_PI) /* http://laughingsquid.com/pi-is-wrong/ */ #define OFFSET_X (1+sin(TAU/12)) #define OFFSET_Y (cos(TAU/12)) #define ODD(A) ((A)&1) static void initialize_hexagons(NGON*hs,size_t n) { NGON*h; gint i,broken; GQueue*shuffler = g_queue_new(); if (NULL == shuffler) { fputs("\ncannot allocate shuffling queue. quitting!\n",stderr); exit(EXIT_FAILURE); } /* randomize characters by stuffing them onto a double end queue and popping them off from random positions */ if ((broken = (NULL == random_numbers))) random_numbers = g_rand_new(); for (i = 'A'; i <= 'Z'; ++i) g_queue_push_head(shuffler,GINT_TO_POINTER(i)); memset(hs,0,n*(sizeof(NGON))); hs[n-1].sides = -1; /* assign the sentinel */ for (h = hs; !h->sides; ++h) { int div = (h-hs)/4, mod = (h-hs)%4; h->sides = 6; h->c = GPOINTER_TO_INT( g_queue_pop_nth( shuffler, g_rand_int_range( random_numbers, (gint32)0, (gint32)g_queue_get_length(shuffler)))); fputc(h->c,stderr); h->r = R; h->Cx = R*(2+div*OFFSET_X), h->Cy = R*(2*(1+mod*OFFSET_Y)+ODD(div)*OFFSET_Y); fprintf(stderr,"(%g,%g)\n",h->Cx,h->Cy); } fputc('\n',stderr); g_queue_free(shuffler); if (broken) g_rand_free(random_numbers); } static void add_loop(cairo_t*cr,NGON*hs,int select) { NGON*h; double r,Cx,Cy,x,y; int i, sides; for (h = hs; 0 < (sides = h->sides); ++h) if ((select && h->selected) || (select == h->selected)) { r = h->r, Cx = h->Cx, Cy = h->Cy; i = 0; x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_move_to(cr,x,y); for (i = 1; i < sides; ++i) x = Cx+r*cos(TAU*i/sides), y = Cy+r*sin(TAU*i/sides), cairo_line_to(cr,x,y); cairo_close_path(cr); } } static int make_labels(cairo_t*cr,NGON*hs,int select) { NGON*h; int i = 0; char text[2]; text[1] = 0; for (h = hs; 0 < h->sides; ++h) if ((select && h->selected) || (select == h->selected)) /* yuck, need to measure the font. Better to use pango_cairo */ *text = h->c, cairo_move_to(cr,h->Cx,h->Cy), cairo_show_text(cr,text), ++i; return i; } static int archive(int a) { static GQueue*q = NULL; if ((NULL == q) && (NULL == (q = g_queue_new()))) { fputs("\ncannot allocate archival queue. quitting!\n",stderr); exit(EXIT_FAILURE); } if (a < -1) /* reset */ return g_queue_free(q), q = NULL, 0; if (-1 == a) /* pop off tail */ return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_pop_tail(q)); if (!a) /* peek most recent entry */ return g_queue_is_empty(q) ? 0 : GPOINTER_TO_INT(g_queue_peek_head(q)); g_queue_push_head(q,GINT_TO_POINTER(a)); /* store */ return a; } /* to do: use appropriate sizing, use the cairo transformation matrix */ static gboolean draw(GtkWidget*widget,cairo_t*cr,gpointer data) { /* unselected fill in yellow */ cairo_set_source_rgba(cr,0.8,0.8,0,1), add_loop(cr,(NGON*)data,0); cairo_fill(cr); /* selected fill, purple */ cairo_set_source_rgba(cr,0.8,0,0.8,1); add_loop(cr,(NGON*)data,1); cairo_fill_preserve(cr); /* all outlines gray, background shows through, fun fun! */ cairo_set_line_width (cr, 3.0); cairo_set_source_rgba(cr,0.7,0.7,0.7,0.7); add_loop(cr,(NGON*)data,0); cairo_stroke(cr); /* select labels */ cairo_set_source_rgba(cr,0,1,0,1); make_labels(cr,(NGON*)data,1); cairo_stroke(cr); /* unselected labels */ cairo_set_source_rgba(cr,1,0,0,1); /* to do: clean up this exit code */ if (!make_labels(cr,(NGON*)data,0)) { int c; putchar('\n'); while ((c = archive(-1))) putchar(c); puts("\nfinished"); archive(-2); exit(EXIT_SUCCESS); } cairo_stroke(cr); return TRUE; } /*the widget is a GtkDrawingArea*/ static gboolean button_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) { NGON*h,*hs = (NGON*)data; gdouble x_win, y_win; if (!gdk_event_get_coords(event,&x_win,&y_win)) fputs("\nBUTTON, gdk_event_get_coords(event,&x_win,&y_win)) failed\n",stderr); else { fprintf(stderr,"x_win=%g y_win=%g\n",(double)x_win,(double)y_win); for (h = hs; 0 < h->sides; ++h) /* detection algorithm: */ /* if mouse click within inner radius of hexagon */ /* Much easier than all in-order cross products have same sign test! */ if ((pow((x_win-h->Cx),2)+pow((y_win-h->Cy),2)) < pow((h->r*cos(TAU/(180/h->sides))),2)) { ++h->selected; archive(h->c); /* discovery: gdk_window_invalidate_region with NULL second argument does not work */ gdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE); break; } } return TRUE; } static gboolean key_press_event(GtkWidget*widget,const GdkEvent*event,gpointer data) { NGON*h,*hs = (NGON*)data; guint keyval; int unicode; if (!gdk_event_get_keyval(event,&keyval)) fputs("\nKEY! gdk_event_get_keyval(event,&keyval)) failed.\n",stderr); else { unicode = (int)gdk_keyval_to_unicode(gdk_keyval_to_upper(keyval)); fprintf(stderr,"key with unicode value: %d\n",unicode); for (h = hs; 0 < h->sides; ++h) /* look for a matching character associated with a hexagon */ if (h->c == unicode) { ++(h->selected); archive(h->c); /* discovery: gdk_window_invalidate_region with NULL second argument does not work */ gdk_window_invalidate_rect(gtk_widget_get_window(widget),(const GdkRectangle*)NULL,TRUE); break; } } return TRUE; } int main(int argc,char*argv[]) { GtkWidget *window, *vbox, /* *label, */ *drawing_area; NGON ngons[21]; /* sentinal has negative number of sides */ /* discovery: gtk_init removes gtk debug flags, such as --gtk-debug=all */ /* also calls gdk_init which handles --display and --screen or other X11 communication issues */ gtk_init(&argc, &argv); /* GTK VERSION 3.2.0 */ fprintf(stderr,"GTK VERSION %d.%d.%d\n",GTK_MAJOR_VERSION,GTK_MINOR_VERSION,GTK_MICRO_VERSION); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); /* discovery: to make window transparent I have to use the alpha channel correctly */ /* discovery: GTK_WINDOW(GtkWidget*) casts the widget to window */ /* discovery: window in the function name? use GTK_WINDOW. g_ in function name? use G_OBJECT */ gtk_window_set_title(GTK_WINDOW(window), "Rosetta Code Honeycomb, C with GTK"); gtk_window_set_default_size(GTK_WINDOW(window), 308, 308+12+8); /* XxY */ /* discovery: making the window vanish does not stop the program */ /* discovery: NULL is placeholder for extra data sent to the callback */ g_signal_connect_swapped(G_OBJECT(window),"destroy",G_CALLBACK(gtk_main_quit),NULL); /* I created /tmp/favicon.ico from http://rosettacode.org/favicon.ico */ /* Your window manager could use the icon, if it exists, and you fix the file name */ gtk_window_set_icon(GTK_WINDOW(window),create_pixbuf("/tmp/favicon.ico")); vbox = gtk_vbox_new(TRUE,1); gtk_container_add(GTK_CONTAINER(window),vbox); /* to do: fix the label widget */ /* I did not learn to control multiple box packing, and I was */ /* too lazy to make the label widget accessible. Plan was to */ /* insert the most recent character using "peek" option of the archive */ #if 0 label = gtk_label_new("None Selected"); gtk_widget_set_size_request(label,308,20); gtk_box_pack_end(GTK_BOX(vbox),label,FALSE,TRUE,4); #endif drawing_area = gtk_drawing_area_new(); gtk_widget_set_events(drawing_area,GDK_BUTTON_PRESS_MASK|GDK_KEY_PRESS_MASK|GDK_EXPOSURE_MASK); random_numbers = g_rand_new(); initialize_hexagons(ngons,G_N_ELEMENTS(ngons)); /* Discovery: expose_event changed to draw signal. We no longer need configure-event */ g_signal_connect(G_OBJECT(drawing_area),"draw",G_CALLBACK(draw),(gpointer)ngons); g_signal_connect(G_OBJECT(drawing_area),"button-press-event",G_CALLBACK(button_press_event),(gpointer)ngons); g_signal_connect(G_OBJECT(drawing_area),"key-press-event",G_CALLBACK(key_press_event),(gpointer)ngons); gtk_widget_set_size_request(drawing_area, 308, 308); /* XxY */ gtk_box_pack_start(GTK_BOX(vbox),drawing_area,TRUE,TRUE,4); /* Discovery: must allow focus to receive keyboard events */ gtk_widget_set_can_focus(drawing_area,TRUE); /* Discovery: can set show for individual widgets or use show_all */ gtk_widget_show_all(window); gtk_main(); g_rand_free(random_numbers); return EXIT_SUCCESS; }
ISBN13 check digit
C
Validate the check digit of an ISBN-13 code: ::* Multiply every other digit by '''3'''. ::* Add these numbers and the other digits. ::* Take the remainder of this number after division by '''10'''. ::* If it is '''0''', the ISBN-13 check digit is correct. You might use the following codes for testing: ::::* 978-0596528126 (good) ::::* 978-0596528120 (bad) ::::* 978-1788399081 (good) ::::* 978-1788399083 (bad) Show output here, on this page ;See also: :* for details: 13-digit ISBN method of validation. (installs cookies.)
#include <stdio.h> int check_isbn13(const char *isbn) { int ch = *isbn, count = 0, sum = 0; /* check isbn contains 13 digits and calculate weighted sum */ for ( ; ch != 0; ch = *++isbn, ++count) { /* skip hyphens or spaces */ if (ch == ' ' || ch == '-') { --count; continue; } if (ch < '0' || ch > '9') { return 0; } if (count & 1) { sum += 3 * (ch - '0'); } else { sum += ch - '0'; } } if (count != 13) return 0; return !(sum%10); } int main() { int i; const char* isbns[] = {"978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"}; for (i = 0; i < 4; ++i) { printf("%s: %s\n", isbns[i], check_isbn13(isbns[i]) ? "good" : "bad"); } return 0; }
I before E except after C
C
The phrase "I before E, except after C" is a widely known mnemonic which is supposed to help when spelling English words. ;Task: Using the word list from http://wiki.puzzlers.org/pub/wordlists/unixdict.txt, check if the two sub-clauses of the phrase are plausible individually: :::# ''"I before E when not preceded by C"'' :::# ''"E before I when preceded by C"'' If both sub-phrases are plausible then the original phrase can be said to be plausible. Something is plausible if the number of words having the feature is more than two times the number of words having the opposite feature (where feature is 'ie' or 'ei' preceded or not by 'c' as appropriate). ;Stretch goal: As a stretch goal use the entries from the table of Word Frequencies in Written and Spoken English: based on the British National Corpus, (selecting those rows with three space or tab separated words only), to see if the phrase is plausible when word frequencies are taken into account. ''Show your output here as well as your program.'' ;cf.: * Schools to rethink 'i before e' - BBC news, 20 June 2009 * I Before E Except After C - QI Series 8 Ep 14, (humorous) * Companion website for the book: "Word Frequencies in Written and Spoken English: based on the British National Corpus".
%{ /* compilation and example on a GNU linux system: $ flex --case-insensitive --noyywrap --outfile=cia.c source.l $ make LOADLIBES=-lfl cia $ ./cia < unixdict.txt I before E when not preceded by C: plausible E before I when preceded by C: implausible Overall, the rule is: implausible */ int cie, cei, ie, ei; %} %% cie ++cie, ++ie; /* longer patterns are matched preferentially, consuming input */ cei ++cei, ++ei; ie ++ie; ei ++ei; .|\n ; %% int main() { cie = cei = ie = ei = 0; yylex(); printf("%s: %s\n","I before E when not preceded by C", (2*ei < ie ? "plausible" : "implausible")); printf("%s: %s\n","E before I when preceded by C", (2*cie < cei ? "plausible" : "implausible")); printf("%s: %s\n","Overall, the rule is", (2*(cie+ei) < (cei+ie) ? "plausible" : "implausible")); return 0; }
Identity matrix
C
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
#include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { if (argc < 2) { printf("usage: identitymatrix <number of rows>\n"); exit(EXIT_FAILURE); } int rowsize = atoi(argv[1]); if (rowsize < 0) { printf("Dimensions of matrix cannot be negative\n"); exit(EXIT_FAILURE); } int numElements = rowsize * rowsize; if (numElements < rowsize) { printf("Squaring %d caused result to overflow to %d.\n", rowsize, numElements); abort(); } int** matrix = calloc(numElements, sizeof(int*)); if (!matrix) { printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int*)); abort(); } for (unsigned int row = 0;row < rowsize;row++) { matrix[row] = calloc(numElements, sizeof(int)); if (!matrix[row]) { printf("Failed to allocate %d elements of %ld bytes each\n", numElements, sizeof(int)); abort(); } matrix[row][row] = 1; } printf("Matrix is: \n"); for (unsigned int row = 0;row < rowsize;row++) { for (unsigned int column = 0;column < rowsize;column++) { printf("%d ", matrix[row][column]); } printf("\n"); } }
Idiomatically determine all the lowercase and uppercase letters
C
Idiomatically determine all the lowercase and uppercase letters (of the Latin [English] alphabet) being used currently by a computer programming language. The method should find the letters regardless of the hardware architecture that is being used (ASCII, EBCDIC, or other). ;Task requirements Display the set of all: ::::::* lowercase letters ::::::* uppercase letters that can be used (allowed) by the computer program, where ''letter'' is a member of the Latin (English) alphabet: '''a''' --> '''z''' and '''A''' --> '''Z'''. You may want to mention what hardware architecture is being used, and if applicable, the operating system. ;See also * Idiomatically determine all the characters that can be used for symbols.
#include <stdio.h> int main(int argc, char const *argv[]) { for (char c = 0x41; c < 0x5b; c ++) putchar(c); putchar('\n'); for (char c = 0x61; c < 0x7b; c ++) putchar(c); putchar('\n'); return 0; }
Include a file
C
Demonstrate the language's ability to include source code from other files. ;See Also * [[Compiler/Simple file inclusion pre processor]]
/* Standard and other library header names are enclosed between chevrons */ #include <stdlib.h> /* User/in-project header names are usually enclosed between double-quotes */ #include "myutil.h"
Integer overflow
C
Some languages support one or more integer types of the underlying processor. This integer types have fixed size; usually '''8'''-bit, '''16'''-bit, '''32'''-bit, or '''64'''-bit. The integers supported by such a type can be ''signed'' or ''unsigned''. Arithmetic for machine level integers can often be done by single CPU instructions. This allows high performance and is the main reason to support machine level integers. ;Definition: An integer overflow happens when the result of a computation does not fit into the fixed size integer. The result can be too small or too big to be representable in the fixed size integer. ;Task: When a language has fixed size integer types, create a program that does arithmetic computations for the fixed size integers of the language. These computations must be done such that the result would overflow. The program should demonstrate what the following expressions do. For 32-bit signed integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit signed integer |- | -(-2147483647-1) | 2147483648 |- | 2000000000 + 2000000000 | 4000000000 |- | -2147483647 - 2147483647 | -4294967294 |- | 46341 * 46341 | 2147488281 |- | (-2147483647-1) / -1 | 2147483648 |} For 64-bit signed integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit signed integer |- | -(-9223372036854775807-1) | 9223372036854775808 |- | 5000000000000000000+5000000000000000000 | 10000000000000000000 |- | -9223372036854775807 - 9223372036854775807 | -18446744073709551614 |- | 3037000500 * 3037000500 | 9223372037000250000 |- | (-9223372036854775807-1) / -1 | 9223372036854775808 |} For 32-bit unsigned integers: ::::: {|class="wikitable" !Expression !Result that does not fit into a 32-bit unsigned integer |- | -4294967295 | -4294967295 |- | 3000000000 + 3000000000 | 6000000000 |- | 2147483647 - 4294967295 | -2147483648 |- | 65537 * 65537 | 4295098369 |} For 64-bit unsigned integers: ::: {|class="wikitable" !Expression !Result that does not fit into a 64-bit unsigned integer |- | -18446744073709551615 | -18446744073709551615 |- | 10000000000000000000 + 10000000000000000000 | 20000000000000000000 |- | 9223372036854775807 - 18446744073709551615 | -9223372036854775808 |- | 4294967296 * 4294967296 | 18446744073709551616 |} ;Notes: :* When the integer overflow does trigger an exception show how the exception is caught. :* When the integer overflow produces some value, print it. :* It should be explicitly noted when an integer overflow is not recognized, the program continues with wrong results. :* This should be done for signed and unsigned integers of various sizes supported by the computer programming language. :* When a language has no fixed size integer type, or when no integer overflow can occur for other reasons, this should be noted. :* It is okay to mention, when a language supports unlimited precision integers, but this task is NOT the place to demonstrate the capabilities of unlimited precision integers.
#include <stdio.h> int main (int argc, char *argv[]) { printf("Signed 32-bit:\n"); printf("%d\n", -(-2147483647-1)); printf("%d\n", 2000000000 + 2000000000); printf("%d\n", -2147483647 - 2147483647); printf("%d\n", 46341 * 46341); printf("%d\n", (-2147483647-1) / -1); printf("Signed 64-bit:\n"); printf("%ld\n", -(-9223372036854775807-1)); printf("%ld\n", 5000000000000000000+5000000000000000000); printf("%ld\n", -9223372036854775807 - 9223372036854775807); printf("%ld\n", 3037000500 * 3037000500); printf("%ld\n", (-9223372036854775807-1) / -1); printf("Unsigned 32-bit:\n"); printf("%u\n", -4294967295U); printf("%u\n", 3000000000U + 3000000000U); printf("%u\n", 2147483647U - 4294967295U); printf("%u\n", 65537U * 65537U); printf("Unsigned 64-bit:\n"); printf("%lu\n", -18446744073709551615LU); printf("%lu\n", 10000000000000000000LU + 10000000000000000000LU); printf("%lu\n", 9223372036854775807LU - 18446744073709551615LU); printf("%lu\n", 4294967296LU * 4294967296LU); return 0; }
Integer sequence
C
Create a program that, when run, would display all integers from '''1''' to ''' ''' (or any relevant implementation limit), in sequence (i.e. 1, 2, 3, 4, etc) if given enough time. An example may not be able to reach arbitrarily-large numbers based on implementations limits. For example, if integers are represented as a 32-bit unsigned value with 0 as the smallest representable value, the largest representable value would be 4,294,967,295. Some languages support arbitrarily-large numbers as a built-in feature, while others make use of a module or library. If appropriate, provide an example which reflect the language implementation's common built-in limits as well as an example which supports arbitrarily large numbers, and describe the nature of such limitations--or lack thereof.
#include <openssl/bn.h> /* BN_*() */ #include <openssl/err.h> /* ERR_*() */ #include <stdio.h> /* fprintf(), puts() */ void fail(const char *message) { fprintf(stderr, "%s: error 0x%08lx\n", ERR_get_error()); exit(1); } int main() { BIGNUM i; char *s; BN_init(&i); for (;;) { if (BN_add_word(&i, 1) == 0) fail("BN_add_word"); s = BN_bn2dec(&i); if (s == NULL) fail("BN_bn2dec"); puts(s); OPENSSL_free(s); } /* NOTREACHED */ }
Intersecting number wheels
C
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Wheel { char *seq; int len; int pos; }; struct Wheel *create(char *seq) { struct Wheel *w = malloc(sizeof(struct Wheel)); if (w == NULL) { return NULL; } w->seq = seq; w->len = strlen(seq); w->pos = 0; return w; } char cycle(struct Wheel *w) { char c = w->seq[w->pos]; w->pos = (w->pos + 1) % w->len; return c; } struct Map { struct Wheel *v; struct Map *next; char k; }; struct Map *insert(char k, struct Wheel *v, struct Map *head) { struct Map *m = malloc(sizeof(struct Map)); if (m == NULL) { return NULL; } m->k = k; m->v = v; m->next = head; return m; } struct Wheel *find(char k, struct Map *m) { struct Map *ptr = m; while (ptr != NULL) { if (ptr->k == k) { return ptr->v; } ptr = ptr->next; } return NULL; } void printOne(char k, struct Map *m) { struct Wheel *w = find(k, m); char c; if (w == NULL) { printf("Missing the wheel for: %c\n", k); exit(1); } c = cycle(w); if ('0' <= c && c <= '9') { printf(" %c", c); } else { printOne(c, m); } } void exec(char start, struct Map *m) { struct Wheel *w; int i; if (m == NULL) { printf("Unable to proceed."); return; } for (i = 0; i < 20; i++) { printOne(start, m); } printf("\n"); } void group1() { struct Wheel *a = create("123"); struct Map *m = insert('A', a, NULL); exec('A', m); } void group2() { struct Wheel *a = create("1B2"); struct Wheel *b = create("34"); struct Map *m = insert('A', a, NULL); m = insert('B', b, m); exec('A', m); } void group3() { struct Wheel *a = create("1DD"); struct Wheel *d = create("678"); struct Map *m = insert('A', a, NULL); m = insert('D', d, m); exec('A', m); } void group4() { struct Wheel *a = create("1BC"); struct Wheel *b = create("34"); struct Wheel *c = create("5B"); struct Map *m = insert('A', a, NULL); m = insert('B', b, m); m = insert('C', c, m); exec('A', m); } int main() { group1(); group2(); group3(); group4(); return 0; }
Inverted syntax
C
'''Inverted syntax with conditional expressions''' In traditional syntax conditional expressions are usually shown before the action within a statement or code block: IF raining=true THEN needumbrella=true In inverted syntax, the action is listed before the conditional expression in the statement or code block: needumbrella=true IF raining=true '''Inverted syntax with assignment''' In traditional syntax, assignments are usually expressed with the variable appearing before the expression: a = 6 In inverted syntax, the expression appears before the variable: 6 = a '''Task''' The task is to demonstrate support for inverted syntax forms within the language by showing both the traditional and inverted forms.
main() { int a = 0; do { register int _o = 2; do { switch (_o) { case 1: a = 4; case 0: break; case 2: _o = !!(foo()); continue; } break; } while (1); } while (0); printf("%d\n", a); exit(0); }
Iterated digits squaring
C
If you add the square of the digits of a Natural number (an integer bigger than zero), you always end with either 1 or 89: 15 -> 26 -> 40 -> 16 -> 37 -> 58 -> 89 7 -> 49 -> 97 -> 130 -> 10 -> 1 An example in Python: >>> step = lambda x: sum(int(d) ** 2 for d in str(x)) >>> iterate = lambda x: x if x in [1, 89] else iterate(step(x)) >>> [iterate(x) for x in xrange(1, 20)] [1, 89, 89, 89, 89, 89, 1, 89, 89, 1, 89, 89, 1, 89, 89, 89, 89, 89, 1] ;Task: : Count how many number chains for integers 1 <= n < 100_000_000 end with a value 89. Or, for much less credit - (showing that your algorithm and/or language is slow): : Count how many number chains for integers 1 <= n < 1_000_000 end with a value 89. This problem derives from the Project Euler problem 92. For a quick algorithm for this task see the talk page ;Related tasks: * [[Combinations with repetitions]] * [[Digital root]] * [[Digital root/Multiplicative digital root]]
#include <stdio.h> typedef unsigned long long ull; int is89(int x) { while (1) { int s = 0; do s += (x%10)*(x%10); while ((x /= 10)); if (s == 89) return 1; if (s == 1) return 0; x = s; } } int main(void) { // array bounds is sort of random here, it's big enough for 64bit unsigned. ull sums[32*81 + 1] = {1, 0}; for (int n = 1; ; n++) { for (int i = n*81; i; i--) { for (int j = 1; j < 10; j++) { int s = j*j; if (s > i) break; sums[i] += sums[i-s]; } } ull count89 = 0; for (int i = 1; i < n*81 + 1; i++) { if (!is89(i)) continue; if (sums[i] > ~0ULL - count89) { printf("counter overflow for 10^%d\n", n); return 0; } count89 += sums[i]; } printf("1->10^%d: %llu\n", n, count89); } return 0; }
Jacobi symbol
C
The '''Jacobi symbol''' is a multiplicative function that generalizes the Legendre symbol. Specifically, the Jacobi symbol (a | n) equals the product of the Legendre symbols (a | p_i)^(k_i), where n = p_1^(k_1)*p_2^(k_2)*...*p_i^(k_i) and the Legendre symbol (a | p) denotes the value of a ^ ((p-1)/2) (mod p) * (a | p) 1 if a is a square (mod p) * (a | p) -1 if a is not a square (mod p) * (a | p) 0 if a 0 If n is prime, then the Jacobi symbol (a | n) equals the Legendre symbol (a | n). ;Task: Calculate the Jacobi symbol (a | n). ;Reference: * Wikipedia article on Jacobi symbol.
#include <stdlib.h> #include <stdio.h> #define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))) int jacobi(unsigned long a, unsigned long n) { if (a >= n) a %= n; int result = 1; while (a) { while ((a & 1) == 0) { a >>= 1; if ((n & 7) == 3 || (n & 7) == 5) result = -result; } SWAP(a, n); if ((a & 3) == 3 && (n & 3) == 3) result = -result; a %= n; } if (n == 1) return result; return 0; } void print_table(unsigned kmax, unsigned nmax) { printf("n\\k|"); for (int k = 0; k <= kmax; ++k) printf("%'3u", k); printf("\n----"); for (int k = 0; k <= kmax; ++k) printf("---"); putchar('\n'); for (int n = 1; n <= nmax; n += 2) { printf("%-2u |", n); for (int k = 0; k <= kmax; ++k) printf("%'3d", jacobi(k, n)); putchar('\n'); } } int main() { print_table(20, 21); return 0; }
Jaro similarity
C
The Jaro distance is a measure of edit distance between two strings; its inverse, called the ''Jaro similarity'', is a measure of two strings' similarity: the higher the value, the more similar the strings are. The score is normalized such that '''0''' equates to no similarities and '''1''' is an exact match. ;;Definition The Jaro similarity d_j of two given strings s_1 and s_2 is : d_j = \left\{ \begin{array}{l l} 0 & \text{if }m = 0\\ \frac{1}{3}\left(\frac{m}{|s_1|} + \frac{m}{|s_2|} + \frac{m-t}{m}\right) & \text{otherwise} \end{array} \right. Where: * m is the number of ''matching characters''; * t is half the number of ''transpositions''. Two characters from s_1 and s_2 respectively, are considered ''matching'' only if they are the same and not farther apart than \left\lfloor\frac{\max(|s_1|,|s_2|)}{2}\right\rfloor-1 characters. Each character of s_1 is compared with all its matching characters in s_2. Each difference in position is half a ''transposition''; that is, the number of transpositions is half the number of characters which are common to the two strings but occupy different positions in each one. ;;Example Given the strings s_1 ''DWAYNE'' and s_2 ''DUANE'' we find: * m = 4 * |s_1| = 6 * |s_2| = 5 * t = 0 We find a Jaro score of: : d_j = \frac{1}{3}\left(\frac{4}{6} + \frac{4}{5} + \frac{4-0}{4}\right) = 0.822 ;Task Implement the Jaro algorithm and show the similarity scores for each of the following pairs: * ("MARTHA", "MARHTA") * ("DIXON", "DICKSONX") * ("JELLYFISH", "SMELLYFISH") ; See also * Jaro-Winkler distance on Wikipedia.
#include <stdlib.h> #include <string.h> #include <ctype.h> #include <stdio.h> #define TRUE 1 #define FALSE 0 #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) double jaro(const char *str1, const char *str2) { // length of the strings int str1_len = strlen(str1); int str2_len = strlen(str2); // if both strings are empty return 1 // if only one of the strings is empty return 0 if (str1_len == 0) return str2_len == 0 ? 1.0 : 0.0; // max distance between two chars to be considered matching // floor() is ommitted due to integer division rules int match_distance = (int) max(str1_len, str2_len)/2 - 1; // arrays of bools that signify if that char in the matching string has a match int *str1_matches = calloc(str1_len, sizeof(int)); int *str2_matches = calloc(str2_len, sizeof(int)); // number of matches and transpositions double matches = 0.0; double transpositions = 0.0; // find the matches for (int i = 0; i < str1_len; i++) { // start and end take into account the match distance int start = max(0, i - match_distance); int end = min(i + match_distance + 1, str2_len); for (int k = start; k < end; k++) { // if str2 already has a match continue if (str2_matches[k]) continue; // if str1 and str2 are not if (str1[i] != str2[k]) continue; // otherwise assume there is a match str1_matches[i] = TRUE; str2_matches[k] = TRUE; matches++; break; } } // if there are no matches return 0 if (matches == 0) { free(str1_matches); free(str2_matches); return 0.0; } // count transpositions int k = 0; for (int i = 0; i < str1_len; i++) { // if there are no matches in str1 continue if (!str1_matches[i]) continue; // while there is no match in str2 increment k while (!str2_matches[k]) k++; // increment transpositions if (str1[i] != str2[k]) transpositions++; k++; } // divide the number of transpositions by two as per the algorithm specs // this division is valid because the counted transpositions include both // instances of the transposed characters. transpositions /= 2.0; // free the allocated memory free(str1_matches); free(str2_matches); // return the Jaro distance return ((matches / str1_len) + (matches / str2_len) + ((matches - transpositions) / matches)) / 3.0; } int main() { printf("%f\n", jaro("MARTHA", "MARHTA")); printf("%f\n", jaro("DIXON", "DICKSONX")); printf("%f\n", jaro("JELLYFISH", "SMELLYFISH")); }
Julia set
C
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
#include<graphics.h> #include<stdlib.h> #include<math.h> typedef struct{ double x,y; }complex; complex add(complex a,complex b){ complex c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } complex sqr(complex a){ complex c; c.x = a.x*a.x - a.y*a.y; c.y = 2*a.x*a.y; return c; } double mod(complex a){ return sqrt(a.x*a.x + a.y*a.y); } complex mapPoint(int width,int height,double radius,int x,int y){ complex c; int l = (width<height)?width:height; c.x = 2*radius*(x - width/2.0)/l; c.y = 2*radius*(y - height/2.0)/l; return c; } void juliaSet(int width,int height,complex c,double radius,int n){ int x,y,i; complex z0,z1; for(x=0;x<=width;x++) for(y=0;y<=height;y++){ z0 = mapPoint(width,height,radius,x,y); for(i=1;i<=n;i++){ z1 = add(sqr(z0),c); if(mod(z1)>radius){ putpixel(x,y,i%15+1); break; } z0 = z1; } if(i>n) putpixel(x,y,0); } } int main(int argC, char* argV[]) { int width, height; complex c; if(argC != 7) printf("Usage : %s <width and height of screen, real and imaginary parts of c, limit radius and iterations>"); else{ width = atoi(argV[1]); height = atoi(argV[2]); c.x = atof(argV[3]); c.y = atof(argV[4]); initwindow(width,height,"Julia Set"); juliaSet(width,height,c,atof(argV[5]),atoi(argV[6])); getch(); } return 0; }
Jump anywhere
C
Imperative programs like to jump around, but some languages restrict these jumps. Many structured languages restrict their [[conditional structures]] and [[loops]] to ''local jumps'' within a function. Some assembly languages limit certain jumps or branches to a small range. This task is to demonstrate a local jump and a global jump and the various other types of jumps that the language supports. For the purpose of this task, the jumps need not be used for a single purpose and you have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]]. This task provides a "grab bag" for several types of jumps. There are ''non-local jumps'' across function calls, or ''long jumps'' to anywhere within a program. Anywhere means not only to the tops of functions! * Some languages can ''go to'' any global label in a program. * Some languages can break multiple function calls, also known as ''unwinding the call stack''. * Some languages can save a ''continuation''. The program can later continue from the same place. So you can jump anywhere, but only if you have a previous visit there (to save the continuation). These jumps are not all alike. A simple ''goto'' never touches the call stack. A continuation saves the call stack, so you can continue a function call after it ends. ;Task: Use your language to demonstrate the various types of jumps that it supports. Because the possibilities vary by language, this task is not specific. You have the freedom to use these jumps for different purposes. You may also defer to more specific tasks, like [[Exceptions]] or [[Generator]].
char *str; int *array; FILE *fp; str = (char *) malloc(100); if(str == NULL) goto: exit; fp=fopen("c:\\test.csv", "r"); if(fp== NULL) goto: clean_up_str; array = (int *) malloc(15); if(array==NULL) goto: clean_up_file; ...// read in the csv file and convert to integers clean_up_array: free(array); clean_up_file: fclose(fp); clean_up_str: free(str ); exit: return;
K-d tree
C
{{wikipedia|K-d tree}} A k-d tree (short for ''k''-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is ''k'', the number of points in the data, ''N'', should be ''N'' 2''k''. Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead. '''Task:''' Construct a k-d tree and perform a nearest neighbor search for two example data sets: # The Wikipedia example data of [(2,3), (5,4), (9,6), (4,7), (8,1), (7,2)]. # 1000 3-d points uniformly distributed in a 3-d cube. For the Wikipedia example, find the nearest neighbor to point (9, 2) For the random data, pick a random location and find the nearest neighbor. In addition, instrument your code to count the number of nodes visited in the nearest neighbor search. Count a node as visited if any field of it is accessed. Output should show the point searched for, the point found, the distance to the point, and the number of nodes visited. There are variant algorithms for constructing the tree. You can use a simple median strategy or implement something more efficient. Variants of the nearest neighbor search include nearest N neighbors, approximate nearest neighbor, and range searches. You do not have to implement these. The requirement for this task is specifically the nearest single neighbor. Also there are algorithms for inserting, deleting, and balancing k-d trees. These are also not required for the task.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <time.h> #define MAX_DIM 3 struct kd_node_t{ double x[MAX_DIM]; struct kd_node_t *left, *right; }; inline double dist(struct kd_node_t *a, struct kd_node_t *b, int dim) { double t, d = 0; while (dim--) { t = a->x[dim] - b->x[dim]; d += t * t; } return d; } inline void swap(struct kd_node_t *x, struct kd_node_t *y) { double tmp[MAX_DIM]; memcpy(tmp, x->x, sizeof(tmp)); memcpy(x->x, y->x, sizeof(tmp)); memcpy(y->x, tmp, sizeof(tmp)); } /* see quickselect method */ struct kd_node_t* find_median(struct kd_node_t *start, struct kd_node_t *end, int idx) { if (end <= start) return NULL; if (end == start + 1) return start; struct kd_node_t *p, *store, *md = start + (end - start) / 2; double pivot; while (1) { pivot = md->x[idx]; swap(md, end - 1); for (store = p = start; p < end; p++) { if (p->x[idx] < pivot) { if (p != store) swap(p, store); store++; } } swap(store, end - 1); /* median has duplicate values */ if (store->x[idx] == md->x[idx]) return md; if (store > md) end = store; else start = store; } } struct kd_node_t* make_tree(struct kd_node_t *t, int len, int i, int dim) { struct kd_node_t *n; if (!len) return 0; if ((n = find_median(t, t + len, i))) { i = (i + 1) % dim; n->left = make_tree(t, n - t, i, dim); n->right = make_tree(n + 1, t + len - (n + 1), i, dim); } return n; } /* global variable, so sue me */ int visited; void nearest(struct kd_node_t *root, struct kd_node_t *nd, int i, int dim, struct kd_node_t **best, double *best_dist) { double d, dx, dx2; if (!root) return; d = dist(root, nd, dim); dx = root->x[i] - nd->x[i]; dx2 = dx * dx; visited ++; if (!*best || d < *best_dist) { *best_dist = d; *best = root; } /* if chance of exact match is high */ if (!*best_dist) return; if (++i >= dim) i = 0; nearest(dx > 0 ? root->left : root->right, nd, i, dim, best, best_dist); if (dx2 >= *best_dist) return; nearest(dx > 0 ? root->right : root->left, nd, i, dim, best, best_dist); } #define N 1000000 #define rand1() (rand() / (double)RAND_MAX) #define rand_pt(v) { v.x[0] = rand1(); v.x[1] = rand1(); v.x[2] = rand1(); } int main(void) { int i; struct kd_node_t wp[] = { {{2, 3}}, {{5, 4}}, {{9, 6}}, {{4, 7}}, {{8, 1}}, {{7, 2}} }; struct kd_node_t testNode = {{9, 2}}; struct kd_node_t *root, *found, *million; double best_dist; root = make_tree(wp, sizeof(wp) / sizeof(wp[1]), 0, 2); visited = 0; found = 0; nearest(root, &testNode, 0, 2, &found, &best_dist); printf(">> WP tree\nsearching for (%g, %g)\n" "found (%g, %g) dist %g\nseen %d nodes\n\n", testNode.x[0], testNode.x[1], found->x[0], found->x[1], sqrt(best_dist), visited); million =(struct kd_node_t*) calloc(N, sizeof(struct kd_node_t)); srand(time(0)); for (i = 0; i < N; i++) rand_pt(million[i]); root = make_tree(million, N, 0, 3); rand_pt(testNode); visited = 0; found = 0; nearest(root, &testNode, 0, 3, &found, &best_dist); printf(">> Million tree\nsearching for (%g, %g, %g)\n" "found (%g, %g, %g) dist %g\nseen %d nodes\n", testNode.x[0], testNode.x[1], testNode.x[2], found->x[0], found->x[1], found->x[2], sqrt(best_dist), visited); /* search many random points in million tree to see average behavior. tree size vs avg nodes visited: 10 ~ 7 100 ~ 16.5 1000 ~ 25.5 10000 ~ 32.8 100000 ~ 38.3 1000000 ~ 42.6 10000000 ~ 46.7 */ int sum = 0, test_runs = 100000; for (i = 0; i < test_runs; i++) { found = 0; visited = 0; rand_pt(testNode); nearest(root, &testNode, 0, 3, &found, &best_dist); sum += visited; } printf("\n>> Million tree\n" "visited %d nodes for %d random findings (%f per lookup)\n", sum, test_runs, sum/(double)test_runs); // free(million); return 0; }
Kaprekar numbers
C
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
#include <stdio.h> #include <stdint.h> typedef uint64_t ulong; int kaprekar(ulong n, int base) { ulong nn = n * n, r, tens = 1; if ((nn - n) % (base - 1)) return 0; while (tens < n) tens *= base; if (n == tens) return 1 == n; while ((r = nn % tens) < n) { if (nn / tens + r == n) return tens; tens *= base; } return 0; } void print_num(ulong n, int base) { ulong q, div = base; while (div < n) div *= base; while (n && (div /= base)) { q = n / div; if (q < 10) putchar(q + '0'); else putchar(q + 'a' - 10); n -= q * div; } } int main() { ulong i, tens; int cnt = 0; int base = 10; printf("base 10:\n"); for (i = 1; i < 1000000; i++) if (kaprekar(i, base)) printf("%3d: %llu\n", ++cnt, i); base = 17; printf("\nbase %d:\n 1: 1\n", base); for (i = 2, cnt = 1; i < 1000000; i++) if ((tens = kaprekar(i, base))) { printf("%3d: %llu", ++cnt, i); printf(" \t"); print_num(i, base); printf("\t"); print_num(i * i, base); printf("\t"); print_num(i * i / tens, base); printf(" + "); print_num(i * i % tens, base); printf("\n"); } return 0; }
Kernighans large earthquake problem
C
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { FILE *fp; char *line = NULL; size_t len = 0; ssize_t read; char *lw, *lt; fp = fopen("data.txt", "r"); if (fp == NULL) { printf("Unable to open file\n"); exit(1); } printf("Those earthquakes with a magnitude > 6.0 are:\n\n"); while ((read = getline(&line, &len, fp)) != EOF) { if (read < 2) continue; /* ignore blank lines */ lw = strrchr(line, ' '); /* look for last space */ lt = strrchr(line, '\t'); /* look for last tab */ if (!lw && !lt) continue; /* ignore lines with no whitespace */ if (lt > lw) lw = lt; /* lw points to last space or tab */ if (atof(lw + 1) > 6.0) printf("%s", line); } fclose(fp); if (line) free(line); return 0; }
Keyboard input/Obtain a Y or N response
C
Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> void set_mode(int want_key) { static struct termios old, new; if (!want_key) { tcsetattr(STDIN_FILENO, TCSANOW, &old); return; } tcgetattr(STDIN_FILENO, &old); new = old; new.c_lflag &= ~(ICANON); tcsetattr(STDIN_FILENO, TCSANOW, &new); } int get_key(int no_timeout) { int c = 0; struct timeval tv; fd_set fs; tv.tv_usec = tv.tv_sec = 0; FD_ZERO(&fs); FD_SET(STDIN_FILENO, &fs); select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv); if (FD_ISSET(STDIN_FILENO, &fs)) { c = getchar(); set_mode(0); } return c; } int main() { int c; while(1) { set_mode(1); while (get_key(0)); /* clear buffer */ printf("Prompt again [Y/N]? "); fflush(stdout); c = get_key(1); if (c == 'Y' || c == 'y') { printf("\n"); continue; } if (c == 'N' || c == 'n') { printf("\nDone\n"); break; } printf("\nYes or no?\n"); } return 0; }
Knight's tour
C
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> typedef unsigned char cell; int dx[] = { -2, -2, -1, 1, 2, 2, 1, -1 }; int dy[] = { -1, 1, 2, 2, 1, -1, -2, -2 }; void init_board(int w, int h, cell **a, cell **b) { int i, j, k, x, y, p = w + 4, q = h + 4; /* b is board; a is board with 2 rows padded at each side */ a[0] = (cell*)(a + q); b[0] = a[0] + 2; for (i = 1; i < q; i++) { a[i] = a[i-1] + p; b[i] = a[i] + 2; } memset(a[0], 255, p * q); for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { for (k = 0; k < 8; k++) { x = j + dx[k], y = i + dy[k]; if (b[i+2][j] == 255) b[i+2][j] = 0; b[i+2][j] += x >= 0 && x < w && y >= 0 && y < h; } } } } #define E "\033[" int walk_board(int w, int h, int x, int y, cell **b) { int i, nx, ny, least; int steps = 0; printf(E"H"E"J"E"%d;%dH"E"32m[]"E"m", y + 1, 1 + 2 * x); while (1) { /* occupy cell */ b[y][x] = 255; /* reduce all neighbors' neighbor count */ for (i = 0; i < 8; i++) b[ y + dy[i] ][ x + dx[i] ]--; /* find neighbor with lowest neighbor count */ least = 255; for (i = 0; i < 8; i++) { if (b[ y + dy[i] ][ x + dx[i] ] < least) { nx = x + dx[i]; ny = y + dy[i]; least = b[ny][nx]; } } if (least > 7) { printf(E"%dH", h + 2); return steps == w * h - 1; } if (steps++) printf(E"%d;%dH[]", y + 1, 1 + 2 * x); x = nx, y = ny; printf(E"%d;%dH"E"31m[]"E"m", y + 1, 1 + 2 * x); fflush(stdout); usleep(120000); } } int solve(int w, int h) { int x = 0, y = 0; cell **a, **b; a = malloc((w + 4) * (h + 4) + sizeof(cell*) * (h + 4)); b = malloc((h + 4) * sizeof(cell*)); while (1) { init_board(w, h, a, b); if (walk_board(w, h, x, y, b + 2)) { printf("Success!\n"); return 1; } if (++x >= w) x = 0, y++; if (y >= h) { printf("Failed to find a solution\n"); return 0; } printf("Any key to try next start position"); getchar(); } } int main(int c, char **v) { int w, h; if (c < 2 || (w = atoi(v[1])) <= 0) w = 8; if (c < 3 || (h = atoi(v[2])) <= 0) h = w; solve(w, h); return 0; }
Knuth's algorithm S
C
This is a method of randomly sampling n items from a set of M items, with equal probability; where M >= n and M, the number of items is unknown until the end. This means that the equal probability sampling should be maintained for all successive items > n as they become available (although the content of successive samples can change). ;The algorithm: :* Select the first n items as the sample as they become available; :* For the i-th item where i > n, have a random chance of n/i of keeping it. If failing this chance, the sample remains the same. If not, have it randomly (1/n) replace one of the previously selected n items of the sample. :* Repeat 2nd step for any subsequent items. ;The Task: :* Create a function s_of_n_creator that given n the maximum sample size, returns a function s_of_n that takes one parameter, item. :* Function s_of_n when called with successive items returns an equi-weighted random sample of up to n of its items so far, each time it is called, calculated using Knuths Algorithm S. :* Test your functions by printing and showing the frequency of occurrences of the selected digits from 100,000 repetitions of: :::# Use the s_of_n_creator with n == 3 to generate an s_of_n. :::# call s_of_n with each of the digits 0 to 9 in order, keeping the returned three digits of its random sampling from its last call with argument item=9. Note: A class taking n and generating a callable instance/function might also be used. ;Reference: * The Art of Computer Programming, Vol 2, 3.4.2 p.142 ;Related tasks: * [[One of n lines in a file]] * [[Accumulator factory]]
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> struct s_env { unsigned int n, i; size_t size; void *sample; }; void s_of_n_init(struct s_env *s_env, size_t size, unsigned int n) { s_env->i = 0; s_env->n = n; s_env->size = size; s_env->sample = malloc(n * size); } void sample_set_i(struct s_env *s_env, unsigned int i, void *item) { memcpy(s_env->sample + i * s_env->size, item, s_env->size); } void *s_of_n(struct s_env *s_env, void *item) { s_env->i++; if (s_env->i <= s_env->n) sample_set_i(s_env, s_env->i - 1, item); else if ((rand() % s_env->i) < s_env->n) sample_set_i(s_env, rand() % s_env->n, item); return s_env->sample; } int *test(unsigned int n, int *items_set, unsigned int num_items) { int i; struct s_env s_env; s_of_n_init(&s_env, sizeof(items_set[0]), n); for (i = 0; i < num_items; i++) { s_of_n(&s_env, (void *) &items_set[i]); } return (int *)s_env.sample; } int main() { unsigned int i, j; unsigned int n = 3; unsigned int num_items = 10; unsigned int *frequencies; int *items_set; srand(time(NULL)); items_set = malloc(num_items * sizeof(int)); frequencies = malloc(num_items * sizeof(int)); for (i = 0; i < num_items; i++) { items_set[i] = i; frequencies[i] = 0; } for (i = 0; i < 100000; i++) { int *res = test(n, items_set, num_items); for (j = 0; j < n; j++) { frequencies[res[j]]++; } free(res); } for (i = 0; i < num_items; i++) { printf(" %d", frequencies[i]); } puts(""); return 0; }
Koch curve
C
Draw a Koch curve. See details: Koch curve
#include<graphics.h> #include<stdlib.h> #include<stdio.h> #include<math.h> #define pi M_PI typedef struct{ double x,y; }point; void kochCurve(point p1,point p2,int times){ point p3,p4,p5; double theta = pi/3; if(times>0){ p3 = (point){(2*p1.x+p2.x)/3,(2*p1.y+p2.y)/3}; p5 = (point){(2*p2.x+p1.x)/3,(2*p2.y+p1.y)/3}; p4 = (point){p3.x + (p5.x - p3.x)*cos(theta) + (p5.y - p3.y)*sin(theta),p3.y - (p5.x - p3.x)*sin(theta) + (p5.y - p3.y)*cos(theta)}; kochCurve(p1,p3,times-1); kochCurve(p3,p4,times-1); kochCurve(p4,p5,times-1); kochCurve(p5,p2,times-1); } else{ line(p1.x,p1.y,p2.x,p2.y); } } int main(int argC, char** argV) { int w,h,r; point p1,p2; if(argC!=4){ printf("Usage : %s <window width> <window height> <recursion level>",argV[0]); } else{ w = atoi(argV[1]); h = atoi(argV[2]); r = atoi(argV[3]); initwindow(w,h,"Koch Curve"); p1 = (point){10,h-10}; p2 = (point){w-10,h-10}; kochCurve(p1,p2,r); getch(); closegraph(); } return 0; }
Largest int from concatenated ints
C
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
#include <stdio.h> #include <stdlib.h> #include <string.h> int catcmp(const void *a, const void *b) { char ab[32], ba[32]; sprintf(ab, "%d%d", *(int*)a, *(int*)b); sprintf(ba, "%d%d", *(int*)b, *(int*)a); return strcmp(ba, ab); } void maxcat(int *a, int len) { int i; qsort(a, len, sizeof(int), catcmp); for (i = 0; i < len; i++) printf("%d", a[i]); putchar('\n'); } int main(void) { int x[] = {1, 34, 3, 98, 9, 76, 45, 4}; int y[] = {54, 546, 548, 60}; maxcat(x, sizeof(x)/sizeof(x[0])); maxcat(y, sizeof(y)/sizeof(y[0])); return 0; }
Largest number divisible by its digits
C
Find the largest base 10 integer whose digits are all different, and is evenly divisible by each of its individual digits. These numbers are also known as '''Lynch-Bell numbers''', numbers '''n''' such that the (base ten) digits are all different (and do not include zero) and '''n''' is divisible by each of its individual digits. ;Example: '''135''' is evenly divisible by '''1''', '''3''', and '''5'''. Note that the digit zero (0) can not be in the number as integer division by zero is undefined. The digits must all be unique so a base ten number will have at most '''9''' digits. Feel free to use analytics and clever algorithms to reduce the search space your example needs to visit, but it must do an actual search. (Don't just feed it the answer and verify it is correct.) ;Stretch goal: Do the same thing for hexadecimal. ;Related tasks: :* gapful numbers. :* palindromic gapful numbers. ;Also see: :* The OEIS sequence: A115569: Lynch-Bell numbers.
#include<stdio.h> int main() { int num = 9876432,diff[] = {4,2,2,2},i,j,k=0; char str[10]; start:snprintf(str,10,"%d",num); for(i=0;str[i+1]!=00;i++){ if(str[i]=='0'||str[i]=='5'||num%(str[i]-'0')!=0){ num -= diff[k]; k = (k+1)%4; goto start; } for(j=i+1;str[j]!=00;j++) if(str[i]==str[j]){ num -= diff[k]; k = (k+1)%4; goto start; } } printf("Number found : %d",num); return 0; }
Largest proper divisor of n
C
a(1) = 1; for n > 1, a(n) = '''largest''' proper divisor of n, where '''n < 101 '''.
#include <stdio.h> unsigned int lpd(unsigned int n) { if (n<=1) return 1; int i; for (i=n-1; i>0; i--) if (n%i == 0) return i; } int main() { int i; for (i=1; i<=100; i++) { printf("%3d", lpd(i)); if (i % 10 == 0) printf("\n"); } return 0; }
Last Friday of each month
C
Write a program or a script that returns the date of the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_fridays 2012 2012-01-27 2012-02-24 2012-03-30 2012-04-27 2012-05-25 2012-06-29 2012-07-27 2012-08-31 2012-09-28 2012-10-26 2012-11-30 2012-12-28 ;Related tasks * [[Five weekends]] * [[Day of the week]] * [[Find the last Sunday of each month]]
#include <stdio.h> #include <stdlib.h> int main(int c, char *v[]) { int days[] = {31,29,31,30,31,30,31,31,30,31,30,31}; int m, y, w; if (c < 2 || (y = atoi(v[1])) <= 1700) return 1; days[1] -= (y % 4) || (!(y % 100) && (y % 400)); w = y * 365 + (y - 1) / 4 - (y - 1) / 100 + (y - 1) / 400 + 6; for(m = 0; m < 12; m++) { w = (w + days[m]) % 7; printf("%d-%02d-%d\n", y, m + 1, days[m] + (w < 5 ? -2 : 5) - w); } return 0; }
Last letter-first letter
C
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game. For example, with "animals" as the category, Child 1: dog Child 2: goldfish Child 1: hippopotamus Child 2: snake ... ;Task: Take the following selection of 70 English Pokemon names (extracted from Wikipedia's list of Pokemon) and generate the/a sequence with the highest possible number of Pokemon names where the subsequent name starts with the final letter of the preceding name. No Pokemon name is to be repeated. audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor heatran ivysaur jellicent jumpluff kangaskhan kricketune landorus ledyba loudred lumineon lunatone machamp magnezone mamoswine nosepass petilil pidgeotto pikachu pinsir poliwrath poochyena porygon2 porygonz registeel relicanth remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask Extra brownie points for dealing with the full list of 646 names.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define forall(i, n) for (int i = 0; i < n; i++) typedef struct edge { char s, e, *str; struct edge *lnk; } edge; typedef struct { edge* e[26]; int nin, nout, in[26], out[26];} node; typedef struct { edge *e, *tail; int len, has[26]; } chain; node nodes[26]; edge *names, **tmp; int n_names; /* add edge to graph */ void store_edge(edge *g) { if (!g) return; int i = g->e, j = g->s; node *n = nodes + j; g->lnk = n->e[i]; n->e[i] = g, n->out[i]++, n->nout++; n = nodes + i, n->in[j]++, n->nin++; } /* unlink an edge between nodes i and j, and return the edge */ edge* remove_edge(int i, int j) { node *n = nodes + i; edge *g = n->e[j]; if (g) { n->e[j] = g->lnk; g->lnk = 0; n->out[j]--, n->nout--; n = nodes + j; n->in[i]--; n->nin--; } return g; } void read_names() { FILE *fp = fopen("poke646", "rt"); int i, len; char *buf; edge *p; if (!fp) abort(); fseek(fp, 0, SEEK_END); len = ftell(fp); buf = malloc(len + 1); fseek(fp, 0, SEEK_SET); fread(buf, 1, len, fp); fclose(fp); buf[len] = 0; for (n_names = i = 0; i < len; i++) if (isspace(buf[i])) buf[i] = 0, n_names++; if (buf[len-1]) n_names++; memset(nodes, 0, sizeof(node) * 26); tmp = calloc(n_names, sizeof(edge*)); p = names = malloc(sizeof(edge) * n_names); for (i = 0; i < n_names; i++, p++) { if (i) p->str = names[i-1].str + len + 1; else p->str = buf; len = strlen(p->str); p->s = p->str[0] - 'a'; p->e = p->str[len-1] - 'a'; if (p->s < 0 || p->s >= 26 || p->e < 0 || p->e >= 26) { printf("bad name %s: first/last char must be letter\n", p->str); abort(); } } printf("read %d names\n", n_names); } void show_chain(chain *c) { printf("%d:", c->len); for (edge * e = c->e; e || !putchar('\n'); e = e->lnk) printf(" %s", e->str); } /* Which next node has most enter or exit edges. */ int widest(int n, int out) { if (nodes[n].out[n]) return n; int mm = -1, mi = -1; forall(i, 26) { if (out) { if (nodes[n].out[i] && nodes[i].nout > mm) mi = i, mm = nodes[i].nout; } else { if (nodes[i].out[n] && nodes[i].nin > mm) mi = i, mm = nodes[i].nin; } } return mi; } void insert(chain *c, edge *e) { e->lnk = c->e; if (!c->tail) c->tail = e; c->e = e; c->len++; } void append(chain *c, edge *e) { if (c->tail) c->tail->lnk = e; else c->e = e; c->tail = e; c->len++; } edge * shift(chain *c) { edge *e = c->e; if (e) { c->e = e->lnk; if (!--c->len) c->tail = 0; } return e; } chain* make_chain(int s) { chain *c = calloc(1, sizeof(chain)); /* extend backwards */ for (int i, j = s; (i = widest(j, 0)) >= 0; j = i) insert(c, remove_edge(i, j)); /* extend forwards */ for (int i, j = s; (i = widest(j, 1)) >= 0; j = i) append(c, remove_edge(j, i)); for (int step = 0;; step++) { edge *e = c->e; for (int i = 0; i < step; i++) if (!(e = e->lnk)) break; if (!e) return c; int n = 0; for (int i, j = e->s; (i = widest(j, 0)) >= 0; j = i) { if (!(e = remove_edge(i, j))) break; tmp[n++] = e; } if (n > step) { forall(i, step) store_edge(shift(c)); forall(i, n) insert(c, tmp[i]); step = -1; } else while (--n >= 0) store_edge(tmp[n]); } return c; } int main(void) { int best = 0; read_names(); forall(i, 26) { /* rebuild the graph */ memset(nodes, 0, sizeof(nodes)); forall(j, n_names) store_edge(names + j); /* make a chain from node i */ chain *c = make_chain(i); if (c->len > best) { show_chain(c); best = c->len; } free(c); } printf("longest found: %d\n", best); return 0; }
Law of cosines - triples
C
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
/* * RossetaCode: Law of cosines - triples * * An quick and dirty brute force solutions with O(N^3) cost. * Anyway it is possible set MAX_SIDE_LENGTH equal to 10000 * and use fast computer to obtain the "extra credit" badge. * * Obviously, there are better algorithms. */ #include <stdio.h> #include <math.h> #define MAX_SIDE_LENGTH 13 //#define DISPLAY_TRIANGLES 1 int main(void) { static char description[3][80] = { "gamma = 90 degrees, a*a + b*b == c*c", "gamma = 60 degrees, a*a + b*b - a*b == c*c", "gamma = 120 degrees, a*a + b*b + a*b == c*c" }; static int coeff[3] = { 0, 1, -1 }; for (int k = 0; k < 3; k++) { int counter = 0; for (int a = 1; a <= MAX_SIDE_LENGTH; a++) for (int b = 1; b <= a; b++) for (int c = 1; c <= MAX_SIDE_LENGTH; c++) if (a * a + b * b - coeff[k] * a * b == c * c) { counter++; #ifdef DISPLAY_TRIANGLES printf(" %d %d %d\n", a, b, c); #endif } printf("%s, number of triangles = %d\n", description[k], counter); } return 0; }
Least common multiple
C
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
#include <stdio.h> int gcd(int m, int n) { int tmp; while(m) { tmp = m; m = n % m; n = tmp; } return n; } int lcm(int m, int n) { return m / gcd(m, n) * n; } int main() { printf("lcm(35, 21) = %d\n", lcm(21,35)); return 0; }
Levenshtein distance
C
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
#include <stdio.h> #include <string.h> /* s, t: two strings; ls, lt: their respective length */ int levenshtein(const char *s, int ls, const char *t, int lt) { int a, b, c; /* if either string is empty, difference is inserting all chars * from the other */ if (!ls) return lt; if (!lt) return ls; /* if last letters are the same, the difference is whatever is * required to edit the rest of the strings */ if (s[ls - 1] == t[lt - 1]) return levenshtein(s, ls - 1, t, lt - 1); /* else try: * changing last letter of s to that of t; or * remove last letter of s; or * remove last letter of t, * any of which is 1 edit plus editing the rest of the strings */ a = levenshtein(s, ls - 1, t, lt - 1); b = levenshtein(s, ls, t, lt - 1); c = levenshtein(s, ls - 1, t, lt ); if (a > b) a = b; if (a > c) a = c; return a + 1; } int main() { const char *s1 = "rosettacode"; const char *s2 = "raisethysword"; printf("distance between `%s' and `%s': %d\n", s1, s2, levenshtein(s1, strlen(s1), s2, strlen(s2))); return 0; }
Levenshtein distance/Alignment
C
The [[Levenshtein distance]] algorithm returns the number of atomic operations (insertion, deletion or edition) that must be performed on a string in order to obtain an other one, but it does not say anything about the actual operations used or their order. An alignment is a notation used to describe the operations used to turn a string into an other. At some point in the strings, the minus character ('-') is placed in order to signify that a character must be added at this very place. For instance, an alignment between the words 'place' and 'palace' is: P-LACE PALACE ;Task: Write a function that shows the alignment of two strings for the corresponding levenshtein distance. As an example, use the words "rosettacode" and "raisethysword". You can either implement an algorithm, or use a dedicated library (thus showing us how it is named in your language).
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct edit_s edit_t, *edit; struct edit_s { char c1, c2; int n; edit next; }; void leven(char *a, char *b) { int i, j, la = strlen(a), lb = strlen(b); edit *tbl = malloc(sizeof(edit) * (1 + la)); tbl[0] = calloc((1 + la) * (1 + lb), sizeof(edit_t)); for (i = 1; i <= la; i++) tbl[i] = tbl[i-1] + (1+lb); for (i = la; i >= 0; i--) { char *aa = a + i; for (j = lb; j >= 0; j--) { char *bb = b + j; if (!*aa && !*bb) continue; edit e = &tbl[i][j]; edit repl = &tbl[i+1][j+1]; edit dela = &tbl[i+1][j]; edit delb = &tbl[i][j+1]; e->c1 = *aa; e->c2 = *bb; if (!*aa) { e->next = delb; e->n = e->next->n + 1; continue; } if (!*bb) { e->next = dela; e->n = e->next->n + 1; continue; } e->next = repl; if (*aa == *bb) { e->n = e->next->n; continue; } if (e->next->n > delb->n) { e->next = delb; e->c1 = 0; } if (e->next->n > dela->n) { e->next = dela; e->c1 = *aa; e->c2 = 0; } e->n = e->next->n + 1; } } edit p = tbl[0]; printf("%s -> %s: %d edits\n", a, b, p->n); while (p->next) { if (p->c1 == p->c2) printf("%c", p->c1); else { putchar('('); if (p->c1) putchar(p->c1); putchar(','); if (p->c2) putchar(p->c2); putchar(')'); } p = p->next; } putchar('\n'); free(tbl[0]); free(tbl); } int main(void) { leven("raisethysword", "rosettacode"); return 0; }