1
1
mirror of https://github.com/theoludwig/programming-challenges.git synced 2025-05-13 23:22:49 +02:00

feat(solutions): add a-phone-code/c/function

This commit is contained in:
Théo LUDWIG 2025-05-13 23:11:55 +02:00
parent 070ac30ec3
commit 773f381f9f
Signed by: theoludwig
GPG Key ID: ADFE5A563D718F3B
6 changed files with 96 additions and 0 deletions

View File

@ -0,0 +1,3 @@
# a-phone-code/c/function
Created by [@theoludwig](https://github.com/theoludwig) on 13 May 2025.

View File

@ -0,0 +1,7 @@
#include "character.h"
void character_append(char* string, char character) {
size_t length = strlen(string);
string[length] = character;
string[length + 1] = '\0';
}

View File

@ -0,0 +1,16 @@
#ifndef __CHARACTER__
#define __CHARACTER__
#include <stdlib.h>
#include <string.h>
/**
* @brief Append a character to a string, assuming string points to an array
* with enough space.
*
* @param string
* @param character
*/
void character_append(char* string, char character);
#endif

View File

@ -0,0 +1,14 @@
#include "input.h"
char* input() {
char character;
size_t length = 1;
char* string = malloc(length * sizeof(char));
*string = '\0';
while ((character = getchar()) != '\n' && character != EOF) {
length++;
string = realloc(string, length * sizeof(char));
character_append(string, character);
}
return string;
}

View File

@ -0,0 +1,16 @@
#ifndef __INPUT__
#define __INPUT__
#include <stdio.h>
#include <stdlib.h>
#include "character.h"
/**
* @brief Read a line from stdin.
*
* @return char*
*/
char* input();
#endif

View File

@ -0,0 +1,40 @@
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "input.h"
int main() {
size_t count = (size_t)atoi(input());
size_t prefix_length = 0;
char* last = NULL;
for (size_t i = 1; i < count; i++) {
if (last == NULL) {
last = input();
}
char* current = input();
size_t prefix_current_length = 0;
for (size_t j = 0; j < strlen(current); j++) {
if (current[j] == last[j]) {
prefix_current_length += 1;
} else {
break;
}
}
if (prefix_length > prefix_current_length) {
prefix_length = prefix_current_length;
} else if (prefix_length == 0) {
prefix_length = prefix_current_length;
}
last = current;
}
printf("%ld\n", prefix_length);
return EXIT_SUCCESS;
}