/************************************************************
Write a function partlist that gives all the ways to divide a list (an array) of at least two elements into two non-empty parts.
Each two non empty parts will be in a pair (or an array for languages without tuples or a structin C - C: see Examples test Cases - )
Each part will be in a string
Elements of a pair must be in the same order as in the original array.
Example:
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[["az", "toto picaro zone kiwi"], ["az toto", "picaro zone kiwi"], ["az toto picaro", "zone kiwi"], ["az toto picaro zone", "kiwi"]]
or
a = {"az", "toto", "picaro", "zone", "kiwi"} -->
{{"az", "toto picaro zone kiwi"}, {"az toto", "picaro zone kiwi"}, {"az toto picaro", "zone kiwi"}, {"az toto picaro zone", "kiwi"}}
or
a = ["az", "toto", "picaro", "zone", "kiwi"] -->
[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
or
a = [|"az", "toto", "picaro", "zone", "kiwi"|] -->[("az", "toto picaro zone kiwi"), ("az toto", "picaro zone kiwi"), ("az toto picaro", "zone kiwi"), ("az toto picaro zone", "kiwi")]
*************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Pair Pair;
struct Pair {
char* first;
char* snd;
};
Pair** partlist(char** arr, int sz)
{
int i;
int j;
int k;
int count = 0;
//Pair *TmpPair = malloc(Pair *);
int size = 0;
Pair **out = (Pair**)malloc(sizeof(Pair*) * (sz-1));
for(i=0; i<sz; i++)
{
size += strlen(arr[i]) + 1;
}
//size += 1;
for(i=0; i<sz-1; i++)
{
out[i] = malloc(sizeof(Pair));
out[i]->first = malloc(size);
out[i]->snd = malloc(size);
/*first*/
count = 0;
for(j=0; j<=i; j++)
{
memcpy(out[i]->first + count, arr[j], strlen(arr[j]));
count += strlen(arr[j]);
out[i]->first[count] = ' ';
count ++;
}
out[i]->first[count-1] = '\0';
/*second*/
count = 0;
for( ; j<sz; j++)
{
memcpy(out[i]->snd + count, arr[j], strlen(arr[j]));
count += strlen(arr[j]);
out[i]->snd[count] = ' ';
count ++;
}
out[i]->snd[count-1] = '\0';
}
return out;
}
void dotest(char** arr, int sz, char *expr) {
Pair** act = partlist(arr, sz);
char* sact = array2StringData(act, sz - 1);
if(strcmp(sact, expr) != 0)
printf("partList. Error. Expected \n%s\n but got \n%s\n", expr, sact);
cr_assert_str_eq(sact, expr, "");
free(sact); sact = NULL;
}
Test(partList, ShouldPassAllTheTestsProvided) {
{
char* s[4] = {"cdIw", "tzIy", "xDu", "rThG"};
char* sol = "{{cdIw, tzIy xDu rThG}{cdIw tzIy, xDu rThG}{cdIw tzIy xDu, rThG}}";
dotest(s, 4, sol);
}
{
char* s[5] = {"I", "wish", "I", "hadn't", "come"};
char* sol = "{{I, wish I hadn't come}{I wish, I hadn't come}{I wish I, hadn't come}{I wish I hadn't, come}}";
dotest(s, 5, sol);
}
{
char* s[4] = {"vJQ", "anj", "mQDq", "sOZ"};
char* sol = "{{vJQ, anj mQDq sOZ}{vJQ anj, mQDq sOZ}{vJQ anj mQDq, sOZ}}";
dotest(s, 4, sol);
}
}