Fondamenti di Programmazione a.a. 2011-2012
Soluzioni prova scritta - 24 febbraio 2012
int abs(int x) { return (x > 0 ? x : -x); }
int smooth(int S[], int n, int k) {
int max = 0;
for (int i = 0 ; i < n ; i++) {
for (int j = i ; j < n ; j++) {
if (j - i + 1 > max) {
int h = i;
while (h < j && abs(S[h] - S[h + 1]) <= k)
h++;
if (h == j) max = j - i + 1;
}
}
}
return max;
}
int lcs(char *s1, char *s2, int *start1, int *start2) {
int max = 0;
for (int i = 0 ; s1[i] != '\0' ; i++)
for (int j = 0 ; s2[j] != '\0' ; j++) {
int k = 0;
while (s1[i + k] != '\0' && s1[i + k] == s2[j + k])
k++;
if (k > max) {
max = k;
*start1 = i;
*start2 = j;
}
}
return max;
}
#include <stdlib.h>
#include <string.h>
char *comstr(char **sA1, char **sA2, int n) {
char *com = NULL;
int len = 0;
for (int i = 0 ; i < n ; i++)
for (int j = 0 ; j < n ; j++) {
if (strcmp(sA1[i], sA2[j]) == 0) {
int sep = (com == NULL ? 0 : 1);
com = realloc(com, len + sep + strlen(sA1[i]) + 1);
if (sep == 1) {
com[len] = ';';
com[len + 1] = '\0';
}
strcat(com, sA1[i]);
len += sep + strlen(sA1[i]);
break;
}
}
return com;
}
#include <stdlib.h>
PList rect(PList L, int x1, int y1, int x2, int y2, PList *out) {
PList *pp = &L;
if (out != NULL) *out = NULL;
while (*pp != NULL) {
Point *p = *pp;
int x = p->x, y = p->y;
if (x < x1 || x > x2 || y < y1 || y > y2) {
*pp = p->next;
if (out != NULL) {
p->next = *out;
*out = p;
} else
free(p);
} else
pp = &((*pp)->next);
}
return L;
}
#include <stdio.h>
#include <string.h>
int mfirst(char *fname) {
FILE *f = fopen(fname, "r+b");
if (f == NULL)
return -1;
Rec r, rr;
int count = 0, index = 0;
while (fread(&r, sizeof(Rec), 1, f) == 1) {
rewind(f);
int isfirst = 1;
for (int i = 0 ; i < index && isfirst ; i++) {
fread(&rr, sizeof(Rec), 1, f);
if (strcmp(rr.spec, r.spec) == 0)
isfirst = 0;
}
r.first = isfirst;
if (isfirst) count++;
fseek(f, index*sizeof(Rec), SEEK_SET);
fwrite(&r, sizeof(Rec), 1, f);
fflush(f);
index++;
}
fclose(f);
return count;
}
#include <stdlib.h>
List clist(List C) {
if (C == NULL || C->next == C)
return C;
int max = 0;
Elem *p = C, *pmax = NULL;
do {
Elem *e = p;
int len = 1;
while (e->count == (e->next)->count && e->next != p) {
len++;
e = e->next;
}
if (len > max) {
max = len;
pmax = p;
}
p = p->next;
} while (p != C);
if (max >= 2) {
pmax->count = max*(pmax->count);
for (int i = 1 ; i < max ; i++) {
p = pmax->next;
pmax->next = p->next;
free(p);
}
}
return pmax;
}