Generate all the possible k-ary strings of length and digit upto k
💻 coding

Generate all the possible k-ary strings of length and digit upto k

1 min read 150 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to generate all possible k-ary strings of a specified length n using digits up to k.
  • 2A Java solution is provided to recursively generate and print all combinations of k-ary strings.
  • 3The time complexity of generating these strings is O(k^n), indicating exponential growth with increasing n and k.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to generate all possible k-ary strings of a specified length n using digits up to k."

Generate all the possible k-ary strings of length and digit upto k

You have been given an integer n that corresponds to the length of the array and k which corresponds to the digit value possible in the array. The task is to print all the possible strings using those k values of length n. the array can consist only value digits up to k.

Java Solution:

public class AllStringsKAry {

	public static void main(String[] args) {
		int n = 3;
		int k = 2;
		int[] arr = new int[n];
		GenerateAllStringKAry(n, arr, k);
	}

	private static void GenerateAllStringKAry(int n,int[] arr, int k) {
		if(n<1) {
			for(int i=0;i<arr.length;i++) {
				System.out.print(arr[i]);
			}
			System.out.println();
		}
		else {
			for(int i=0;i<=k;i++) {
				arr[n-1]=i;
				GenerateAllStringKAry(n-1, arr, k);
			}
			
		}
			
	}

}

The time complexity of the above solution is O(k^n).

output:

000
100
200
010
110
210
020
120
220
001
101
201
011
111
211
021
121
221
002
102
202
012
112
212
022
122
222

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 16 July 2018 · 1 min read · 150 words

Part of AskGif Blog · coding

You might also like

Generate all the possible k-ary strings of length and digit upto k | AskGif Blog