Generating total number of n-lettered alphabet combinations in C - c

I am supposed to write a logic to generate a combination of n-lettered words.
For example, if the number 2 is provided, I am required to generate all two-lettered words from a-z i.e:
aa-ba-ca.....za
ab-bb-cb.....zb
.
.
.
.
az-bz........zz
I understood that nested loops will not suffice for this problem since the number of nested loops changes with the number of letters in the word. This turns me to recursion, but I can't think of the logic.

Recursion is the key here. Here is an example written in Java:
public static void printCombos(int totalWords, String s) {
if(totalWords-- <= 0) {
System.out.print(s + " ");
return;
}
for(char i = 'a'; i <= 'z'; i++)
printCombos(totalWords, s + Character.toString(i));
System.out.println();
}
Invoke it:
printCombos(2, "");

There are 26^2 combinations for two letters, 26^3 combinations for three letters and so on - 26^n combinations for n letters
So you can just make one loop for values 0..26^n-1 and build correspoding combinations for every loop counter value
Python-like pseudocode:
result = [""] * n
for i in range(26**n):
t = i
for k in range(n):
digit = t % 26
result[k] = letter[digit] #"a" for 0, "b" for 1 etc
t = t // 26
print(result)

The point of this lesson is to teach you recursion, which is much more valuable than pedantic cheek... but just to be a contrarian, you could totally do this with nested loops if you want. You can do it with an unnested loop...
void up_to_n_letters(int n)
{
char word[n];
int i = 0;
for (char letter = 'a'; i < n; letter++) {
word[i] = letter;
printf("%s,\n", word);
if (letter == 'z') {
letter = 'a' - 1;
i++;
}
}
}

Related

CS50 Week 2 Caesar Practice

