Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
HI,

I want to generate all combinations of a string based on the a number of characters. For instance, if I enter the number "5" then my program should generate all the possible words with 5 letters.

Please anyone can help me to start this logic?
Posted
Updated 4-Apr-11 23:54pm
v2

I have YOUR code:
#pragma once
#include <stdio.h>
#include <tchar.h>
#include <malloc.h>

#define  AC(A)  (sizeof(A)/sizeof(A[0]))

const TCHAR  __all_chars[] = __T("abcdefg");

int increment(unsigned int* used,const unsigned int count)
{
  unsigned int  ix;
  for(ix=0;(ix<count) && ((AC(__all_chars)-1)<=(++used[ix]));used[ix]=0,ix++);
  return ix<count;
}

void build(TCHAR* buff,unsigned int* used,const unsigned int count)
{
  unsigned int  ix;
  for(ix=0;ix<count;ix++) buff[ix] = __all_chars[used[ix]];
  buff[ix] = 0;
}

void combine(TCHAR* buff,const unsigned int count)
{
  unsigned int*  used = (unsigned int*)malloc(sizeof(unsigned int)*count);
  unsigned int  ix,done=0;

  for(ix=0;ix<count;ix++) used[ix] = 0;
  do
  {
    build(buff,used,count); ++done;
    _tprintf(__T("%04i: %s\r\n"),done,buff);
  } while(increment(used,count));

  free(used);
}

int _tmain(int argc, _TCHAR* argv[])
{
  TCHAR          s[256];
  TCHAR*        e;
  unsigned int  n;
  if(_getts_s(s,AC(s)))
  {
    n = _tcstoul(s,&e,10);
    if(0<n)
    {
      TCHAR*  buff = (TCHAR*)malloc(sizeof(TCHAR)*(1+n));
      combine(buff,n);
      free(buff);
    }
  }

  _gettch();
  return 0;
}

Regards.
 
Share this answer
 
Comments
LaxmikantYadav 5-Apr-11 9:05am    
My 5, Nice Algo :)
see this link
Click
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900