How to generate N number of passwords of length M each in Java

Java program to generate N passwords, each of length M. The number of passwords returned does not exceed length of M.

Example:

Input : N = 1, M = 3
Output: 571

Input : N = 2, M = 4
Output: 5671
        1987

Approach:

  • Import random package for creating random numbers.
  • Initialize variables N and M.
  • Create an array of N length.
  • Run nested loops
  1. First loop for generating N numbers of passwords.
  2. Second loop for creating the password of M length.

Below is the implementation of the above approach:

// Java Program to Generate N Number
// of Passwords of Length M Each
import java.util.Random;
import java.util.Scanner;

public class GFG {
	public static void main(String args[])
	{
		// create a object of random class
		Random r = new Random();
		// N is numbers of password
		int N = 5;
		// M is the length of passwords
		int M = 8;
		// create a array of store passwords
		int[] a = new int[N];

		// run for loop N time
		for (int j = 0; j < N; j++) {
			// run this loop M time for genarating
			// M length password
			for (int i = 0; i < M; i++) {
				// store the password in array
				System.out.print(a[j] = r.nextInt(10));
			}
			System.out.println();
		}
	}
}

Output

73807243
05081188
63921767
70426689
06272980

Time Complexity: O(N*M), where N is the number of required passwords and M is the length of each password.

Submit Your Programming Assignment Details