Computer Science & C Programming


C Programming

As a more concrete application, the following program takes a list of integers and randomly suppress an element until the list is empty:

#define MAXI 9

GList* create() {
  GList* list = NULL;
  // Init
  for (gint i=0; i<MAXI; i++)
    list = g_list_append(list,GINT_TO_POINTER(i));
  return list;
}

void display(GList* list) {
  for (GList* it=list; it!=NULL; it=it->next)
    g_print("%i",it->data);
  g_print("\n");
}

gint32 select1(GList* list) {
  int size = g_list_length(list);
  GRand* generator = g_rand_new();
  return g_rand_int_range(generator,0,size-1);
}

void main() {
  GList* list = create();
  display(list);
  GList* clone= g_list_copy(list);
  while (g_list_length(clone)>1) {
    int pos = select1(clone);
    gpointer val = g_list_nth_data(clone,pos);
    clone = g_list_remove(clone,val);
    display(clone);
  }
}

As an exercise/alternative, how to get ALL the possible combinaison ?