My code seems to be working properly except at the point when it should print the final output. The problem is to input a string and output an encrypted version. The encryption works by adding an int defined as the key and then adding that value to each character of the ascii values of the inputed string. My issue is that when the cypher text is outputted there are only spaces and no letters or even numbers.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[]) {
int key = atoi(argv[1]);
printf("%i\n", key);
if (argc != 2) {
printf("Usage: ./ceasar key\n");
} else {
string text = get_string("Plaintext: ");
for (int i = 0, len = strlen(text); i < len; i++) {
int cipher = text[i];
int ciphertext = cipher + key;
int ciphermod = ciphertext % 26;
printf("%c", ciphermod);
}
printf("\n");
}
}
You've got a few issues going on here. Please make sure to thoroughly read the assignment before turning to others for assistance.
The assignment requires you to:
Only encode alphabetic characters. Look to the function isalpha() for this.
Encode both uppercase and lowercase characters accurately. Note that, in ASCII, uppercase letters and lowercase letters are separate entities.
Meaning, you must have your code be able to handle both, as they are each handled differently.
Perhaps taking some time to sit and take in the ASCII table may be helpful to you, as it will help you understand what is really happening when you add the key.
Use the correct formula for encoding letters. The i'th ciphered letter ci corresponding to the i'th plaintext letter pi is defined as ci = (pi + k) % 26.
Your code is equivalent to this formula, but it does not account for wrapping, uppercase/lowercase letters, etc. The project specification doesn't just ask you to repeat the formula, it asks you to solve a problem using it. To do so, you must understand it. I explain more, subsequently.
I recommend:
Modifying the text in-place. Currently, you calculate the ciphered text and print it. If you add code for modifying the text where it sits, it'll make ignoring non-alphabetic characters easier.
Modify the formula.
Where 𝚨 is the ASCII character code for the beginning of either the uppercase or lowercase characters, the formula might shake out as follows:
ci = (pi - 𝚨 + k) % 26 + 𝚨
What this modified formula does is first take the ASCII code for Pi and turn it into a number that represents which letter in the alphabet it is, ignoring case. Then, you can add the key(shift the cipher). Using % 26 on this result then makes sure that the result is between 1 and 26—always a letter. Finally, we add back 𝚨 so that the character has a case again.
Here's the modified code with the solution broken down, step by step:
// ...
for (int i = 0, n = strlen(text); i < n; i++) {
if (!isalpha(text[i])) continue;
if (isupper(text[i])) {
// the letter's ASCII code on its own.
int charcode = text[i];
// the letter's index in the alphabet. A = 0, B = 1, etc.
// this is no longer a valid ASCII code.
int alphabet_index = charcode - 'A';
// the letter's index in the alphabet, shifted by the key.
// note, this may shift the letter past the end/beginning of the alphabet.
int shifted_alphabet_index = alphabet_index + key;
// the letter's index in the alphabet, shifted by the key, wrapped around.
// the modulo operator (%) returns the remainder of a division.
// in this instance, the result will always be between 0 and 25,
// meaning it will always be a valid index in the alphabet.
int shifted_index_within_alphabet = shifted_alphabet_index % 26;
// this is the final ASCII code of the letter, after it has been shifted.
// we achieve this by adding back the 'A' offset so that the letter is
// within the range of the correct case of letters.
int final_shifted_charcode = shifted_index_within_alphabet + 'A';
text[i] = final_shifted_charcode;
}
else { // islower
int charcode = text[i];
int alphabet_index = charcode - 'a';
int shifted_alphabet_index = alphabet_index + key;
int shifted_index_within_alphabet = shifted_alphabet_index % 26;
int final_shifted_charcode = shifted_index_within_alphabet + 'a';
text[i] = final_shifted_charcode;
}
}
printf("ciphertext: %s\n", text);
// ...
And here is the solution, simplified down:
// ...
for (int i = 0, n = strlen(text); i < n; i++) {
if (!isalpha(text[i])) // if not alphabetic, skip
continue; //
if (isupper(text[i])) // if uppercase
text[i] = (text[i] - 'A' + key) % 26 + 'A'; //
else // if lowercase
text[i] = (text[i] - 'a' + key) % 26 + 'a'; //
}
printf("ciphertext: %s\n", text);
// ...
Just as a side note, the statement if (!isalpha(text[i])) is acting like something called a guard clause. This is a useful concept to know. Using guard clauses allows you to have simpler, more readable code. Imagine if I had nested all of the code inside the for loop under the if (isalpha(text[i])) condition. It would be harder to read and understand, and difficult to match up the different bracket pairs.
Edit: I would also echo what chqrlie said. Do not use argv[n] until you have verified that argc >= (n + 1)
The formula to compute the ciphered characters is incorrect:
you should only encode letters
you should subtract the code for the first letter 'a' or 'A'
you should add the code for the first letter 'a' or 'A' to the encoded index.
Note also that you should not use argv[1] until you have checked that enough arguments have been passed.
Here is a modified version:
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, string argv[]) {
if (argc != 2) {
printf("Usage: ./ceasar key\n");
} else {
int key = atoi(argv[1]);
printf("%i\n", key);
string text = get_string("Plaintext: ");
for (int i = 0, len = strlen(text); i < len; i++) {
int c = text[i];
if (c >= 'a' && c <= 'z') {
int cipher = c - 'a';
int ciphertext = cipher + key;
int ciphermod = ciphertext % 26;
c = 'a' + ciphermod;
} else
if (c >= 'A' && c <= 'Z') {
int cipher = c - 'A';
int ciphertext = cipher + key;
int ciphermod = ciphertext % 26;
c = 'A' + ciphermod;
}
printf("%c", c);
}
printf("\n");
}
return 0;
}

C Problems with a do while loop in a code that delete duplicate chars

