Cod sursa(job #2324545)

Utilizator AxellApostolescu Alexandru Axell Data 20 ianuarie 2019 23:14:10
Problema Potrivirea sirurilor Scor 26
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGHT 2000000

void apparitions(char *a, char *b, FILE* out);

int main() {
	FILE* in = fopen("strmatch.in", "rt");
	if (in == NULL) {
		printf("Couldn`t open input file!\n");
		return -1;
	}
	FILE* out = fopen("strmatch.out", "wt");
	if (out == NULL) {
		printf("Couldn`t open output file!\n");
		return -2;
	}
	char *a = malloc(LENGHT * sizeof(char));
	char *b = malloc(LENGHT * sizeof(char));
	fgets(a, LENGHT - 1, in);
	char *pos;
	if ((pos=strchr(a, '\n')) != NULL) {
		*pos = '\0';
	}
	if ((pos=strchr(b, '\n')) != NULL) {
		*pos = '\0';
	}
	fgets(b, LENGHT - 1, in);
	apparitions(a, b, out);

	// Close / free
	free(a);
	free(b);
	fclose(in);
	fclose(out);
	return 0;
}

void apparitions(char *a, char *b, FILE* out) {
	int ct = 0, yes = 0;
	int *occur = malloc(10 * sizeof(int));
	if (strlen(a) > strlen(b)) {
		return;
	}
	for (int i = 0 ; i < (int)strlen(b) ; ++i) {
		for (int j = 0 ; j < (int)strlen(a) ; ++j) {
			if (a[j] == b[i + j]) {
				yes++;
			}
		}
		if (yes == (int)strlen(a)) {
			occur[ct] = i;
			ct++;
		}
		if (ct % 10 == 0) {
			occur = realloc(occur, (ct + 10) * sizeof(int));
		} 
		yes = 0;
	}
	fprintf(out, "%d\n", ct);
	for (int i = 0 ; i < ct ; ++i) {
		fprintf(out, "%d ", occur[i]);
	}
	free(occur);
}