Liệt kê các phần tử trong mảng 1 chiều số nguyên thỏa mãn thuộc đoạn [x, y]

Yêu cầu
– Nhập vào mảng 1 chiều số nguyên
– Nhập x, y là giá trị 2 đầu mút.
– Viết hàm liệt kê các phần tử trong mảng 1 chiều số nguyên thỏa mãn thuộc đoạn [x, y].

Giải thuật
– Dùng vòng lặp for() đếm các số lượng phần tử nằm trong đoạn [x, y] – Cấp phát mảng động subArr[] với kích thước đã đếm ở trên.
– Kiểm tra phần tử của mảng, nếu thỏa mãn thuộc đoạn [x, y], lưu vào mảng subArr[]

Code

package net.vncoding;
import java.util.Scanner;

public class JavaCore {
	
    public static void main(String[] args) {
        
    	int arr[] = {1, 3, -6, 13, 0, 20, 9, -7, 14, 0, 34, 28, 32, 11, 100};
    	int x, y;
        Scanner sc = new Scanner(System.in);
        do {
        	System.out.print("x = ");
            x = sc.nextInt();
            System.out.print("y = ");
            y = sc.nextInt();
        }while(x >= y);
        
        int[] subArr = GetElement(arr, x, y);
        
        if(subArr.length == 0) {
            System.out.format("No elements belongs to [%d;%d]", x, y);
        }
        else {
            System.out.format("Elements belongs to [%d;%d] are:\n", x, y);
            for(int i = 0; i < subArr.length; i++) {
        	System.out.print(subArr[i] + "\t");
            }
        }
        sc.close();
    }
    
    public static int[] GetElement(int[] arr, int x, int y) {
    	int cnt = 0;
    	int i, j = 0;
    	// Count the number of element belongs to [x; y]
    	for(i = 0; i < arr.length; i++) {
            if(arr[i] <= y && arr[i] >= x) {
        	cnt++;
            }
        }
    	// Extract elements which belongs to [x;y]
    	int[] subArr = new int[cnt];
    	for(i = 0; i < arr.length; i++) {
            if(arr[i] <= y && arr[i] >= x) {
        	subArr[j++] = arr[i]; 
            }
        }
    	return subArr;
    }
}

Kết quả

Java - Liệt kê các phần tử trong mảng 1 chiều số nguyên thỏa mãn thuộc đoạn [x, y]
Java – Liệt kê các phần tử trong mảng 1 chiều số nguyên thỏa mãn thuộc đoạn [x, y]

Be the first to comment

Leave a Reply