2017-02-20 9 views
4

Это один метод для моего класса, который используется для проверки того, имеют ли две последовательности одинаковые значения в некотором порядке, игнорируя дубликаты.Метод для возврата булеана, который определяет, являются ли 2 массива одинаковыми в значениях


Например:

первый: 3 3 2 1 1

Второе: 2 3 1

Они считаются одинаковыми в этом методе.


Однако

первый: 3 3 2 1 1

второй: 3 3 1 1

считаются не то же самое.


'

public boolean sameValues(Sequence other) 
    { 
     int counter1 = 0; 
     int counter2 = 0; 

     //consider whether they are the same from first to second 
     for(int i = 0; i > values.length; i++) 
     { 
      for(int n = 0; n > other.len(); n++) 
      { 
       counter1++; 
       if(values[i] == other.get(n)) 
       { 
        break; 
       } 
      } 

      if(values[i] != other.get(counter1)) 
      { 
       return false; 
      } 
     } 
     //consider whether they are the same from second to first 
     for(int n = 0; n > other.len(); n++) 
     { 
      for(int i = 0; i > values.length; i++) 
      { 
       counter2++; 
       if(values[i] == other.get(n)) 
       { 
        break; 
       } 
      } 

      if(values[counter2] != other.get(n)) 
      { 
       return false; 
      } 
     } 
     return true; 
    } 

'

Однако, независимо от того, что я импортировать, ответ всегда будет правдой.

'

import java.util.Scanner; 
import java.util.Arrays; 

public class SameValuesTester 
{ 
    public static void main(String[] args) 
    { 
     Sequence first = new Sequence(20); 
     Sequence second = new Sequence(20); 
     int firstCounter = 0; 
     int secondCounter = 0; 

     //import the first array 
     Scanner x = new Scanner(System.in); 
     System.out.println("Please enter the values" + 
          "for the first sequence with q to quit."); 
     for(int i = 0; x.hasNextInt(); i++) 
     { 
      first.set(i, x.nextInt()); 
      firstCounter++; 
     } 

     //import the second array 
     Scanner y = new Scanner(System.in); 
     System.out.println("Please enter the values" + 
          "for the second sequence with q to quit."); 
     for(int j = 0; y.hasNextInt(); j++) 
     { 
      second.set(j, y.nextInt()); 
      secondCounter++; 
     } 

     //.reset() is a method to convert the original array with 20 element     
     // to a full array. 
     first.reset(firstCounter); 
     second.reset(secondCounter); 

     //compare two Sequence 
     System.out.println(first.sameValues(second)); 
    } 
} 

'

+0

, так что вы просто хотите проверить, имеют ли они одинаковые значения в нем, независимо от количества вхождений? – XtremeBaumer

+0

Какое правило для определения '3 3 2 1 1' и' 2 3 1' совпадают, но '3 3 2 1 1' и' 3 3 1 1' не являются? –

+0

Вам нужно только проверить, имеют ли две последовательности одинаковые значения в некотором порядке, игнорируя дубликаты. @XtremeBaumer –

ответ

3

Что вы могли бы сделать, это создать два HashSet от вашего Arrays и использовать HashSet.containsAll(), чтобы проверить, если они содержат одни и те же элементы:

//Arrays as input 
Integer[] array1 = {3, 3, 2, 1, 1}; 
Integer[] array2 = {2, 3, 1}; 

Set<Integer> set1 = new HashSet<Integer>(); 
Set<Integer> set2 = new HashSet<Integer>(); 

//Fill set1 and set2 from array1 & array2 
Collections.addAll(set1, array1); 
Collections.addAll(set2, array2); 

//return result 
return set1.containsAll(set2) && set2.containsAll(set1); 
2

Там это два вопроса.

Во-первых, есть опечатка (> вместо < в охранниках). Условие защиты никогда не выполняется, что всегда возвращает true.

Другое относится к способу обработки счетчиков. Вам нужен цикл while, который прерывается, когда это значение найдено, а затем проверьте, находится ли счетчик в конце массива, и в этом случае это ложь.

public boolean sameValues(Sequence other) 
{ 
    //consider whether they are the same from first to second 
    for(int i = 0; i < values.length; i++) 
    { 
     int counter = 0; 
     while(counter < other.len()) 
     { 
      if(values[i] == other.get(counter)) 
      { 
       break; 
      } 
      counter++; 
     } 

     if(counter == other.len()) 
     { 
      return false; 
     } 
    } 
    //consider whether they are the same from second to first 
    for(int n = 0; n < other.len(); n++) 
    { 
     int counter = 0; 
     while(counter < values.length) 
     { 
      if(other.get(n) == values[counter]) 
      { 
       break; 
      } 
      counter++; 
     } 

     if(counter == values.length) 
     { 
      return false; 
     } 
    } 
    return true; 
} 
Смежные вопросы