Finding all possible words from inputted phone number [duplicate] - c

This question already has answers here:
Generating all Possible Combinations
(12 answers)
Closed 9 years ago.
I have a problem that I need some help in figuring out. I was hoping I could get a few pointers on a better way to approach what i'm doing. My main issue is a few lines below (//This is whats hanging me up) and described at the bottom of page.
I need to permutate all possible outcomes of a phone number: (not just dictionary words)
I.E. 222-2222
Should output a list 3^7 long with all the possible permutations of a,b,c
I.E.
AAAAAAA
AAAAAAB
AAAAAAC
AAAAABA // THIS IS WHATS HANGING ME UP
AAAAABB
AAAAABC
AAAAACA // HERE TOO AND SO ON
MY CODE (purposely shortened for testing) GIVES ME:
AAAA
AAAB
AAAC
AABC
AACC
ABCC
ACCC
BCCC
CCCC
I'm a beginning programming student so my knowledge goes as far as using for, while, if, statements and grabbing individual chars from the array.
Here's what my code looks like so far: (this is a part of a function. Code missing)
char alphaFunc(char n[]){
int d1=n[0]-48;
int d2=n[1]-48;
int d3=n[2]-48;
int d4=n[3]-48;
int d5=n[4]-48;
int d6=n[5]-48;
int d7=n[6]-48;
int a=0,b=0,c=0,d=0,e=0,f=0,g=0;
int i=0;
char charArray[10][4]={ {'0','0','0'},{'1','1','1'},{'A','B','C'},
{'D','E','F'},{'G','H','I'},{'J','K','L'},{'M','N','O'},
{'P','R','S'},{'T','U','V'},{'W','X','Y'} };
while(i <=14){
printf("%c%c%c%c\n", charArray[d1][a],
charArray[d2][b],charArray[d3][c],charArray[d4][d],
charArray[d5][e],charArray[d6][f],charArray[d7][g]);
g++;
if(g==3){
g=2;
f++;
}
if(f==3){
f=2;
e++;
}
if(e==3){
e=2;
d++;
}
I'm not exactly looking for someone to do this for me I just need a little help in figuring out which sort of statement will work b/c when you have a digit get to CharArray[d-][a] location [3] and reset it to [0] it sends you to a different part of the loop. (hope that makes sense).

Since the values of charArray are constant, I would recommend making it a global variable, rather than declaring it in your function. In addition, since some numbers have 4 letters, whereas others have 3, you may want to look into using a jagged array to represent it.
As far as printing the permutations you can get from a phone number, I think recursion is going to be your friend. Assuming you can store the phone number in an int array, the following should work:
public void printPermutations(int[] phoneNumber)
{
printPermutations(phoneNumber, 0, String.Empty);
}
private void printPermutations(int[] phoneNumber, int index, string permutation)
{
if(index >= phoneNumber.Length)
{
// If we've reached the end, print the number
printf(permutation + "\n");
}
else
{
// Otherwise, generate a permutation for each
// character this digit can be
int digit = phoneNumber[index];
char[] chars = charArray[digit];
for (int i = 0; i < chars.Length; i++)
{
printPermutations(phoneNumber, index+1, permutation + chars[i]);
}
}
}

Related

How to find the total number of a certain element in an array(C)

I'm trying to create a complete C program to read ten alphabets and display them on the screen. I shall also have to find the number of a certain element and print it on the screen.
#include <stdio.h>
#include <conio.h>
void listAlpha( char ch)
{
printf(" %c", ch);
}
int readAlpha(){
char arr[10];
int count = 1, iterator = 0;
for(int iterator=0; iterator<10; iterator++){
printf("\nAlphabet %d:", count);
scanf(" %c", &arr[iterator]);
count++;
}
printf("-----------------------------------------");
printf("List of alphabets: ");
for (int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
listAlpha(arr[x]);
}
printf("%c",arr);
return 0;
}
int findTotal(){
}
int main(){
readAlpha();
}
The code should be added in the findTotal() element. The output is expected as below.
Output:
List of alphabets : C C C A B C B A C C //I've worked out this part.
Total alphabet A: 2
Total alphabet B: 2
Total alphabet C: 6
Alphabet with highest hit is C
I use an array to count the number of the existence of each character,
I did this code but the display of number of each character is repeated in the loop
int main()
{
char arr[100];
printf("Give a text :");
gets(arr);
int k=strlen(arr);
for(int iterator=0; iterator<k; iterator++)
{
printf("[%c]",arr[iterator]);
}
int T[k];
for(int i=0;i<k;i++)
{
T[i]=arr[i];
}
int cpt1=0;
char d;
for(int i=0;i<k;i++)
{int cpt=0;
for(int j=0;j<k;j++)
{
if(T[i]==T[j])
{
cpt++;
}
}
if(cpt>cpt1)
{
cpt1=cpt;
d=T[i];
}
printf("\nTotal alphabet %c : %d \n",T[i],cpt);
}
printf("\nAlphabet with highest hit is : %c\n",d,cpt1);
}
There is no way to get the number of elements You write in an array.
Array in C is just a space in the memory.
C does not know what elements are actual data.
But there are common ways to solve this problem in C:
as mentioned above, create an array with one extra element and, fill the element after the last actual element with zero ('\0'). Zero means the end of the actual data. It is right if you do not wish to use '\0' among characters to be processed. It is similar to null-terminated strings in C.
add the variable to store the number of elements in an array. It is similar to Pascal-strings.
#include <stdio.h>
#include <string.h>
#define ARRAY_SIZE 10
char array[ARRAY_SIZE + 1];
int array_len(char * inp_arr) {
int ret_val = 0;
while (inp_arr[ret_val] != '\0')
++ret_val;
return ret_val;
}
float array_with_level[ARRAY_SIZE];
int array_with_level_level;
int main() {
array[0] = '\0';
memcpy(array, "hello!\0", 7); // 7'th element is 0
printf("array with 0 at the end\n");
printf("%s, length is %d\n", array, array_len(array));
array_with_level_level = 0;
const int fill_level = 5;
int iter;
for (iter = 0; iter < fill_level; ++iter) {
array_with_level[iter] = iter*iter/2.0;
}
array_with_level_level = iter;
printf("array with length in the dedicated variable\n");
for (int i1 = 0; i1 < array_with_level_level; ++i1)
printf("%02d:%02.2f ", i1, array_with_level[i1]);
printf(", length is %d", array_with_level_level);
return 0;
}
<conio.h> is a non-standard header. I assume you're using Turbo C/C++ because it's part of your course. Turbo C/C++ is a terrible implementation (in 2020) and the only known reason to use it is because your lecturer made you!
However everything you actually use here is standard. I believe you can remove it.
printf("%c",arr); doesn't make sense. arr will be passed as a pointer (to the first character in the array) but %c expects a character value. I'm not sure what you want that line to do but it doesn't look useful - you've listed the array in the for-loop.
I suggest you remove it. If you do don't worry about a \0. You only need that if you want to treat arr as a string but in the code you're handling it quite validly as an array of 10 characters without calling any functions that expect a string. That's when it needs to contain a 0 terminator.
Also add return 0; to the end of main(). It means 'execution successful' and is required to be conformant.
With those 3 changes an input of ABCDEFGHIJ produces:
Alphabet 1:
Alphabet 2:
Alphabet 3:
Alphabet 4:
Alphabet 5:
Alphabet 6:
Alphabet 7:
Alphabet 8:
Alphabet 9:
Alphabet 10:-----------------------------------------List of alphabets: A B C D E F G H I J
It's not pretty but that's what you asked for and it at least shows you've successfully read in the letters. You may want to tidy it up...
Remove printf("\nAlphabet %d:", count); and insert printf("\nAlphabet %d: %c", count,arr[iterator]); after scanf(" %c", &arr[iterator]);.
Put a newline before and after the line of minus signs (printf("\n-----------------------------------------\n"); and it looks better to me.
But that's just cosmetics. It's up to you.
There's a number of ways to find the most frequent character. But at this level I recommend a simple nested loop.
Here's a function that finds the most common character (rather than the count of the most common character) and if there's a tie (two characters with the same count) it returns the one that appears first.
char findCommonest(const char* arr){
char commonest='#'; //Arbitrary Bad value!
int high_count=0;
for(int ch=0;ch<10;++ch){
const char counting=arr[ch];
int count=0;
for(int c=0;c<10;++c){
if(arr[c]==counting){
++count;
}
}
if(count>high_count){
high_count=count;
commonest=counting;
}
}
return commonest;
}
It's not very efficient and you might like to put some printfs in to see why!
But I think it's at your level of expertise to understand. Eventually.
Here's a version that unit-tests that function. Never write code without a unit test battery of some kind. It might look like chore but it'll help debug your code.
https://ideone.com/DVy7Cn
Footnote: I've made minimal changes to your code. There's comments with some good advice that you shouldn't hardcode the array size as 10 and certainly not litter the code with that value (e.g. #define ALPHABET_LIST_SIZE (10) at the top).
I have used const but that may be something you haven't yet met. If you don't understand it and don't want to learn it, remove it.
The terms of your course will forbid plagiarism. You may not cut and paste my code into yours. You are obliged to understand the ideas and implement it yourself. My code is very inefficient. You might want to do something about that!
The only run-time problem I see in your code is this statement:
printf("%c",arr);
Is wrong. At this point in your program, arr is an array of char, not a single char as expected by the format specifier %c. For this to work, the printf() needs to be expanded to:
printf("%c%c%c%c%c%c%c%c%c%c\n",
arr[0],arr[1],arr[2],arr[3],arr[4],
arr[5],arr[6],arr[7],arr[8],arr[9]);
Or: treat arr as a string rather than just a char array. Declare arr as `char arr[11] = {0};//extra space for null termination
printf("%s\n", arr);//to print the string
Regarding this part of your stated objective:
"I shall also have to find the number of a certain element and print it on the screen. I'm new to this. Please help me out."
The steps below are offered to modify the following work
int findTotal(){
}
Change prototype to:
int FindTotal(char *arr);
count each occurrence of unique element in array (How to reference)
Adapt above reference to use printf and formatting to match your stated output. (How to reference)

Debug-print for loop omitting 1st value

I was debugging a low level program, I had to ensure that my array exp have all values I expect it to have. So I wrote a code snippet that prints my array to help debug it. Problem is standard library isn't available so I need to use my own code.
My code snippet:
int test=0;char val[5]={};
int l=0;
for(int k=0;exp[k]!=0;k++)
{
test=exp[k]; //taking in value
int_to_ascii(test, val);
print_char(val,2*l,0xd);
for(int m=0;val[m]!='\0';m++)//clearing out val for next iteration
val[m]='\0';
l=k*0xA0; //next line
}
exp is an integer array..
code for int_to_ascii:
if(src==0)
{
stack[i++]='\0'; //pushing NULL and 0 to stack
stack[i++]='0';
}
else
{
while(src!=0) //converting last digit and pushing to stack
{
stack[i]=(0x30+src%10);
src/=10;
i++;
}
}
i--;
len=i;
while(i>=0)
{
dest[len-i]=stack[i]; //popping and placing from left to right
i--; //inorder not to get reversed.
}
print_char works because I use it to print entire window and interface. It basically takes
char* szarray,int offset,int color.
I was yelling at my computer for nearly 2 hours because I thought my array is incorrect but it shouldn't be, but the actual problem was in this debug code.It doesn't print exp[0].
When it should output:
20480
20530
5
It just prints
20530
5
I even tried brute forcing values into exp[0]. If I give any value except 20480 into that, it will print invalid characters into first entry,like this:
20530P\. ;not exact value, demonstration purpose only
5
I think something is off in int_to_ascii, but that also is extensively used in other parts without any problems.
Any one have any idea with it?

array of pointer game not sure how to move pointers to back

there is a game that this program needs to play X-boom its supposed to take out the x player each turn and put it in the back of the array and then shorten the array so its no longer a part of it in that function. for example
player 1 2 3 4 and the x for the game is 3
players remaining: 1 2 4
players remaining: 1 4
players remaining: 1
i made this code that i think should do it but im not sure why its not working properly
i have a photo to how the output is supposed to look like but i dont know how to share it here if any one knows please tell me in the comments
my problem is mostly with the play function notice that is number 3 in the array was kicked you are supposed to keep on playing from number 3 just that there will be a new pointer there
i tried to solve this be just going to the one that needed to be kicked and doing a swap for it to go back while moving everyone else forward and then shortening the array by 1
in the end the main function will print the array and it needs to be in order that the first player to be kicked will be last in the array
void get_boom_number(int * i){
printf("enter the boom number\n");
scanf("%d",i);
return ;
}
#define LENGTH 31
void play(char * players[],int length,int boomnum){
int count=-1;
count = (count+boomnum-1)%(length);
char * temp;
for (int i = 0; i<30; i++) {
printf("%d\n",count);
for (int start=count; start<length-1; start++) {
temp=*(players+start);
*(players+start)=*(players+start+1);
*(players+start+1)=temp;
}
count=(count+boomnum-1)%(length);
length=length-1;
}
return ;
}
int main()
{
char * players[LENGTH]={"Tyrion Lannister","Daenerys Targaryen","Jon Snow","Arya Stark","Theon Greyjoy", "Joffrey Baratheon","Khal Drogo","Ted Mosby","Marshall Eriksen","Robin Scherbatsky","Barney Stinson", "Lily Aldrin", "Tracy McConnell", "Ted Mosby", "Leonard Hofstadter","Sheldon Cooper", "Penny", "Howard Wolowitz", "Raj Koothrappali", "Bernadette Rostenkowski-Wolowitz","Amy Farrah Fowler", "Gregory House", "Lisa Cuddy", "James Wilson","Eric Foreman", "Allison Cameron", "Robert Chase" ,"Lawrence Kutner", "Chris Taub","Remy 13 Hadley", "Amber Volakis"};
int boom_number, i;
get_boom_number(&boom_number);
play(players,LENGTH,boom_number);
and then just printing the array also we are not alowed to use "[]" for the hole thing.
A problem with your code is that count will become negative if the boomnum number is e.g. 1. I don't understand why count is initialized to -1 and why you subtract 1 more when recalculating count. Your code is the same as:
int count = (boomnum-2)%(length);
Again, it seems strange to subtract 2. Anyway, you must check that the result isn't negative.
Another problem is this:
count=(count+boomnum-1)%(length);
length=length-1;
This can cause count to be equal to length in the next iteration. I guess that's not what you want. You need to swap the two lines to avoid that. Like:
length=length-1;
count=(count+boomnum-1)%(length);
Doing that and input 2 for boom_number leads to the result:
Remy 13 Hadley
(Strange name by the way).
I would also change:
for (int i = 0; i<30; i++) {
to
while(length > 1) {
It's a bad idea to hard code the number of loops.
Further, this line:
count=(count+boomnum-1)%(length);
is also a problem. If boomnum is zero it may again cause count to become negative.

"No Output" result in C?

I was doing a programming question and one of the sample output is 64197148392731290. My code for that question is correct as it is giving me the right answers for other test cases (output for those test cases are in single digit).
I understand that there will be too many iterations for the test case which has 64197148392731290 as output. So what should I do to get correct answer for that test case too.
Here is the code :
#include<stdio.h>
#include<string.h>
int main() {
int test_case;long long int i, j, count, n, k, k1;
scanf("%d", &test_case);
while(test_case--) {
scanf("%lld%lld", &n, &k);
char a[n];
count=0;
k1=k;
scanf("%s", a);
while(k1--) {
strcat(a,a);
}
for(i=0;i<(n*k);i++) {
if(a[i]=='a') {
for(j=(i+1);j<(n*k);j++) {
if(a[j]=='b') {
count++;
}
}
}
}
printf("%lld\n", count);
}
return 0;
}
Sample Input and Output :
Input:
3
4 2
abcb
7 1
aayzbaa
12 80123123
abzbabzbazab
Output:
6
2
64197148392731290
My task is to count the number of subsequences "ab" (not necessarily consecutive) in the new string. The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains two integers N and K, denoting the length of the initial string S and the number of repetitions respectively.
The second line contains a string S. Its length is exactly N, and each of its characters is a lowercase English letter.
If you are trying to store input in "int" that wont work coz this number its out of range, change it to "long long int"
Well the previous answer was sure wrong. Thanks for the code.
Sorry don't have time for detailed study but preliminary analysis tells me that maybe the error is because you are trying to store a sting of length 2n in a[n]. It works for smaller values since when you declare
char a[n];
^
variable known at runtime
it actually allocates a large block so that any value of n within range is possible. For large values strcat(a,a) will probably fail.
Basically somewhere down the line the string becomes corrupt. Most probably that is because of strcat. I suggest remove strcat, do something else to a similar effect.

What am I doing wrong (C arrays)?

I'm just a beginner at C.
I'm trying to make a simple program to arrange the user-entered digits in ascending order. I have figured out the solution but can't understand why my other code wouldn't work :(
-------------------------------------------------------------------------
working code:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=0;i<10;i++)
{scanf("%d",&num[i]);}
for (i=0;i<9;i++)
{
for (j=i+1;j<10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=0;i<10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
-------------------------------------------------------------------------
code that won't work:
-------------------------------------------------------------------------
#include <stdio.h>
int main()
{
int i,j,num[10];
printf("Enter 10 numbers\n");
for (i=1;i<=10;i++)
{scanf("%d",&num[i]);}
for (i=1;i<10;i++)
{
for (j=i+1;j<=10;j++)
{
if (num[i]>num[j])
{
num[i]+=num[j];
num[j]=num[i]-num[j];
num[i]=num[i]-num[j];
}
}
}
printf("The numbers in ascending order are:");
for (i=1;i<=10;i++)
{
printf(" %d",num[i]);
}
return 0;
}
In the latter program, numbers appear out of order, and there even are numbers that haven't been entered.
My question is, isn't it basically the same code? Just that in the latter program numbers would be stored from num[1] to num[10] instead of num[0] through num[9]?
Does it have something to do with array definitions?
It seems I have serious misconceptions, please help me out!
In C, when you have int num[10];, your indexes need to go from 0 to 9, never to 10. So look over your code, if any i or j ends up with a value of 10 any time during the program run, that's bad news.
Indexes in C go start from 0. so when you declare an array of size 10, and you try to get element at index 10, you're actually getting the 11th element. Since you haven't defined the 11th element, the array will most likely get some random numbers from memory, which is why you are noticing numbers you have note entered.
Since you are new to programming, I would suggest taking the time now to really learn about how C manages memory, and how different data structures access the memory. It might be a little boring now, but you'll save yourself some headaches in the future, and you will start to build good habits and good practices, which will lead to writing good, optimal code
for(i=0;i<9;i++) //**i<9**
for (j=i+1 ...)
If i=8 then j=9 , everything is OK.
In second code snippet:
for(i=0;i<10;i++) //**i<10**
for (j=i+1 ...)
If i=9 then j=10, so you try to access num[10] and it gives you error.
If you want to access num[10] then you must declare array int num[11] and then you can access num[10].
Array Basics
int num[10]
Capacity of array = 10
Every element of this array are integer.
First element index is 0. So If you want to access first element , num[0]
Last element index is 9. So If you want to access last element, index must be length of array - 1 , so num[9]
There are 10 elements in the array and they are :
num[0] , num[1] , num[2] , num[3] , num[4] , num[5] , num[6] , num[7] , num[8] and num[9]
You can learn further at http://www.cplusplus.com/doc/tutorial/arrays/
In your non-working example, you have invalid memory accesses. For example, when i = 9 and j = 10, you access num[10], which is invalid memory.
Welcome to programming! I believe you are a bit confused about how arrays are indexed in C.
Arrays in most languages (including C) are known as zero-indexed arrays. This means the start of an array is always at position 0. So if you make int num[10], trying to access num[10] isn't actually a valid call at all, because the start is num[0]. Hence you can only access from num[0] to num[9].
It's an easy mistake to make, even though I've been programming for years sometimes when it's been a long night I'll still make silly array indexing issues.
In your other code example, you were doing this:
int num[10];
for(int i = 1; i <= 10; i++) {
//...
}
That means you have an array with ten spaces [0-9], and for the last part of your for loop, you were trying to access num[10] which doesn't exist.
Your working example goes from 0-9 and never tries to read num[10], so it works.
Arrays in C, as in most languages, start with position 0 and count that as position one. So the last element of your array would be the size you entered when you declared the variable, minus one.

Resources