Generate numbers (Permutation) in java

               Numbers are magical elements in the field of mathematics. Generating all possible number combinations from a set of numbers is permutation. Let us generate numbers based on this.

How to generate numbers like permutation in java?

Let us create this program using an integer array.

Steps:

àMain method:

  • Include the built in packages java.util.ArrayList and java.util.List.
  • First, Write the code for class with main() function.
  • Next, Declare an integer array with 3 integers as input.
  • Now, call a function generateNos() with input array as arguments.
  • Finally, print the number received from the function.

à generateNos():

  • It create a list(output) for display.
  • It has array as Boolean which stores the  ip_used.
  • Call the backtrack_it function.It generates the number combination (Permutation).

àbacktrack_it():

  • It checks the current number combination is same as the ip_digits, it is added to output.
  • Each number is added and marked as used and recursively calling the array until all numbers are iterated.
  • Finally, it backtracks the unmarking digit and deleted from the current number combination.

Program:

import java.util.ArrayList;

import java.util.List;

public class GenerateNos {

    public static void main(String[] args) {

        int[] ip_digits = {4, 3, 7};

        List<String> nos = generateNos(ip_digits);

        for (String number : nos) {

            System.out.println(number);

        }

    }

    public static List<String> generateNos(int[] ip_digits) {

        List<String> output = new ArrayList<>();

        boolean[] ip_used = new boolean[ip_digits.length];

        backtrack_it(output, ip_digits, new StringBuilder(), ip_used);

        return output;

    }

    private static void backtrack_it(List<String> output, int[] ip_digits, StringBuilder ip_current, boolean[] ip_used) {

        if (ip_current.length() == ip_digits.length) {

            output.add(ip_current.toString());

            return;

        }

        for (int i = 0; i < ip_digits.length; i++) {

            if (ip_used[i]) continue;

            ip_used[i] = true;

            ip_current.append(ip_digits[i]);

            backtrack_it(output, ip_digits, ip_current, ip_used);

            ip_used[i] = false;

            ip_current.deleteCharAt(ip_current.length() - 1);

        }

    }

}

Output:

C:\raji\blog>javac GenerateNos.java

C:\raji\blog>java GenerateNos

437

473

347

374

743

734

This is the way of generating numbers in java. Here, we generated number combination as permutation. Keep coding!!!

No comments:

Post a Comment