Vaffelman
Vaffelman

Reputation: 93

Solving a puzzle, array programming, java

I have a problem: I cannot check whenever to elements in two array A and B are the same... why does this not work? It is this part of my program the problem lies, and in the if(A.get(j)==B.get(i)), is there something about arrays i don't know about.

     for(int i=0; i<n; i++){
          if(B.get(i) != A.get(i)){
              for(int j=0; j<n; j++){
                  if(A.get(j)==B.get(i)){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }

The hole program is... import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;

  public class Opgave4Uge6 {
      private static Scanner s;

      public static void main(String arg[]){

      int n = s.nextInt();

      long time = System.currentTimeMillis();

      ArrayList<Integer> A = new ArrayList<>(); 
      for(int a=0; a<n ;a++){
          A.add(new Integer(a));
      }
      System.out.println("The solution");
      System.out.println(A);

      ArrayList<Integer> B = new ArrayList<>(); 
      for(int b=0; b<n ;b++){
          B.add(new Integer(b));
      }
      Collections.shuffle(B);

      System.out.println("The random list");
      System.out.println(B);

      int count = 0;

      for(int i=0; i<n; i++){
          if(B.get(i) != A.get(i)){
              for(int j=0; j<n; j++){
                  if(A.get(j)==B.get(i)){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }
      System.out.println(B+" Solved!");
      System.out.println("Number of moves "+count);
      int k = n-count;
      System.out.println("Number of cycles "+k);
      long newtime = System.currentTimeMillis()-time;
      System.out.println("Time "+newtime+" ms");
      }
  }

BTW: I am using Netbeans.

Upvotes: 0

Views: 1251

Answers (1)

amudhan3093
amudhan3093

Reputation: 750

Its not about arrays.use .equals() method

for(int i=0; i<n; i++){
          if(!B.get(i).equals(A.get(i))){
              for(int j=0; j<n; j++){
                  if(A.get(j).equals(B.get(i))){
                      Collections.swap(B, j, i);
                      System.out.println("Swapping "+i+" with "+j+" : "+B);
                      count++;
                  }
              }
          }
      }

Upvotes: 2

Related Questions