Monday 27 November 2017

Java Program to Generate All Possible Combinations of a Given List of Numbers


Code:

import java.util.Random;
import java.util.Scanner;

public class Permute_All_List_Numbers 
{
    static void permute(int[] a, int k) 
    {
        if (k == a.length) 
        {
            for (int i = 0; i < a.length; i++) 
            {
                System.out.print(" [" + a[i] + "] ");
            }
            System.out.println();
        } 
        else 
        {
            for (int i = k; i < a.length; i++) 
            {
                int temp = a[k];
                a[k] = a[i];
                a[i] = temp;

                permute(a, k + 1);

                temp = a[k];
                a[k] = a[i];
                a[i] = temp;
            }
        }
    }

    public static void main(String args[]) 
    {
        Random random = new Random();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the length of list: ");
        int N = sc.nextInt();
        int[] sequence = new int[N];

        for (int i = 0; i < N; i++)
            sequence[i] = Math.abs(random.nextInt(100));

        System.out.println("The original sequence is: ");
        for (int i = 0; i < N; i++)
            System.out.print(sequence[i] + " ");

        System.out.println("\nThe permuted sequences are: ");
        permute(sequence, 0);

        sc.close();
    }
}


Output:

Enter the length of list: 
3
The original sequence is: 
15 61 16 
The permuted sequences are: 
 [15]  [61]  [16] 
 [15]  [16]  [61] 
 [61]  [15]  [16] 
 [61]  [16]  [15] 
 [16]  [61]  [15] 
 [16]  [15]  [61] 


Enter the length of list: 
4
The original sequence is: 
50 98 4 61 
The permuted sequences are: 
 [50]  [98]  [4]  [61] 
 [50]  [98]  [61]  [4] 
 [50]  [4]  [98]  [61] 
 [50]  [4]  [61]  [98] 
 [50]  [61]  [4]  [98] 
 [50]  [61]  [98]  [4] 
 [98]  [50]  [4]  [61] 
 [98]  [50]  [61]  [4] 
 [98]  [4]  [50]  [61] 
 [98]  [4]  [61]  [50] 
 [98]  [61]  [4]  [50] 
 [98]  [61]  [50]  [4] 
 [4]  [98]  [50]  [61] 
 [4]  [98]  [61]  [50] 
 [4]  [50]  [98]  [61] 
 [4]  [50]  [61]  [98] 
 [4]  [61]  [50]  [98] 
 [4]  [61]  [98]  [50] 
 [61]  [98]  [4]  [50] 
 [61]  [98]  [50]  [4] 
 [61]  [4]  [98]  [50] 
 [61]  [4]  [50]  [98] 
 [61]  [50]  [4]  [98] 
 [61]  [50]  [98]  [4]



More Java Programs:


















100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...