Question: Suppose you represent every number with a character like
0 –> a, 1 –> b, 2 –> c, ………………24 –> y, 25 –> z
Now given a number, give words combinations for it.
Example: 1234
=> 1-2-3-4, 12-2-4, 1-23-4
=> bcde, mde, bxe
Answer: As we are seeing in example, we can see that every time we can club at most 2 numbers at a time. And that too only if they form a number less than 25 (=> z). Now if we divide this problem in sub-problems (sub string) and append the result of second part to result of first part recursively, whoa! We are done.
Example: Lets say our input is “121324”, and our generation function is Calculate(), then output will be like:
This process will stop, once we reach the last character in input string. Now this is a simple recursion now, with few things in mind:
- Recursion will stop once we reach the last character in input string.
- While we are combining 2 characters, we should take care that it doesn’t exceed 25.
Code:
// 1234 => 1-2-3-4, 12-2-4, 1-23-4 => bcde, mde, bxe #include <iostream> using namespace std; char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; char input[100]; int len; void print_combination(int index, char out[], int outindex) { if(index == len){ out[outindex] = '\0'; cout << out << endl; return; } if(index <= (len - 1)){ out[outindex] = arr[int(input[index]) - 48]; print_combination(index+1, out, outindex+1); } if(index <= (len - 2)){ int num = (int(input[index])-48)*10 + (int(input[index+1])-48); if (num <= 25){ out[outindex] = arr[num]; print_combination(index+2, out, outindex+1); } } } int main(int argc, char* argv[]) { char out[100] = {'\0',}; if (argc < 2) exit(0); else strcpy(input,argv[1]); len = strlen(input); print_combination(0, out, 0); }Update: We can also consider memoization to save repetitive call for same substring.
Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.
Can you provide java code..........
@Rajeev: Sorry mate, I am not into Java. Please try understanding the algorithm.
Here comes a java implementation
Hats off Akash for your wonderful explanation :-)
import java.io.*;
class str
{
public static void main(String args[])
{
String n="121";
calc(n,"");
}
public static void calc(String n,String op)
{
String a="abcdefghijklmnopqrstuvwyz";
int v1=0,v2=0;
if(n.length()==0)
System.out.println(op);
if(n.length()>0)
{
v1=Character.getNumericValue(n.charAt(0));
op+=a.charAt(v1);
calc(n.substring(1),op);
}
if(n.length()>1)
{
v2=Character.getNumericValue(n.charAt(1));
if(10*v1+v2 <=25)
{
op=op.substring(0,op.length()-1)+a.charAt(10*v1+v2);
calc(n.substring(2),op);
}
}
}
}
@Anonymous: thanks mate for your contribution.
public class CharCombinationWithNumbers {
private static char[] alphabet = "abcdefghijklmnopqrstyuvxyz".toCharArray();
public static void main(String[] args) {
printPossibilities("", "1234");
}
private static void printPossibilities(String partialString, String string) {
if (string == null || string.length() < 1) {
System.out.println(partialString);
return;
}
int digit = Integer.parseInt(string.substring(0, 1));
printPossibilities(partialString + alphabet[digit], string.substring(1));
if (string.length() > 1) {
digit = Integer.parseInt(string.substring(0, 2));
if (digit >= 10 && digit < alphabet.length) {
printPossibilities(partialString + alphabet[digit], string.substring(2));
}
}
}
}
Nice explanation. I like it. Here is my java version.
public class CharCombinationWithNumbers {
private static char[] alphabet = "abcdefghijklmnopqrstyuvxyz".toCharArray();
public static void main(String[] args) {
printPossibilities("", "1234");
}
private static void printPossibilities(String partialString, String string) {
if (string == null || string.length() < 1) {
System.out.println(partialString);
return;
}
int digit = Integer.parseInt(string.substring(0, 1));
printPossibilities(partialString + alphabet[digit], string.substring(1));
if (string.length() > 1) {
digit = Integer.parseInt(string.substring(0, 2));
if (digit >= 10 && digit < alphabet.length) {
printPossibilities(partialString + alphabet[digit], string.substring(2));
}
}
}
}
Thanks guys!
I think this is not the optimal code. You can use DP to reduce the order of computation.
c++ code is here:
#include
using namespace std;
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char input[100];
int len;
void print_combination(int index, char out[], int outindex)
{
if(index == len){
out[outindex] = '\0';
cout << out << endl;
return;
}
if(index <= (len - 1)){
out[outindex] = arr[int(input[index]) - 48];
print_combination(index+1, out, outindex+1);
}
if(index <= (len - 2)){
int num = (int(input[index])-48)*10 + (int(input[index+1])-48);
if (num <= 25){
out[outindex] = arr[num];
print_combination(index+2, out, outindex+1);
}
}
}
int main(int argc, char* argv[])
{
char out[100] = {'\0',};
if (argc < 2)
exit(0);
else
strcpy(input,argv[1]);
len = strlen(input);
print_combination(0, out, 0);
}
import java.util.*;
public class Combos{
________public static void main(String[] args){
__________printCombos(1234);
________}
________public static void printCombos(int i){
__________printCombos(i, "");
________}
________private static void printCombos(int i, String str){
__________if (i == 0){
____________System.out.println(str);
____________return;
__________}
__________int rightDigit = rightDigits(i,1);
__________printCombos(
____________trimRightDigits(i,1),
____________toChar(rightDigit) + str);
__________int rightTwoDigits = rightDigits(i,2);
__________if (rightDigit != rightTwoDigits &&
______________inRange(rightTwoDigits)){
____________printCombos(
______________trimRightDigits(i,2),
______________toChar(rightTwoDigits) + str);
____________}
________}
________private static int rightDigits(int i, int len){
__________return i%((int)Math.pow(10,len));
________}
________private static int trimRightDigits(int i, int len){
__________return i/((int)Math.pow(10,len));
________}
________private static char toChar(int i){
__________return Character.toChars('a'+i)[0];
________}
________private static boolean inRange(int i){
__________return i < 26;
________}
}
Really amazing information you have shared i was looking for this kind of unique information please do share that kind of unique information more as you can.
-Web Development Services
Uniqueness is the key to writing blogs. So you are providing with great informative sense. I am impressed with your way of providing such good content to read.Custom Website Development WordPress
You performed a fantastic job! This is a fantastic article. This is quite appealing to me. It is quite helpful to my research. It's evident that you're passionate about the subject. I'm hoping you'll give me more information about the software. Please keep spreading the word. Custom Website Design Company
How much I learnt from this blog is beyond your comprehension.
Custom Website Developer