115 lines
2.4 KiB
C
115 lines
2.4 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <malloc.h>
|
|
#include "lceb.h"
|
|
|
|
static char **combs;
|
|
static int ncombs=0;
|
|
|
|
void print_comb(n)
|
|
int n;
|
|
{
|
|
printf("comb %d/%d=[%s]\n", n, ncombs, combs[n]);
|
|
}
|
|
void print_combs()
|
|
{
|
|
int i;
|
|
printf("op combs: ");
|
|
for (i=0; i<ncombs; ++i)
|
|
printf("%s ", combs[i]);
|
|
putchar('\n');
|
|
}
|
|
static unsigned n_combine(nops, len)
|
|
int nops, len;
|
|
{
|
|
int result = 1;
|
|
while(len > 0){
|
|
if(len & 1)
|
|
result *= nops;
|
|
nops *= nops;
|
|
len >>=1;
|
|
}
|
|
return result;
|
|
}
|
|
|
|
static char *combine(ops, len, n)
|
|
char *ops; /* string to combine */
|
|
int len; /* len of result */
|
|
int n; /* iteration # */
|
|
{
|
|
static char *res=NULL;
|
|
static int len_ops;
|
|
int i;
|
|
|
|
if (!res) { // 1st call
|
|
len_ops=strlen(ops);
|
|
# ifdef DEBUG_MEM
|
|
printf("mem: allocating operators working area (%d bytes)\n", len+1);
|
|
# endif
|
|
res=malloc(len * sizeof(char) + 1);
|
|
}
|
|
for(i=0; i<len; ++i){
|
|
res[len -i -1] = ops[n % len_ops];
|
|
n /= len_ops;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
void gen_combinations(nops)
|
|
int nops;
|
|
{
|
|
char *ops="/-*+";
|
|
int i, n_combs;
|
|
int len_ops=strlen(ops);
|
|
# ifdef DEBUG_OPER
|
|
printf("gen_combinations(%d)\n", nops);
|
|
# endif
|
|
n_combs=n_combine(len_ops, nops);
|
|
# ifdef DEBUG_MEM
|
|
printf("allocating %d operators combinations\n", n_combs);
|
|
# endif
|
|
combs=malloc(sizeof (char*)*n_combs);
|
|
for (i=0; i<n_combs; ++i) {
|
|
combs[ncombs]=strdup(combine(ops, nops, i));
|
|
ncombs++;
|
|
}
|
|
}
|
|
|
|
int n_combs()
|
|
{
|
|
return ncombs;
|
|
}
|
|
char *nth_comb(n)
|
|
int n;
|
|
{
|
|
return combs[n];
|
|
}
|
|
|
|
#ifdef STANDALONE
|
|
int main(ac, av)
|
|
int ac;
|
|
char **av;
|
|
{
|
|
char *ops="/-+*", *p;
|
|
int len_ops=strlen(ops);
|
|
int i, nops, ncombs;
|
|
|
|
if (ac!=2) {
|
|
fprintf(stderr, "usage: %s nops\n", *av);
|
|
exit (1);
|
|
}
|
|
nops=atoi(*(av+1));
|
|
ncombs=n_combine(len_ops, nops);
|
|
combs=malloc(sizeof (char*)*ncombs);
|
|
printf("# operators combinations : %d\nlist = ", ncombs);
|
|
for (i=0; i<ncombs; ++i) {
|
|
p=combine(ops, nops, i);
|
|
printf("[%s]\n", p);
|
|
//for (j=0; j<4; ++j)
|
|
// distribute(j, p);
|
|
//printf("\n");
|
|
}
|
|
}
|
|
#endif
|