【问题标题】:Counting cycles in a permutation of an array计算数组排列中的循环
【发布时间】:2016-02-05 01:13:39
【问题描述】:

我必须编写一些代码来计算数组排列中的周期数。

我在 Google 上找到了我认为是用 python 编写的解决方案:

def key(element):
return element

def find_cycles(l):
seen = set()
cycles = []
for i in range(len(l)):
    if i != key(l[i]) and not i in seen:
        cycle = []
        n = i
        while 1: 
            cycle.append(n)
            n = key(l[n])
            if n == i:
                break
        seen = seen.union(set(cycle))
        cycles.append(list(reversed(cycle)))
return cycles

到目前为止,我自己编写了这段代码,这是我尝试将Python代码转换为Java代码并且它不起作用:

    public static ArrayList<Integer> numbers;
public static ArrayList<Integer> cycles;
public static ArrayList<Integer> cycle; 

public Puslespil(int permutations){
    numbers = new ArrayList<Integer>(); 
    for (int i = 0; i<permutations;i++){
        numbers.add(i);
    }
}

public static void main(String[] args){
    new Puslespil(5);
    ArrayList<Integer> visited = new ArrayList<Integer>();
    cycles = new ArrayList<Integer>();
    Collections.shuffle(numbers);
    System.out.println(numbers);
    for(int i=0; i<numbers.size();i++){
        if(i != numbers.get(i) && !visited.contains(i)){
            cycle = new ArrayList<Integer>();

        }
        int n = i;
        while(true){
            cycle.add(n);
            n = numbers.get(n);
            if(n == i)
                break;
            visited.addAll(cycle);
            Collections.reverse(cycle);
            cycles.addAll(cycle);

        }

    }

    System.out.println("cycles: " + cycles);
}

我找到的Python代码返回了每个循环所涉及的数字,但我真的只需要找到循环的数量。

如何正确转换代码,或提出其他解决方案?

【问题讨论】:

    标签: java python


    【解决方案1】:

    我认为您想找到存储在数组中的排列的循环(即,数组的值是索引 0..N-1)。 对吧?

    如果是这种情况,您需要做的就是从排列的数组表示转换为图/邻接矩阵表示,然后运行此answer(也是 python 代码)中描述的连通分量算法。 连通分量的个数就是循环数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 2019-05-26
      • 2018-10-31
      • 1970-01-01
      • 2018-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多