#include <stdio.h>
#include <string.h>
long set_bit(long bm, int i)
{
return (bm | (1 << i));
}
long clear_bit(long bm, int i)
{
return (bm & ~(1 << i));
}
int is_bit_set(long bm, int i)
{
return (bm & (1 << i)) != 0;
}
void char_combo_internal(long bm, int offset, int length, char *str)
{
int i;
//printf("\nDEBUG: *");
if (offset >= length)
{
str[offset] = '\0';
printf(" %s\n", str);
return;
}
for (i = 0; i < length; i++)
{
if (is_bit_set(bm, i)) continue;
bm = set_bit(bm, i);
str[offset] = 'a' + i;
str[offset+1] = '\0';
//printf("\nDEBUG: %s", str);
char_combo_internal(bm, offset+1, length, str);
bm = clear_bit(bm, i);
}
return;
}
void char_combo(int length)
{
if (length <=0) return;
char *str = (char *) malloc(sizeof(char) * (length + 1));
long bm = 0;
char_combo_internal(bm, 0, length, str);
free(str);
}
int main()
{
printf("\nCombinations (1) : \n");
char_combo(1);
printf("\nCombinations (2) : \n");
char_combo(2);
printf("\nCombinations (2) : \n");
char_combo(4);
}