字符串:基于给定长度的所有组合 [英] Strings: All combinations based on a given length

查看:105
本文介绍了字符串:基于给定长度的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,

我想基于多个字符生成字符串的所有组合.例如,如果我输入数字"5",则我的程序应生成5个字母的所有可能单词.



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?

推荐答案

我有您的代码:
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;
}


问候.


请参阅此链接
单击
see this link
Click


这篇关于字符串:基于给定长度的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