I'm a beginner programmer that is learning C and I'm doing some exercises on LeetCode but I ran with a problem with today's problem, I'm going to put the problem bellow but my difficult is on a do while loop that I did to loop the deleting function if there are adjacent duplicates, my code can delete the duplicates on the first iteration, but it's not looping to do any subsequent tasks, if anyone could help my I would be grateful.
The LeetCode Daily Problem (10/11/2022):
You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.
We repeatedly make duplicate removals on s until we no longer can.
Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.
Example 1:
Input: s = "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Example 2:
Input: s = "azxxzy"
Output: "ay"
Constraints:
1 <= s.length <= 105
s consists of lowercase English letters.
My code (testcase: "abbaca"):
char res[100]; //awnser
char * removeDuplicates(char * s){
//int that verifies if any char from the string can be deleted
int ver = 0;
//do while loop that reiterates to eliminate the duplicates
do {
int lenght = strlen(s);
int j = 0;
int ver = 0;
//for loop that if there are duplicates adds one to ver and deletes the duplicate
for (int i = 0; i < lenght ; i++){
if (s[i] == s[i + 1]){
i++;
j--;
ver++;
}
else {
res[j] = s[i];
}
j++;
}
//copying the res string into the s to redo the loop if necessary
strcpy(s,res);
} while (ver > 0);
return res;
}
The fuction returns "aaca".
I did some tweaking with the code and found that after the loop the ver variable always return to 0, but I don't know why.
I see two errors
res isn't terminated so the strcpy may fail
You have two definitions of int ver so the one being incremented is not the one being checked by while (ver > 0); In other words: The do-while only executes once.
Based on your code it can be fixed like:
char res[100]; //awnser
char * removeDuplicates(char * s){
//int that verifies if any char from the string can be deleted
int ver = 0;
//do while loop that reiterates to eliminate the duplicates
do {
int lenght = strlen(s);
int j = 0;
ver = 0; // <--------------- Changed
//for loop that if there are duplicates adds one to ver and deletes the duplicate
for (int i = 0; i < lenght ; i++){
if (s[i] == s[i + 1]){
i++;
j--;
ver++;
}
else {
res[j] = s[i];
}
j++;
}
res[j] = '\0'; // <---------------- Changed
//copying the res string into the s to redo the loop if necessary
strcpy(s,res);
} while (ver > 0);
return res;
}

My function for a hangman game in C is not working

A specific function for my hangman game in C, int hidden_word i cant seem to get right. Its purpose is to display the underscores of the missing letters aswell as the correctly guessed letters. Below are two pictures to demonstrate what the result looks like so far. Obviously the underscores arent even in the second picture. Here is a description from the header file -
// hidden_word()
// Creates the word that is displayed to the user, with all the correctly guessed letters shown, and the rest displayed as underscores.
Any non-letters (punctuation, etc) are displayed.
// The function takes two strings as inputs. word[] is the word that the player is trying to guess,
// and display_word[] is the output string to be displayed to the player. The guesses array is a binary
// array of size 26 indicating whether each letter (a-z) has been guessed yet or not.
// Returns 0 if successful, -1 otherwise.
what its supposed to look like
what is actually looks like
int hidden_word ( char display_word[], char word[], unsigned char guesses[26] ){
int result = 0;
int l = strlen(display_word);
if (l != strlen(word))
return -1;
printf("%d", l);
int i;
for (i = 0; i < l; ++i) {
char c2 = (word[i] >= 'A' && word[i] <= 'Z') ? word[i] + 32 : word[i];
if (guesses[c2 - 97] == 1)
{
display_word[i] = word[i];
}
else
{
display_word[i] = '_';
result = -1;
}
}
return result;
}

Obtain two cluster via bubble sort mechanism

