【问题标题】:How to turn an array of integers into a permutation and count the loops in it?如何将整数数组转换为排列并计算其中的循环?
【发布时间】:2019-05-26 02:31:11
【问题描述】:

我一直在网上查看并询问朋友,因为我对编码非常陌生。我发现所有这些帖子都是关于在 n 个字母上写下所有可能的排列。我不是在找那个。

我想要实现的是给定一个整数数组,我想将其转换为如下排列。假设 X 是一个整数数组;

X= { 3, 4, 1, 2, 5}

现在熟悉置换群(或对称群)的人会知道,任何置换都有循环符号。我想将 X 视为一些分配值的函数,如下所示;

1 --> 3

2 --> 4

3 --> 1

4 --> 2

5 --> 5

在某种程度上,如果上述函数是置换 sigma,那么我们有 sigma(1)= X 中的第 1 个条目,sigma(2)= X 中的第 2 个条目,依此类推。

最后,我需要计算这个排列中有多少个循环,或者一个循环符号中的循环数。同样对于上面的例子,我们有

1 --> 3 --> 1(所以这是一个循环)

2 --> 4 --> 2(另一个循环)

5 --> 5(这也是一个循环)

所以它也应该告诉我在这种情况下 X 有 3 个循环。

这可能是一个详细的问题,但任何一点点的帮助都非常感谢。非常感谢大家!

【问题讨论】:

  • array of integers,不是string of numbers
  • 我改了标题,希望现在更合适。感谢您的快速回复,因为我是一个完整的新手,您推荐给我的帖子谈论的是 Python 代码。我想在 C 中执行此操作,您认为类似的方法也适用于 C 吗?

标签: c arrays algorithm function permutation


【解决方案1】:

整数数组已经是一个排列,仅偏移一,因为 C 中的数组是零索引的。您可以循环遍历该数组/排列p;一旦看到不属于任何已知循环的元素x,就不断计算p[x]p[p[x]], ...,直到返回x(在C 代码中执行此操作时减去1 以说明零索引C 数组)。那是一个周期;考虑这个循环并继续下一个元素。 C 代码如下所示。

另一种方法是将排列转换为图形并计算图形中连接组件的数量,如here所做的那样。

#include <stdio.h>
#include <stdbool.h>

unsigned count_cycles(const unsigned permutation[], const unsigned n)
{
    unsigned num_cycles = 0;
    bool visited[n];
    unsigned i;

    // initially, no elements are visited
    for(i = 0; i < n; ++i) {
        visited[i] = false;
    }

    // iterate through all elements
    for(i = 0; i < n; ++i) {
        if(!visited[i]) {
            // found a new cycle; mark all elements in it as visited
            int x = i;
            do {
                visited[x] = true;
                x = permutation[x] - 1;
            } while(!visited[x]);
            // account for the new cycle
            num_cycles++;
        }
    }

    return num_cycles;
}

int main()
{
    const unsigned permutation[] = { 3, 4, 1, 2, 5};
    const unsigned N = 5;
    printf("%u\n", count_cycles(permutation, N)); // prints "3"
}

【讨论】:

  • 非常感谢@kfx!我从没想过图表的想法,太棒了!上面的代码很棒,但我也会尝试理解图一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2020-09-10
  • 1970-01-01
  • 2014-08-26
  • 2016-12-24
  • 2018-09-06
  • 1970-01-01
相关资源
最近更新 更多