Java: Find the number of combinations
Count Combinations Satisfying Sum of Variables
Write a Java program to find the number of combinations that satisfy p + q + r + s = n where n is a given number <= 4000 and p, q, r, s range from 0 to 1000.
Sample Solution:
Java Code:
// Importing the necessary Java utility package
import java.util.*;
// Main class named "Main"
public class Main {
// Main method, the entry point of the program
public static void main(String[] args) {
// Creating a Scanner object to read input from the console
Scanner sc = new Scanner(System.in);
// Prompting the user to input a positive integer
System.out.println("Input a positive integer:");
// Initializing arrays to store temporary and final results
int[] temp = new int[2001];
int[] ans = new int[4001];
// Nested loops to calculate combinations and populate the 'temp' array
for (int i = 0; i <= 1000; i++) {
for (int j = 0; j <= 1000; j++) {
temp[i + j]++;
}
}
// Nested loops to calculate combinations and populate the 'ans' array
for (int i = 0; i <= 2000; i++) {
for (int j = 0; j <= 2000; j++) {
ans[i + j] += temp[i] * temp[j];
}
}
// Reading a positive integer from the user
int n = sc.nextInt();
// Prompting the user with the result
System.out.println("Number of combinations of a, b, c, d:");
// Printing the final result
System.out.println(ans[n]);
}
}
Sample Output:
Input a positive integer: 252 Number of combinations of a,b,c,d: 2731135
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to count the number of quadruple combinations (p, q, r, s) that sum to n using recursion with memoization.
- Write a Java program to determine the number of combinations of four variables summing to n using iterative dynamic programming.
- Write a Java program to count combinations satisfying p + q + r + s = n where each variable is restricted to prime numbers.
- Write a Java program to enumerate all valid combinations (p, q, r, s) that satisfy the sum condition and output the total count.
Go to:
PREV : Maximum Path Sum from Hilltop Data.
NEXT : Add Rows and Columns of Spreadsheet Table.
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.