I am trying to obtain two cluster from the strings via bubble sort algorithm. Main logic is putting the character strings to left side and the numbers to right side, and the positions can not be changed according to the right to left reading, also i need to use bubble sort for this implementation(!)
For example;
If the string is '503692EC12FATMA' i need to put it FIRSTLY as 'ECFATMA50369212' but the thing i didn't get it how i can use bubble sort to implement this mechanism besides a single if statement ?
I tried somethings but i always sort the character array via bubble sort i can not store the old positions, i need to use just one array and it needs to be implementation of C.
My code example :
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[25],temp;
int l,i,j;
// clrscr();
printf("enter Any Sting\n");
gets(st);
l=strlen(st);
/*Logic Bubble Sort */
for(i=1;i<l;i++)
for(j=0;j<l-i;j++)
if(st[j]>st[j+1])
{
temp=st[j];
st[j]=st[j+1];
st[j+1] =temp;
}
printf("sorted string \n");
printf("%s",st);
getch();
}
But this gives me : '01223569AACEFMT' (!)
After i made the string 'ECFATMA50369212', i will use this string to arrange a cluster left to right A < B and 0 < 1.
to : 'AACEFMT01223569'
Like two functions, first function, use bubble sort to divide numbers and characters, then use this functions returned array to compare it right to left for sorting to create sorted character array.
Any help would be appreciated.
I think that the problem with your code is that you are bubble-sorting the array according to the ASCII values of the characters, in which upper-case letters (as well as lower-case letters) appear after number characters.
What you could do to make you program work is define you own comparison function, in which you would treat number characters (48 <= ASCII code <= 57) and upper-case letter characters (65 <= ASCII code <= 90) differently.
To do this in a single pass requires a differentiation of digits and non-digits. Once you have that, the algorithm can be summed up as:
Always swap if you have digit in the first slot and a non-digit in the second.
Else, only swap if their both digits or both non-digits and then, only if they're out of order (the higher slot is "less than" the lower slot).
Following that, you can do this in a single bubble-run. Its all about proper comparison:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char st[25] = "503692EC12FATMA", temp;
size_t len, i;
int swapped = 1;
puts(st);
len = strlen(st);
while (swapped && len--)
{
swapped = 0;
for (i=0; i<len; ++i)
{
int swap = !isdigit((unsigned char)st[i+1]);
if (isdigit((unsigned char)st[i]))
swap = swap || (st[i+1] < st[i]);
else
swap = swap && (st[i+1] < st[i]);
if (swap)
{
temp = st[i];
st[i] = st[i+1];
st[i+1] = temp;
swapped = 1;
}
}
}
puts(st);
}
Output
503692EC12FATMA
AACEFMT01223569
There are other ways to do this obviously. You can even combine all that madness into a single if expression if you're a masochist, (i didn't for clarity). But to accomplish both clustering and cluster-sorting, this is one way to achieve it.
I suppose it is your homework and you actually need some kind of buble-type sort to do clustering first, without actually sorting, here is sample version which "bubbles" letter to the beginning of the string, preserving their relative positions:
l = strlen(st);
for (i = 1; i < l; i++)
if (isAlpha(st[i])) // bubble this letter to the beginning of the string
for (j = (i - 1); (j >= 0) && !isAlpha(st[j]); j--)
swap(&st[j + 1], &st[j]);
printf("sorted string\n%s\n", st);
NOTE: you need following 2 functions before your main:
char isAlpha(char a) {
return (a >= 'A') && (a <= 'Z');
}
void swap(char* a, char *b) {
char t = *a; *a = *b; *b = t;
}
This is not a bubble sort algorithm. What you're trying to do is just a string manipulation that can be done like that:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char st[25],temp;
int l,i,j;
// clrscr();
printf("enter Any Sting\n");
gets(st);
int i;
char sorted_st[25];
int str_index = 0;
for (i = 0; i < strlen(l); ++i) {
if((l[i] >= 'a' && l[i] <= 'z') ||
(l[i] >= 'A' && l[i] <= 'Z')) {
sorted_st[str_index++] = l[i];
}
}
for (i = 0; i < strlen(l); ++i) {
if(l[i] >= '0' && l[i] <= '9') {
sorted_st[str_index++] = l[i];
}
}
// add the terminating zero
sorted_st[str_index++] = '\0';
printf("sorted string \n");
printf("%s",st);
getch();
}
ADVICE: It's better your main function to return int. On successful execution should return '0', in other cases error code.
int main() {
/* code */
return 0;
}

Permutations for digits represented by Phone Number

