HOWTO · Java

Java의 배열에서 반복 요소 계산

이 자습서에서는 Java에서 배열의 반복 요소를 계산하는 방법을 보여줍니다.

이 페이지의 내용

이 자습서는 Java에서 배열의 반복 요소를 계산하는 방법을 보여줍니다.

Java의 배열에서 반복 요소 계산

배열의 중복 요소를 계산하는 프로그램을 만들 수 있습니다. 배열은 정렬되지 않거나 정렬될 수 있습니다.

이 튜토리얼은 정렬된 배열과 정렬되지 않은 배열에서 반복되는 요소를 계산하는 방법을 보여줍니다.

배열에서 반복되는 요소를 계산하려면 아래 단계를 따르십시오.

  • 먼저 입력 배열을 가져옵니다.
  • 그런 다음 하나의 임시 배열을 만듭니다.
  • 다음 단계는 입력 배열을 순회하는 것입니다.
  • 순회하는 동안 현재 요소가 임시 배열에 있는지 확인하십시오. 그런 다음 현재 요소에 대한 검사를 건너뛸 필요가 있습니다.
  • 현재 요소를 사용할 수 없는 경우 현재 요소와 모든 다음 요소를 계속 비교합니다.
  • 어느 단계에서든 일치 항목이 발견되면 해당 요소를 임시 배열에 추가합니다.
  • 마지막 단계는 임시 배열에서 총 반복 요소를 표시하는 것입니다.

Java 코드에서 위의 단계를 구현해 보겠습니다.

package delftstack;

public class Example {
  public static void main(String[] args) {
    int InputArray[] = {100, 220, 100, 400, 200, 100, 200, 600, 400, 700};
    int TemporaryArray[] = new int[InputArray.length];
    int RepeatCount = 0;

    for (int x = 0; x < InputArray.length; x++) {
      int element = InputArray[x];
      boolean flag = false;
      for (int y = 0; y < RepeatCount; y++) {
        if (TemporaryArray[y] == element) {
          flag = true;
          break;
        }
      }

      if (flag) {
        continue;
      }

      for (int y = x + 1; y < InputArray.length; y++) {
        if (InputArray[y] == element) {
          TemporaryArray[RepeatCount++] = element;
          break;
        }
      }
    }

    System.out.println("The Total Repeated elements in the array: " + RepeatCount);
    System.out.println("The Repeated elements are : ");
    for (int x = 0; x < RepeatCount; x++) {
      System.out.print(TemporaryArray[x] + " ");
    }
  }
}

위의 코드는 반복되는 숫자를 세고 인쇄합니다. 출력을 참조하십시오.

The Total Repeated elements in the array: 3
The Repeated elements are :
100 400 200

위의 내용은 정렬된 배열과 정렬되지 않은 배열 모두에 사용할 수 있습니다. 그러나 보다 단순화하기 위해 정렬된 배열에 대해서만 작동하는 프로그램을 만들 수 있습니다.

예를 참조하십시오.

package delftstack;

public class Example {
  public static void main(String[] args) {
    int InputArray[] = {100, 100, 100, 200, 200, 220, 400, 400, 600, 700};
    int TemporaryArray[] = new int[InputArray.length];
    int RepeatCount = 0;

    for (int x = 1; x < InputArray.length; x++) {
      int element = InputArray[x];
      if (element == TemporaryArray[RepeatCount]) {
        continue;
      }

      for (int y = x + 1; y < InputArray.length; y++) {
        if (InputArray[y] == element) {
          TemporaryArray[RepeatCount++] = element;
          break;
        }
      }
    }

    System.out.println("The Total Repeated elements in the array: " + RepeatCount);
    System.out.println("The Repeated elements are : ");
    for (int x = 0; x < RepeatCount; x++) {
      System.out.print(TemporaryArray[x] + " ");
    }
  }
}

이제 이 프로그램은 정렬된 배열에 대해 잘 작동합니다. 더 단순화된 버전입니다.

출력을 참조하십시오.

The Total Repeated elements in the array: 3
The Repeated elements are :
100 200 400