Проверка анаграммы в Java

Я написал программу, которая проверяет элементы двух массивов и говорит, являются ли они анаграммами или нет. Мой код не работает должным образом. Подскажите, пожалуйста, ошибка в циклах for при сортировке отдельных массивов? Что должно быть исправлено? Должен ли я использовать разные имена для циклов двух массивов?

/*/ Anagrams:

Example: two sets of numbers: {10, 40, 20, 30} and {20, 10, 30, 40} are anagrams to
         each other

/*/

import static java.lang.System.*;
import java.util.*;

class Anagram_Check{
    public static void main(String[] args){
        Scanner orcho = new Scanner(in);
        out.println("Please enter the amount of numbers for the first array: ");
        int quantity1 = orcho.nextInt();
        out.println("Please enter the amount of numbers for the second array: ");
        int quantity2 = orcho.nextInt();

        if(quantity1 != quantity2){
            out.println("No, the arrays will not be anagrams");
        }

        else{
           int[] myArray1 = new int[quantity1];

            out.println("Please enter the numbers of the first array: ");

            for(int count = 0; count < myArray1.length; count++){
                myArray1[count] = orcho.nextInt();
            }

            int icu;

            for(int count = 0; count < myArray1.length; count++){
                for(int check = 0; check < myArray1.length - 1; check++){
                    if(myArray1[check] > myArray1[check + 1]){
                        icu = myArray1[check]; 
                        myArray1[check] = myArray1[check + 1]; 
                        myArray1[check + 1] = icu; 
                    }
                }
            }

            int[] myArray2 = new int[quantity2];

            out.println("Please enter the numbers of the second array: ");

            for(int count = 0; count < myArray2.length; count++){
                myArray2[count] = orcho.nextInt();
            }

            for(int count = 0; count < myArray2.length; count++){
                for(int check = 0; check < myArray2.length - 1; check++){
                    icu = myArray2[check]; 
                    myArray2[check] = myArray2[check + 1]; 
                    myArray2[check + 1] = icu; 
                }
            }

            int d = 0;

            for(int count = 0; count < myArray1.length; count++){
                if(myArray1[count] == myArray2[count]){
                    d = 1;
                }

                else{
                    d = 5;
                }
            }

            if(d == 1){
                out.println("Yes, they are anagrams");
            }  

            else if (d ==5){
                out.println("No, they are not anagrams");
            }
        }

        orcho.close();
    }
}

3 ответа

Я думаю, что проблема заключается в следующем для цикла:

    int d = 0;

    for(int count = 0; count < myArray1.length; count++){
        if(myArray1[count] == myArray2[count]){
            d = 1;
        }
        else{
            d = 5;
        }
    }

так как вы изменяете значение 'd' на каждой итерации, когда вы проверяете значение позже, вы действительно проверяете, равны ли последние элементы обоих массивов. Простым решением было бы добавить

break;

после окончания оператора else, когда вы знаете, что оба массива не равны, нет необходимости продолжать проверку.

редактировать - также было бы лучше использовать логическое значение для d вместо int, поскольку это только два возможных значения

пример проверки, являются ли массивы анаграммами

boolean d = true;

for(int count=0; count < myArray1.length; count++){
    if (myArray[count]!=myArray2[count]){
        d=false;
        break;
    }
}

if (d) {
    System.out.println("Yes, they are anagrams");
}else{
    System.out.println("Yes, they are not anagrams");
}

Используйте этот простой алгоритм сортировки, называемый Bubble Sort. Может использоваться для сортировки небольших списков. Это также эффективно. Перейдите в ваш список, и он сделает все остальное.

например, bubbleSort(myArray1);

public static void bubbleSort(int[] list) {

    boolean flag = true; //checks if all the values have been compared
                         //default is set to true only to enter the loop

    while (flag) {

        flag = false; //assume all values are compared

        for (int i = 0; i < (list.length - 1); i++) {

            if (list[i] < list[i + 1]) {

                int temp = list[i];
                list[i] = list[i + 1];
                list[i + 1] = temp;
                flag = true; //all values are not compared since
                             // were still able to do comparisons
            }
        }
    }
}
import java.util.Arrays;
import java.util.Scanner;

//this program checks if the arrays are anagrams to each other; 
//done by Nadim Baraky

public class Anagram_Check {


  public static void main(String[] args) {

     Scanner sc = new Scanner(System.in);

     System.out.print("Please enter the amount of numbers of the first array: ");
     int quantity_1 = sc.nextInt();

     System.out.print("Please enter the amount of numbers of the second array: ");
     int quantity_2 = sc.nextInt();

     if(quantity_1 != quantity_2) {
        System.out.println("No , the arrays will not be anagrams");
     }

     else {

        int[] myArray1 = new int[quantity_1];
        System.out.print("Please enter the numbers of the first array: ");

        //filling the array with numbers
        for(int i = 0; i < myArray1.length; i++) {
            myArray1[i] = sc.nextInt();
        }
        Arrays.sort(myArray1); //this method sorts the array in increasing order 

        int[] myArray2 = new int[quantity_2];
        System.out.print("Please enter the numbers of the second array: ");

        for(int i = 0; i < myArray2.length; i++) {
                myArray2[i] = sc.nextInt();
        }
        sc.close();
        Arrays.sort(myArray2);

        if(anagram_checker(myArray1, myArray2)) {
            System.out.println("Yes, they are anagrams.");
        }
        else {
            System.out.println("No, they are not anagrams.");
        }
    }
}


 //this method returns ture if the two arrays are anagrams and false otherwise  
  public static boolean anagram_checker(int[] myArray1, int[] myArray2) {
      for(int i = 0; i < myArray1.length; i++) {
         //this loop goes over all the elements of the two arrays and checks if the elements are not equal
          if(myArray1[i] != myArray2[i]) {
             return false;
          }
      } 
          //reaching this point means that all elements are equal & it'll return true
             return true;
  }

}

Другие вопросы по тегам