I have an interview in 2 days and I am having a very hard time finding a solutions for this question:
What I want to do is .. for any phone number .. the program should print out all the possible strings it represents. For eg.) A 2 in the number can be replaced by 'a' or 'b' or 'c', 3 by 'd' 'e' 'f' etc. In this way how many possible permutations can be formed from a given phone number.
I don't want anyone to write code for it ... a good algorithm or psuedocode would be great.
Thank you
This is the popular correspondence table:
d = { '2': "ABC",
'3': "DEF",
'4': "GHI",
'5': "JKL",
'6': "MNO",
'7': "PQRS",
'8': "TUV",
'9': "WXYZ",
}
Given this, or any other d, (executable) pseudocode to transform a string of digits into all possible strings of letters:
def digstolets(digs):
if len(digs) == 0:
yield ''
return
first, rest = digs[0], digs[1:]
if first not in d:
for x in digstolets(rest): yield first + x
return
else:
for x in d[first]:
for y in digstolets(rest): yield x + y
tweakable depending on what you want to do for characters in the input string that aren't between 2 and 9 included (this version just echoes them out!-).
For example,
print list(digstolets('1234'))
in this version emits
['1ADG', '1ADH', '1ADI', '1AEG', '1AEH', '1AEI', '1AFG', '1AFH', '1AFI',
'1BDG', '1BDH', '1BDI', '1BEG', '1BEH', '1BEI', '1BFG', '1BFH', '1BFI',
'1CDG', '1CDH', '1CDI', '1CEG', '1CEH', '1CEI', '1CFG', '1CFH', '1CFI']
Edit: the OP asks for more explanation, here's an attempt. Function digstolets (digits to letters) takes a string of digits digs and yields a sequence of strings of characters which can be letters or "non-digits". 0 and 1 count as non-digits here because they don't expand into letters, just like spaces and punctuations don't -- only digits 2 to 9 included expand to letters (three possibilities each in most cases, four in two cases, since 7 can expand to any of PQRS and 9 can expand to any of WXYZ).
First, the base case: if nothing is left (string digs is empty), the only possible result is the empty string, and that's all, this recursive call is done, finished, kaput.
If digs is non-empty it can be split into a "head", the first character, and a "tail", all the rest (0 or more characters after the first one).
The "head" either stays as it is in the output, if a non-digit; or expands to any of three or four possibilities, if a digit. In either case, the one, three, or four possible expansions of the head must be concatenated with every possible expansion of the tail -- whence, the recursive call, to get all possible expansions of the tail (so we loop over all said possible expansion of the tail, and yield each of the one, three, or four possible expansions of the head concatenated with each possible expansion of the tail). And then, once again, th-th-that's all, folks.
I don't know how to put this in terms that are any more elementary -- if the OP is still lost after THIS, I can only recommend a serious, total review of everything concerning recursion. Removing the recursion in favor of an explicitly maintained stack cannot simplify this conceptual exposition -- depending on the language involved (it would be nice to hear about what languages the OP is totally comfortable with!), recursion elimination can be an important optimization, but it's never a conceptual simplification...!-)
If asked this in an interview, I'd start by breaking the problem down. What are the problems you have to solve?
First, you need to map a number to a set of letters. Some numbers will map to different numbers of letters. So start by figuring out how to store that data. Basically you want a map of a number to a collection of letters.
Once you're there, make it easier, how would you generate all the "words" for a 1-digit number? Basically how to iterate through the collection that's mapped to a given number. And how many possibilities are there?
OK, now the next step is, you've got two numbers and want to generate all the words. How would you do this if you were just gonna do it manually? You'd start with the first letter for the first number, and the first letter for the second number. Then go to the next letter for the second number, keeping the first letter for the first, etc. Think about it as numbers (basically indices into the collections for two numbers which each map to 3 letters):
00,01,02,10,11,12,20,21,22
So how would you generate that sequence of numbers in code?
Once you can do that, translating it to code should be trivial.
Good luck!
Another version in Java.
First it selects character arrays based on each digit of the phone number. Then using recursion it generates all possible permutations.
public class PhonePermutations {
public static void main(String[] args) {
char[][] letters =
{{'0'},{'1'},{'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'}};
String n = "1234";
char[][] sel = new char[n.length()][];
for (int i = 0; i < n.length(); i++) {
int digit = Integer.parseInt("" +n.charAt(i));
sel[i] = letters[digit];
}
permutations(sel, 0, "");
}
public static void permutations(char[][] symbols, int n, String s) {
if (n == symbols.length) {
System.out.println(s);
return;
}
for (int i = 0; i < symbols[n].length; i ++) {
permutations(symbols, n+1, s + symbols[n][i]);
}
}
}
This is a counting problem, so it usually helps to find a solution for a smaller problem, then think about how it expands to your general case.
If you had a 1 digit phone number, how many possibilities would there be? What if you had 2 digits? How did you move from one to the other, and could you come up with a way to solve it for n digits?
Here's what I came up with:
import java.util.*;
public class PhoneMmemonics {
/**
* Mapping between a digit and the characters it represents
*/
private static Map<Character,List<Character>> numberToCharacters = new HashMap<Character,List<Character>>();
static {
numberToCharacters.put('0',new ArrayList<Character>(Arrays.asList('0')));
numberToCharacters.put('1',new ArrayList<Character>(Arrays.asList('1')));
numberToCharacters.put('2',new ArrayList<Character>(Arrays.asList('A','B','C')));
numberToCharacters.put('3',new ArrayList<Character>(Arrays.asList('D','E','F')));
numberToCharacters.put('4',new ArrayList<Character>(Arrays.asList('G','H','I')));
numberToCharacters.put('5',new ArrayList<Character>(Arrays.asList('J','K','L')));
numberToCharacters.put('6',new ArrayList<Character>(Arrays.asList('M','N','O')));
numberToCharacters.put('7',new ArrayList<Character>(Arrays.asList('P','Q','R')));
numberToCharacters.put('8',new ArrayList<Character>(Arrays.asList('T','U','V')));
numberToCharacters.put('9',new ArrayList<Character>(Arrays.asList('W','X','Y','Z')));
}
/**
* Generates a list of all the mmemonics that can exists for the number
* #param phoneNumber
* #return
*/
public static List<String> getMmemonics(int phoneNumber) {
// prepare results
StringBuilder stringBuffer = new StringBuilder();
List<String> results = new ArrayList<String>();
// generate all the mmenonics
generateMmemonics(Integer.toString(phoneNumber), stringBuffer, results);
// return results
return results;
}
/**
* Recursive helper method to generate all mmemonics
*
* #param partialPhoneNumber Numbers in the phone number that haven't converted to characters yet
* #param partialMmemonic The partial word that we have come up with so far
* #param results total list of all results of complete mmemonics
*/
private static void generateMmemonics(String partialPhoneNumber, StringBuilder partialMmemonic, List<String> results) {
// are we there yet?
if (partialPhoneNumber.length() == 0) {
//Printing the pnemmonics
//System.out.println(partialMmemonic.toString());
// base case: so add the mmemonic is complete
results.add(partialMmemonic.toString());
return;
}
// prepare variables for recursion
int currentPartialLength = partialMmemonic.length();
char firstNumber = partialPhoneNumber.charAt(0);
String remainingNumbers = partialPhoneNumber.substring(1);
// for each character that the single number represents
for(Character singleCharacter : numberToCharacters.get(firstNumber)) {
// append single character to our partial mmemonic so far
// and recurse down with the remaining characters
partialMmemonic.setLength(currentPartialLength);
generateMmemonics(remainingNumbers, partialMmemonic.append(singleCharacter), results);
}
}
}
Use recursion and a good data structure to hold the possible characters. Since we are talking numbers, an array of array would work.
char[][] toChar = {{'0'}, {'1'}, {'2', 'A', 'B', 'C'}, ..., {'9', 'W', 'X'. 'Y'} };
Notice that the ith array in this array of arrays holds the characters corresponding to the ith button on the telephone. I.e., tochar[2][0] is '2', tochar[2][1] is 'A', etc.
The recursive function will take index as a parameter. It will have a for loop that iterates through the replacement chars, replacing the char at that index with one from the array. If the length equals the length of the input string, then it outputs the string.
In Java or C#, you would want to use a string buffer to hold the changing string.
function recur(index)
if (index == input.length) output stringbuffer
else
for (i = 0; i < tochar[input[index]].length; i++)
stringbuffer[index] = tochar[input[index]][i]
recur(index + 1)
A question that comes to my mind is the question of what should 0 and 1 become in such a system? Otherwise, what you have is something where you could basically just recursively go through the letters for each value in the 2-9 range for the simple brute force way to churn out all the values.
Assuming normal phone number length within North America and ignoring special area codes initially there is also the question of how many digits represent 4 values instead of 3 as 7 and 9 tend to get those often unused letters Q and Z, because the count could range from 3^10 = 59,049 to 4^10 = 1,048,576. The latter is 1024 squared, I just noticed.
The OP seems to be asking for an implementation as he is struggling to understand the pseudocode above. Perhaps this Tcl script will help:
array set d {
2 {a b c}
3 {d e f}
4 {g h i}
5 {j k l}
6 {m n o}
7 {p q r s}
8 {t u v}
9 {w x y z}
}
proc digstolets {digits} {
global d
set l [list]
if {[string length $digits] == 0} {
return $l
}
set first [string index $digits 0]
catch {set first $d($first)}
if {[string length $digits] == 1} {
return $first
}
set res [digstolets [string range $digits 1 end]]
foreach x $first {
foreach y $res {
lappend l $x$y
}
}
return $l
}
puts [digstolets "1234"]
#include <sstream>
#include <map>
#include <vector>
map< int, string> keyMap;
void MakeCombinations( string first, string joinThis , vector<string>& eachResult )
{
if( !first.size() )
return;
int length = joinThis.length();
vector<string> result;
while( length )
{
string each;
char firstCharacter = first.at(0);
each = firstCharacter;
each += joinThis[length -1];
length--;
result.push_back(each);
}
first = first.substr(1);
vector<string>::iterator begin = result.begin();
vector<string>::iterator end = result.end();
while( begin != end)
{
eachResult.push_back( *begin);
begin++;
}
return MakeCombinations( first, joinThis, eachResult);
}
void ProduceCombinations( int inNumber, vector<string>& result)
{
vector<string> inputUnits;
vector<string> finalres;
int number = inNumber;
while( number )
{
int lastdigit ;
lastdigit = number % 10;
number = number/10;
inputUnits.push_back( keyMap[lastdigit]);
}
if( inputUnits.size() == 2)
{
MakeCombinations(inputUnits[0], inputUnits[1], result);
}
else if ( inputUnits.size() > 2 )
{
MakeCombinations( inputUnits[0] , inputUnits[1], result);
vector<string>::iterator begin = inputUnits.begin();
vector<string>::iterator end = inputUnits.end();
begin += 2;
while( begin != end )
{
vector<string> intermediate = result;
vector<string>::iterator ibegin = intermediate.begin();
vector<string>::iterator iend = intermediate.end();
while( ibegin != iend)
{
MakeCombinations( *ibegin , *begin, result);
//resultbegin =
ibegin++;
}
begin++;
}
}
else
{
}
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
keyMap[1] = "";
keyMap[2] = "abc";
keyMap[3] = "def";
keyMap[4] = "ghi";
keyMap[5] = "jkl";
keyMap[6] = "mno";
keyMap[7] = "pqrs";
keyMap[8] = "tuv";
keyMap[9] = "wxyz";
keyMap[0] = "";
string inputStr;
getline(cin, inputStr);
int number = 0;
int length = inputStr.length();
int tens = 1;
while( length )
{
number += tens*(inputStr[length -1] - '0');
length--;
tens *= 10;
}
vector<string> r;
ProduceCombinations(number, r);
cout << "[" ;
vector<string>::iterator begin = r.begin();
vector<string>::iterator end = r.end();
while ( begin != end)
{
cout << *begin << "," ;
begin++;
}
cout << "]" ;
return 0;
}
C program:
char *str[] = {"0", "1", "2abc", "3def", "4ghi", "5jkl", "6mno", "7pqrs", "8tuv", "9wxyz"};
const char number[]="2061234569";
char printstr[15];
int len;
printph(int index)
{
int i;
int n;
if (index == len)
{
printf("\n");
printstr[len] = '\0';
printf("%s\n", printstr);
return;
}
n =number[index] - '0';
for(i = 0; i < strlen(str[n]); i++)
{
printstr[index] = str[n][i];
printph(index +1);
}
}
Call
printph(0);

Resources