【问题标题】:Finding Permutations of Strings with no Repeats [duplicate]查找没有重复的字符串的排列[重复]
【发布时间】:2014-04-17 23:06:06
【问题描述】:

我已经在这个论坛here 上发布了这个问题,但是看到没有人回答我决定在这里尝试。

基本上,我正在寻找一种方法来置换给定范围内的整数数组,而不会重复排列。过去我很难理解如何找到排列,所以我希望有人可以深入解释我需要实现什么以及为什么。

这是我现在的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define LENGTH 2

double NumberOfPermuationsOfString( int length, char minimum, char maximum )
{
    return pow( ( maximum - minimum ) + 1, length );
}

int NextPermutation( char * buffer, char minimum, char maximum )
{
    const size_t length = strlen( buffer ) + 1;

    int i = 0;

    for ( ; i < length; ++i )
    {
        /* I don't know what to do here... */
    }

    return 0;
}

void DisplayPermutations( int length, char minimum, char maximum )
{
    char buffer[( length + 1 )];
    memset( buffer, 0, sizeof( buffer ) );
    memset( buffer, minimum, sizeof( buffer ) - 1 );

    int i = 0;

    do
    {
        printf( "%s\n", buffer );
    } while ( NextPermutation( &buffer[0], minimum, maximum ) );
}

int main( )
{
    printf( "Iterating through %0.lf permuations...\n", NumberOfPermuationsOfString( LENGTH, 'a', 'z' ) );
    DisplayPermutations( LENGTH, 'a', 'z' );

    return 0;
}

这不是 C#,不要让命名约定欺骗了您...

【问题讨论】:

  • “没有重复排列”是什么意思?你打算把 1,2,3 和 3,2,1 一样对待吗?
  • 我不想有“abc”一次,然后再出现。这又是怎么重复的?这不是 C#...
  • 嗯,C,但我想说的是它适用于 C++。

标签: c++ c arrays string algorithm


【解决方案1】:

Fabulous Adventures in Coding blog 的作者 Eric Lippert 在Producing Permutations 上有一个很好的系列。

在解释中,他提供了代码。例如,part four 中的以下 sn-p 执行您想要的操作 并且 允许随机访问(但使用自定义类型):

public static Permutation NthPermutation(int size, BigInteger index)
{
  if (index < 0 || index >= Factorial(size))
    throw new ArgumentOutOfRangeException("index");
  if (size == 0) // index must be zero since it is smaller than 0!
    return Empty;
  BigInteger group = index / size; // What block are we in?
  Permutation permutation = NthPermutation(size - 1, group);
  bool forwards = group % 2 != 0; // Forwards or backwards?
  int insert = (int) (index % size); // Where are we making the insert?                      
  return new Permutation(
    permutation.InsertAt(forwards ? insert : size - insert - 1, size - 1));
}

【讨论】:

  • 我没有在 C# 中执行此操作...这意味着我无法访问此类方法。
  • 您应该能够提取底层逻辑并将其转换为 C++。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多