English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

كيف تجد جميع أزواج العناصر في تشكيلات Java التي تبلغ مجموعها عددًا معينًا؟

البحث عن جميع الأزواج من العناصر في جهاز التوجيه Java التي تساوي العدد المحدد-

  • أضف كل عنصر في المجموعة إلى جميع العناصر المتبقية (باستثناء نفسه).

  • تحقق من أن مجموع العناصر يساوي العدد المطلوب.

  • إذا كان صحيحًا، فإنه يطبع مؤشره.

مثال

import java.util.Arrays;
import java.util.Scanner;
public class sample {
   public static void main(String args[]){
      // من قراءة المجموعة من المستخدم
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the size of the array that is to be created:")
      int size = sc.nextInt();
      int[] myArray = new int[size];
      System.out.println("Enter the elements of the array:");
      for(int i=0; i<size; i++){
         myArray[i] = sc.nextInt();
      }
      //Read number
      System.out.println("Enter the number:");
      int num = sc.nextInt();
      System.out.println("The array created is: " + Arrays.toString(myArray));
      System.out.println("indexes of the elements whose sum is: " + num);
      for(int i=0; i<myArray.length; i++){
         for(int j=i; j<myArray.length; j++){
            if((myArray[i]+myArray[j])== num && i!=j){
               System.out.println(i+", "+j);
            }
         }
      }
   }
}

نتيجة الخروج

Enter the size of the array that is to be created:
8
Enter the elements of the array:
15
12
4
16
9
8
24
0
Enter the number:
24
The array created is: [15, 12, 4, 16, 9, 8, 24, 0]
indexes of the elements whose sum is: 24
0, 4
3, 5
6, 7
تعليمية Elasticsearch