Handout #37 CS106A 2002 Dec.30,2002 Alex Khomenko Practice Final Solutions Problem 1:Strings. static char curptr NULL; /global state variable * char *strtok(char *str,char delim) int i; if(str =NULL)str curPtr; if(strcmp(str,"")==0)return (NULL); for(i=0;i<strlen(str);i++) { if(str[i]=delim) { str[i]=\0'; curptr str +i 1; return(str); curptr "" return(str); Problem 2:Arrays (a) void MakeHistogram(int pict[SIZE][SIZE],int hist [N_COLORS]) { int i,ji for (i=0;i<N COLORS;i++) hist[i]0; for (i 0;i SIZE;i++) for (j=0;j<SIZE;j++) hist[pict[i][j]]++; for (i=0;i<N COLORS;i++) printf("&d",hist[i]); printf("\n"); } (b) for (i =0;i<N PICTS;i++) MakeHistogram(knownData[i],histograms [i]);
Handout #37 2002 Dec. 30, 2002 Alex Khomenko Practice Final Solutions Problem 1: Strings. static char curPtr = NULL; /* global state variable */ char *strtok(char *str, char delim) { int i; if(str == NULL) str = curPtr; if(strcmp(str, "") == 0) return(NULL); for(i = 0; i < strlen(str); i++) { if(str[i] == delim) { str[i] = '\0'; curPtr = str + i + 1; return(str); } } curPtr = ""; return(str); } Problem 2: Arrays (a) void MakeHistogram(int pict[SIZE][SIZE], int hist[N_COLORS]) { int i, j; for (i = 0; i < N_COLORS; i++) hist[i] = 0; for (i = 0; i < SIZE; i++) for (j = 0; j < SIZE; j++) hist[pict[i][j]]++; for (i = 0; i < N_COLORS; i++) printf(" %d", hist[i]); printf("\n"); } (b) for (i = 0; i < N_PICTS; i++) { MakeHistogram(knownData[i], histograms[i]); CS106A
2 }
2 }
3 (c) int BestMatch(int unknown [SIZE][SIZE],int histograms [N_PICTS][N_COLORS]) int score [N_PICTS],hist [N_COLORS]; int i,best 0; MakeHistogram(unknown,hist); for (i =0;i<N_PICTS;i++) score [i]Compare(histograms [i],hist); for (i 1;i N PICTS;i++) if (score[i]score[best]) best =i; return best; int Compare(int h1[N_COLORS],int h2[N_COLORS]) int score 0,i; for (i=0;i<N COLORS;i++) score +abs(h1[i]-h2[i]); return score;
3 (c) int BestMatch(int unknown[SIZE][SIZE], int histograms[N_PICTS][N_COLORS]) { int score[N_PICTS], hist[N_COLORS]; int i, best = 0; MakeHistogram(unknown, hist); for (i = 0; i < N_PICTS; i++) score[i] = Compare(histograms[i], hist); for (i = 1; i < N_PICTS; i++) if (score[i] < score[best]) best = i; return best; } int Compare(int h1[N_COLORS], int h2[N_COLORS]) { int score = 0, i; for (i = 0; i < N_COLORS; i++) score += abs(h1[i] - h2[i]); return score; }
4 Problem 3:Function trace STACK HEAP main e' 6 mika schuey n '1 david mika schuey mika schuey mika 1' schuey mika schuey mika schuey Rubens jean jos 6 hello\0 johnny there\0 6 howyalldoin?\0 Orphaned! Ouch\0 Ralf eddie heinz marc pedro
4 Problem 3: Function trace STACK HEAP n david main mika schuey mika schuey mika schuey mika schuey mika schuey mika schuey jean jos Rubens johnny i eddie heinz Ralf marc pedro 6 6 hello\0 there\0 6 howyalldoin?\0 'e' 'l' 'l' Ouch\0 Orphaned!
5
5