w3resource

Java Exercises: Find the number of combinations

Java Basic: Exercise-241 with Solution

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 in the range of 0 to 1000.

Sample Solution:

Java Code:

 import java.util.*;
public class Main{ 
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
	System.out.println("Input a positive integer:");
    int[] temp = new int[2001];
    int[] ans = new int[4001];
    for(int i=0;i<=1000;i++){
    for(int j=0;j<=1000;j++){
    temp[i+j]++;
     }
       }
    for(int i=0;i<=2000;i++){
    for(int j=0;j<=2000;j++){
    ans[i+j]+=temp[i]*temp[j];
     }
        }
	      int n = sc.nextInt();
          System.out.println("Number of combinations of a,b,c,d:");
          System.out.println(ans[n]);      
     }
}

Sample Output:

Input a positive integer:
252
Number of combinations of a,b,c,d:
2731135

Flowchart:

Flowchart: Find the number of combinations.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program that compute the maximum value of the sum of the passing integers.
Next: Write a Java program to which adds up columns and rows of given table as shown in the specified figure.

What is the difficulty level of this exercise?



Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

Ref: https://bit.ly/3o8L2KH