Skip to content

Instantly share code, notes, and snippets.

@SirAeroWN
Last active January 22, 2019 21:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SirAeroWN/0919f288f5e5f4dc79f8190f36216734 to your computer and use it in GitHub Desktop.
Save SirAeroWN/0919f288f5e5f4dc79f8190f36216734 to your computer and use it in GitHub Desktop.
Solution to Cassido's interview question on Jan. 22, 2019 in C
/* Try It Online (TIO): https://bit.ly/2T9P9nq */
#include <stdio.h>
/*
step through the two character arrays, comparing character for character
when x is looped through, reset its position and increment the counter
when y is looped through, break the loop
before returning the counter, make sure that the loop finished both arrays, otherwise set the counter to -1
*/
int repeat(char** x, char** y) {
int i = 0;
int j = 0;
int c = 0;
while ((*y)[j] != '\0') {
if ((*x)[i] == '\0') {
i = 0;
}
if ((*x)[i] != (*y)[j]) {
break;
}
j++;
i++;
c += ((*x)[i] == '\0') ? 1 : 0;
}
/* check to make sure both pointers are at the end of their strings */
c = ((*x)[i] == '\0' && (*y)[j] == '\0') ? c : -1;
return c;
}
/*
Expected output:
'pi', 'pipipi': 3
'wah', 'waluigi': -1
*/
int main() {
char* a = "pi";
char* b = "pipipi";
printf("'%s', '%s': %d\n", a, b, repeat(&a, &b));
char* c = "wah";
char* d = "waluigi";
printf("'%s', '%s': %d\n", c, d, repeat(&c, &d));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment