【问题标题】:Print out a specific number of permutations (java)打印出特定数量的排列(java)
【发布时间】:2018-11-02 19:09:01
【问题描述】:

我编写的代码采用数组的元素并遍历数组以给出所有排列。但我需要它只显示一定数量的排列:

最后的代码是只给出 9 个元素的 6 个排列(换句话说,打印总共 362880 个输出的前 60480 个排列)。为简单起见,我使用数组中的 4 个元素,并打印出所有 24 个排列。但我需要代码适用于任意数量的排列。例如,如果我需要它打印出 1-permutation,代码应该打印前 4 个排列 - ABCD、ABDC、ACBD 和 ACDB。我不确定如何解决这个问题。

public static void main(String[] args) {
    // TODO Auto-generated method stub


    String[] myArray = {"A","B","C", "D"};
    int size = myArray.length; 
    permutation(myArray, 0, size-1);

    // Calculate Permutations
    int n=size;
    int r=6; // subject to change
    int p = n - r;
    int total=1;
    int total2=1;
    int total3=0;

    for (int top=n; top>0; top--)
    {
        total *= top;
    }

    if ((n-r<0))
    {
     System.out.println("r value cannot be greater than array size");
     total3=0;
    }
    else 
    {
        for (int bot=1; bot<=p; bot++)
        {
            if (p==0) // should be -- else if (p==0) -- after correction
            {
                total2=1;
            }
            else
            {
                total2 *= bot;
            }
        }
        total3 = total/total2;
    }

    System.out.printf("%d permutations of %d elements = %d\n",r,n,total3);
    // end calculation

}
// end main

// print array
public static void prtArray(String[] myArray, int size)
{
    for(int i=0; i<size; i++)
    {
        System.out.printf("%s", myArray[i]);
    }
    System.out.println();
}

// swap elements    
public static void swap(String[] myArray, int i, int j) {
    String temp;
    temp = myArray[i];
    myArray[i]=myArray[j];
    myArray[j]=temp;
}

// permutation 
private static void permutation(String[] myArray, int b, int e)
{
    if (b == e)
        prtArray(myArray, e+1); // accounts for array of size 1
    else
    {
        for(int i = b; i <= e; i++)
        {

            swap(myArray, i, b);
            permutation(myArray, b+1, e);
            swap(myArray, i, b);

        }
    }
}
}

【问题讨论】:

  • System.out.printf("%d", myArray[i]); 更改为 System.out.printf("%s", myArray[i]);%d 代表数字,%s 代表字符串,而您正在尝试打印字符串。
  • 谢谢。我没有收到任何错误,但元素没有交换(它只是打印出 24 行 ABCD)

标签: java arrays sorting permutation swap


【解决方案1】:

以下是五分之三的完整解决方案:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static java.util.stream.Collectors.toList;

public class Permutations {

  public static void main(String[] args) {
    String[] myArray = {"A", "B", "C", "D", "E"};
    List<String> list = Arrays.asList(myArray);

    List<List<String>> perms = makePerms(list, 3);
    perms.forEach(Permutations::printPerm);
    System.out.println("Size = " + perms.size());
}

  private static List<List<String>> makePerms(List<String> list, int count) {
    if (count == 1) {
      return list.stream().map(Arrays::asList).collect(toList());
    }
    return list.stream()
          .flatMap(e -> makePerms(remove(list, e), count - 1).stream()
                .map(l -> add(l, e)))
          .collect(toList());
  }

  private static <T> List<T> remove(List<T> list, T elem) {
    List<T> newList = new ArrayList<>(list);
    newList.remove(elem);
    return newList;
  }

  private static <T> List<T> add(List<T> list, T elem) {
    List<T> newList = new ArrayList<>(list);
    newList.add(elem);
    return newList;
  }

  private static void printPerm(List<String> perm) {
    perm.forEach(System.out::print);
    System.out.println();
  }
}

【讨论】:

    【解决方案2】:

    问题在于您的交换。您的交换不是交换数组中的元素。因为它正在获取两个字符串并交换它们,但它并没有改变数组内的值。修复你的交换,它会没事的。

    【讨论】:

    • 很难阅读您发布的格式的代码,但我很高兴答案有所帮助。您应该点击正确答案上的“接受”。
    • 我已经更新了代码和问题。关于如何让代码只打印出前 4 个安排的任何提示?因为那是我仍然坚持的地方。
    【解决方案3】:

    我的与 Donat 非常相似。取一个元素并返回其余元素的 len-1 排列。

    public class Permuter {
    
    public static void main(String[] args) {
        List<String> source = asList("A", "B", "C", "D");
        List<String> permutations = returnPermutations(source, 3, 0);
        permutations.forEach(s -> System.out.println(s));
    }
    
    private static List<String> returnPermutations(List<String> source, int choose, int len) {
        List<String> result = new ArrayList<>();
    
        if (len + 1 == choose) {
            return source;
        } else {
            for (String s : source) {
                List<String> tail = new ArrayList<>(source);
                tail.remove(s);
                result.addAll(returnPermutations(tail, choose, len+1).stream().map(ts -> s + ts)
                        .collect(Collectors.toList()));
            }
            return result;
        }
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2017-03-13
      • 2016-10-25
      • 2013-05-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多