Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

โปรแกรม Java คำนวณการจัดหมู่ (nCr Combinations)


ในบทความนี้ เราจะทำความเข้าใจวิธี คำนวณการจัดหมู่ (Combination - nCr) ใน Java

สูตร: nCr = n! / (r! × (n-r)!)

โดย n! = แฟกทอเรียลของ n

ตัวอย่าง Input และ Output

Input:

Value of n : 6
Value of r : 4

Output:

The nCr value is : 15

อัลกอริธึม

ขั้นตอนที่ 1 - เริ่มต้น
ขั้นตอนที่ 2 - ประกาศตัวแปร n, r
ขั้นตอนที่ 3 - อ่านค่าจากผู้ใช้ หรือกำหนดค่าเริ่มต้น
ขั้นตอนที่ 4 - สร้างฟังก์ชัน my_factorial คำนวณแฟกทอเรียล
ขั้นตอนที่ 5 - สร้างฟังก์ชัน Compute_nCr ใช้สูตร n! / (r! * (n-r)!)
ขั้นตอนที่ 6 - เรียกฟังก์ชันและแสดงผล
ขั้นตอนที่ 7 - หยุด

ตัวอย่างที่ 1: รับค่าจากผู้ใช้

import java.util.*;
public class Combination {
    static int Compute_nCr(int n, int r) {
        return my_factorial(n) / (my_factorial(r) * my_factorial(n - r));
    }
    static int my_factorial(int n) {
        int i, my_result;
        my_result = 1;
        for (i = 2; i <= n; i++)
            my_result = my_result * i;
        return my_result;
    }
    public static void main(String[] args) {
        int n, r;
        System.out.println("Required packages have been imported");
        Scanner my_scanner = new Scanner(System.in);
        System.out.println("A reader object has been defined");
        System.out.print("Enter the value of n : ");
        n = my_scanner.nextInt();
        System.out.print("Enter the value of r : ");
        r = my_scanner.nextInt();
        System.out.println("The combination value for the given input is = " + Compute_nCr(n, r));
    }
}

Output

Required packages have been imported
A reader object has been defined
Enter the value of n : 6
Enter the value of r : 4
The combination value for the given input is = 15

ตัวอย่างที่ 2: กำหนดค่าไว้ล่วงหน้า

public class Combination {
    static int Compute_nCr(int n, int r) {
        return my_factorial(n) / (my_factorial(r) * my_factorial(n - r));
    }
    static int my_factorial(int n) {
        int i, my_result;
        my_result = 1;
        for (i = 2; i <= n; i++)
            my_result = my_result * i;
        return my_result;
    }
    public static void main(String[] args) {
        int n, r;
        n = 6;
        r = 4;
        System.out.println("The n and r values are defined as " + n + " and " + r);
        System.out.println("The combination value for the given input is = " + Compute_nCr(n, r));
    }
}

Output

The n and r values are defined as 6 and 4
The combination value for the given input is = 15