Created
January 18, 2019 10:44
-
-
Save tvallois/abb449f7e57fe60b424cf01ba705e863 to your computer and use it in GitHub Desktop.
my_level_in_c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <assert.h> | |
#include <limits.h> | |
#include <math.h> | |
#include <stdbool.h> | |
#include <stddef.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
typedef struct CounterValue | |
{ | |
char* key; | |
int value; | |
} CounterValue; | |
typedef struct Counter | |
{ | |
int len; | |
int cap; | |
CounterValue *values; | |
} Counter; | |
Counter initCounter() { | |
struct Counter first; | |
first.len = 0; | |
first.cap = 10; | |
first.values = malloc(10 * sizeof(CounterValue)); | |
return first; | |
} | |
bool checkExistingKey(Counter* counter, char* key) { | |
for (int i = 0; i < counter->len; i++) { | |
if (strcmp(counter->values[i].key, key) == 0) { | |
counter->values[i].value++; | |
return true; | |
} | |
} | |
return false; | |
} | |
void incrementCounter(Counter* counter, char* key) { | |
bool existing_key = checkExistingKey(counter, key); | |
if (!existing_key){ | |
if (counter->len == counter->cap) { | |
counter->cap *= 2; | |
counter->values = realloc(counter->values, counter->cap * sizeof(CounterValue)); | |
} | |
counter->values[counter->len].key = strdup(key); | |
counter->values[counter->len].value = 1; | |
counter->len++; | |
} | |
} | |
void freeCounter(Counter* counter) { | |
for (int i = 0; i < counter->len; i++) { | |
free(counter->values[i].key); | |
} | |
free(counter->values); | |
} | |
long repeatedString(char* s, long n) { | |
char newWord[n + 1]; | |
for (int i = 0 ; i < n ; i++) { | |
size_t j = i % strlen(s); | |
newWord[i] = s[j]; | |
newWord[i+1] = '\0'; | |
} | |
Counter counter = initCounter(); | |
incrementCounter(&counter, "a"); | |
incrementCounter(&counter, "b"); | |
incrementCounter(&counter, "c"); | |
incrementCounter(&counter, "d"); | |
incrementCounter(&counter, "e"); | |
incrementCounter(&counter, "f"); | |
incrementCounter(&counter, "g"); | |
incrementCounter(&counter, "h"); | |
incrementCounter(&counter, "i"); | |
incrementCounter(&counter, "j"); | |
incrementCounter(&counter, "k"); | |
incrementCounter(&counter, "l"); | |
incrementCounter(&counter, "n"); | |
incrementCounter(&counter, "o"); | |
printf("%d", counter.values[0].value); | |
freeCounter(&counter); | |
printf("%s\n", newWord); | |
return 0; | |
} | |
int main(int argc, char const *argv[]) { | |
long size = 10; | |
char word[] = "aba"; | |
long result = repeatedString(word, size); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment