2017-02-19 26 views
0

Мне нужно найти все перестановки для данного n (пользовательский ввод) без backtracking.Java set/setElementAt не устанавливает правильное значение

Что я попытался это:

import java.util.Scanner; 
import java.util.Vector; 

class Main { 

    private static int n; 
    private static Vector<Vector<Integer>> permutations = new Vector<>(); 



    private static void get_n() { 

     Scanner user = new Scanner(System.in); 

     System.out.print("n = "); 

     n = user.nextInt(); 
    } 
    private static void display(Vector<Vector<Integer>> permutations) { 

     for (int i = 0; i < factorial(n) - 1; ++i) { 
      for (int j = 0; j < n; ++j) { 
       System.out.print(permutations.elementAt(i).elementAt(j) + " "); 
      } 
      System.out.println(); 
     } 
    } 



    private static int factorial(int n) { 

     int result = 1; 

     for (int i = 1; i <= n; ++i) { 

      result *= i; 
     } 

     return result; 
    } 
    private static int max(Vector<Integer> permutation) { 

     int max = permutation.elementAt(0); 

     for (int i = 1; i < permutation.size(); ++i) 
      if (permutation.elementAt(i) > max) 
       max = permutation.elementAt(i); 

     return max; 
    } 



    // CHECKS FOR ELEMENT COUNT AND 0 - (n-1) APPARITION 
    public static int validate_permutation(Vector<Integer> permutation) { 

     // GOOD NUMBER OF ELEMENTS 
     if (max(permutation) != permutation.size() - 1) 
      return 0; 

     // PROPER ELEMENTS APPEAR 
     for (int i = 0; i < permutation.size(); ++i) 
      if (!permutation.contains(i)) 
       return 0; 

     return 1; 
    } 

    private static Vector<Integer> next_permutation(Vector<Integer> permutation) { 

     int i; 

     do { 
      i = 1; 

      // INCREMENT LAST ELEMENT 
      permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1); 

      // IN A P(n-1) PERMUTATION FOUND n. "OVERFLOW" 
      while (permutation.elementAt(permutation.size() - i) == permutation.size()) { 

       // RESET CURRENT POSITION 
       permutation.set(permutation.size() - i, 0); 

       // INCREMENT THE NEXT ONE 
       ++i; 
       permutation.set(permutation.size() - i, permutation.elementAt(permutation.size() - i) + 1); 
      } 
     } while (validate_permutation(permutation) == 0); 


     // OUTPUT 
     System.out.print("output of next_permutation:\t\t"); 
     for (int j = 0; j < permutation.size(); ++j) 
      System.out.print(permutation.elementAt(j) + " "); 
     System.out.println(); 

     return permutation; 
    } 

    private static Vector<Vector<Integer>> permutations_of(int n) { 

     Vector<Vector<Integer>> permutations = new Vector<>(); 

     // INITIALIZE PERMUTATION SET WITH 0 
     for (int i = 0; i < factorial(n); ++i) { 

      permutations.addElement(new Vector<>()); 

      for(int j = 0; j < n; ++j) 
       permutations.elementAt(i).addElement(0); 
     } 


     for (int i = 0; i < n; ++i) 
      permutations.elementAt(0).set(i, i); 

     for (int i = 1; i < factorial(n); ++i) { 

      // ADD THE NEXT PERMUTATION TO THE SET 
      permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i); 

      System.out.print("values set by permutations_of:\t"); 
      for (int j = 0; j < permutations.elementAt(i).size(); ++j) 
       System.out.print(permutations.elementAt(i).elementAt(j) + " "); 
      System.out.println("\n"); 
     } 

     System.out.print("\nFinal output of permutations_of:\n\n"); 
     display(permutations); 

     return permutations; 
    } 



    public static void main(String[] args) { 

     get_n(); 

     permutations.addAll(permutations_of(n)); 
    } 
} 

Теперь проблема очевидна при выполнении кода. next_permutation выводит правильные перестановки при вызове, значения задаются правильно соответствующему вектору перестановок, но конечный результат является массовой копией последней перестановки, что заставляет меня думать, что каждый раз, когда новая перестановка выводится next_permutation и set в вектор перестановок, как-то, что перестановка также скопирована над все других перестановок. И я не могу понять, почему для меня жизнь.

Я пробовал как set, setElementAt, так и реализацию, где я не инициализирую кубики векторов перестановок, но добавляю перестановки, поскольку они выводятся next_permutation с помощью add(), и я нахожусь в той же самой проблеме. Есть ли какой-то странный способ, с помощью которого Java обрабатывает память? Или что было бы причиной этого?

Спасибо заранее!

ответ

0
permutations.setElementAt(next_permutation(permutations.elementAt(i - 1)), i); 

Это в буквальном смысле установки вектора в permutations(i) быть тот же объект, какpermutations[i-1]. Не то же самое значение - тот же самый объект. Я думаю, что это источник ваших проблем. Вместо этого вам нужно скопировать значения в вектор.

 Смежные вопросы

  • Нет связанных вопросов^_^