storing the permuted strings into an array - c

I have been trying to store the permuted strings from the following function into an array. I am getting the following error,
Error 2 error C2106: '=' : left operand must be l-value
I want to be able to store all the permuted string and retrieve them one by one.
#include<stdio.h>
#include<string.h>
const char cstr[100][100];
char* permute(const char *a, int i, int n)
{
int j;
if (i == n)
{
cstr [k] =a;
k++;
}
else
{
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
return cstr;
}
int main ()
{
char str1 [100];
printf ( "enter a string\n" );
scanf( "%d" , &str );
permute ( str1 , 0 , n-1 );
//can't decide what parameter to consider to terminate the loop
printf( "%s" , cstr[i] ); /*then print the strings returned from permute
function*/
return 0;
}

cstr[k] = a; is where your error is.
cstr[k] is a char[100], but a is a char*. These are fundamentally different and cannot be assigned to each other. You want to do a strcpy(cstr[k], a) instead (or a memcpy).
cstrk[k] refers to a character array of size 100 and arrays cannot directly be assigned to in C, therefore it is not an l-value expression.

Following is the fully working program
#include <stdio.h>
#include <string.h>
char cstr[100][100];
int k;
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* End of swap() */
/* Function to print permutations of string */
char permute(char *a, int i, int n)
{
int j;
if (i == n)
{
strcpy(cstr[k],a);
k++;
// printf("%s\n", a);
}
else {
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
return cstr;
}
/* The main() begins */
int main()
{
char a[20];
int n,x,i;
printf("Enter a string: ");
scanf("%s", a);
n = strlen(a);
printf("Permutaions:\n");
permute(a, 0, n - 1);
for(i=0;i<k;i++)
printf("%s\n",cstr[i]);
getchar();
scanf("%d",&x);
return 0;
}

Related

Core keeps dumping when trying to reverse array using a function to swap values of 2 pointers

#include<stdio.h>
int main() {
/* read integer array */
int n, i;
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
/* reverse the array */
for (i = 0; i < n / 2; i++) {
exchange(a[i], a[n - i - 1]);
}
/* print the array */
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
/* free the memory */
free(a);
return;
}
/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
This is the code, the function exchange tries to exchange the values of the integers which these two pointers are pointing to.
Keeps dumping the core.
In this call of the function exchange
exchange(a[i], a[n - i - 1]);
the both arguments have the type int while the function expects arguments of the type int *.
You need to call the function like
exchange( a + i, a + n - i - 1);
You need to send address values for exchange functions since arguments of it are declared as pointers. Therefore, you need to change this line
exchange(a[i], a[n - i - 1]);
to this line because as I mentioned it expects addresses.
exchange(&a[i], &a[n - i - 1]);
A nicer way would be passing the whole array and indexes to swap.
Like this: TRY IT ONLINE
#include<stdio.h>
#include <stdlib.h>
void exchange(int **arr, int n1, int n2);
int main() {
/* read integer array */
int n, i;
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
/* reverse the array */
for (i = 0; i < n / 2; i++) {
exchange(&a, i, n - i - 1);
}
/* print the array */
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
/* free the memory */
free(a);
return 0;
}
/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int **arr, int n1, int n2) {
int temp = (*arr)[n1];
(*arr)[n1] = (*arr)[n2];
(*arr)[n2] = temp;
}

function that remove an integer from an array using pointer in C

I got a question where I need to write a function that reads an integer X and an array A of type int (size N) from the keyboard and eliminates all occurrences of X in A.
for example the input is:
5
1 2 3 4 3
3
and it would return:
A : 1 2 3 4 3
New A : 1 2 4
my code so far is
#include <stdio.h>
#include<stdlib.h>
#define DIM 50
int main() {
int *A;
int N, X;
int *P1, *P2;
do{
scanf("%d", &N);
}while(N<0 || N>DIM);
A= (int*)malloc(N*sizeof(int));
for(P1=A; P1<A+N ; P1++)
scanf("%d ", P1);
printf("\n");
scanf("%d",&X);
printf("A : ");
for(P1=A; P1<A+N ; P1++)
printf("%d ", *P1);
printf("\n");
but I don't know how to continue if you could please help
What you need is to write a function that will erase elements equal to the specified value and reallocate the result array.
Here is a demonstration program where such a function is shown in action.
#include <stdio.h>
#include <stdlib.h>
size_t erase_remove( int **a, size_t n, int value )
{
size_t m = 0;
for (int *p = *a, *q = *a; p != *a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
if (m != n)
{
int *tmp = realloc( *a, m * sizeof( int ) );
if (tmp != NULL)
{
*a = tmp;
}
else
{
m = -1;
}
}
return m;
}
int main( void )
{
size_t n = 5;
int *a = malloc( n * sizeof( int ) );
size_t i = 0;
a[i++] = 1, a[i++] = 2, a[i++] = 3, a[i++] = 4, a[i++] = 3;
int value = 3;
size_t m = erase_remove( &a, n, value );
if (m != -1) n = m;
for (const int *p = a; p != a + n; ++p)
{
printf( "%d ", *p );
}
putchar( '\n' );
free( a );
}
The program output is
1 2 4
If the memory reallocation for the array within the function was not successful the function returns the value (size_t)-1.
The function preserves the order of elements after removing elements equal to the target value.
If to make the function more general that can deal not only with arrays dynamically allocated then it can look very simply.
size_t erase_remove( int *a, size_t n, int value )
{
size_t m = 0;
for (int *p = a, *q = a; p != a + n; ++p)
{
if (*p != value)
{
if (q != p) *q = *p;
++q;
++m;
}
}
return m;
}
In this case the caller of the function should reallocate the result dynamically allocated array (if it is required) based on the returned value m from the function.
#define N_MAX 50
#define N_MIN 0
int main(void) {
int n;
do{
scanf("%d", &n);
}while(N<N_MIN || N>N_MAX);
int *array = (int*) malloc(sizeof(int) * n);
int i; // number of elements in array
for (i = 0; i < n; i++) {
scanf("%d", array + i);
}
int x;
scanf("%d", &x);
//remove x from arr
for (int j = 0; j <= i; j++) {
if (*(array + j) == x) {
*(array + j) = *(array + i); // replace removed value by last value in array
i--; // decremment number of elements in array
}
}
// print
for (int j = 0; j <= i; j++) {
print("%d", *(array + j));
}
free(array)
}
Try this out!
#include <stdio.h>
#include <stdlib.h>
// Required Prototypes
int *get_nums(char *, size_t *);
int *remove_num(int *, size_t *, int);
void display(char *, int *, size_t);
int main(int argc, char *argv[])
{
size_t size = 0;
int *arr = get_nums("Enter numbers (seperated by space): ", &size);
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr, size);
arr = remove_num(arr, &size, num);
display("New Array: ", arr, size);
free(arr);
return 0;
}
int *get_nums(char *label, size_t *size)
{
size_t length = 0;
int *arr = NULL;
printf("%s", label);
int c, num;
do {
scanf("%d", &num);
arr = realloc(arr, (length + 1) * sizeof(int));
arr[length++] = num;
} while ( (c = getchar()) != '\n' && c != EOF);
*size = length;
return arr;
}
int *remove_num(int *arr, size_t *size, int num)
{
// Copy elements to the new array
// Return the new array
size_t new_size = 0;
int *new_arr = NULL;
for (size_t i = 0; i < *size; ++i) {
if (arr[i] != num) {
new_arr = realloc(new_arr, (new_size + 1) * sizeof(int));
new_arr[new_size++] = arr[i];
}
}
*size = new_size;
free(arr);
return new_arr;
}
void display(char *label, int *arr, size_t size)
{
printf("%s", label);
for (size_t i = 0; i < size; ++i)
printf("%d ", arr[i]);
printf("\n");
}
The main idea is you create an array of integers. Then you copy those elements to a new array which you do not want to remove. And finally you display the new array. That's all. Yes, it's that simple. ;-)
Enter numbers (seperated by space): 1 2 3 4 3
Enter number to be removed: 3
Old Array: 1 2 3 4 3
New Array: 1 2 4
As #Ahmed Masud said in comments about too many reallocations, here's my modified answer. Please do note that the code below is little bit complex but far more efficient than my previous one.
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *a;
size_t length;
size_t capacity;
} Array;
// Required Prototypes
Array *init_Array(void);
void destroy(Array *);
Array *get_nums(char *);
void remove_num(Array *, int);
void display(char *, Array *);
int main(int argc, char *argv[])
{
Array *arr = get_nums("Enter Numbers (seperated by space): ");
int num;
printf("Enter number to be removed: ");
scanf("%d", &num);
display("Old Array: ", arr);
remove_num(arr, num);
display("New Array: ", arr);
destroy(arr);
return 0;
}
Array *init_Array(void)
{
Array *arr = malloc( sizeof(Array) );
arr->capacity = 1;
arr->length = 0;
arr->a = malloc( sizeof(int) );
return arr;
}
Array *get_nums(char *label)
{
printf("%s", label);
Array *arr = init_Array();
int c, num;
do {
scanf("%d", &num);
// check and reallocate
if (arr->length == arr->capacity) {
arr->a = realloc(
arr->a,
(2 * arr->capacity) * sizeof(int)
);
arr->capacity *= 2;
}
arr->a[arr->length++] = num;
} while ((c = getchar()) != '\n' && c != EOF);
return arr;
}
void remove_num(Array *arr, int num)
{
int remv_idx = -1;
int *a = arr->a;
size_t count = 0;
for (size_t i = 0; i < arr->length; ++i) {
if (a[i] == num) count++;
if (a[i] == num && remv_idx == -1)
remv_idx = i;
if (remv_idx != -1 && remv_idx < i && a[i] != num)
a[remv_idx++] = a[i];
}
arr->length -= count;
arr->capacity = arr->length;
arr->a = realloc(a, arr->capacity * sizeof(int));
}
void display(char *label, Array *arr)
{
printf("%s", label);
for (size_t i = 0; i < arr->length; ++i)
printf("%d ", arr->a[i]);
printf("\n");
}
void destroy(Array *arr)
{
free(arr->a);
free(arr);
}
Here I did not consider any new array but removed the elements in place. I'm keeping both of my solution because you might not need the 2nd one if your input space is small. One more thing, since the question did not mention about any reallocations failures so I did not check it in my code.
Here is an approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_arr(int *arr, size_t size);
size_t remove_by_value(int *arr, size_t len, int value)
{
int count = 0; // maintain how many times we see value
int k;
for(k = 0; k < len ; k++) {
if ( arr[k] == value ) {
while(arr[count+k] == value) {
count++;
} // skip over conscutive values
if ( count + k >= len )
break;
arr[k] = arr[k+count];
arr[k+count] = value;
print_arr(arr, len);
}
}
return len-count;
}
void print_arr(int *arr, size_t size)
{
for(int k = 0; k < size; k++) {
printf("%02d ", arr[k]);
}
printf("---\n");
}
int main()
{
int test_values[] = { 0, 1, 3, 2, 3, 5, 4, 7, 8 };
size_t len = sizeof(test_values)/sizeof(int);
int *arr = malloc(len*sizeof(int));
memcpy(arr, test_values, len*sizeof(int));
print_arr(arr, len);
len = remove_by_value(arr, len, 3);
print_arr(arr, len);
arr = realloc(arr, len);
print_arr(arr, sizeof(int)*len);
return 0;
}
It bubbles the value to be extracted to the end of the array and lops it off.
The nice thing is that it doesn't use any extra memory to do its work.
The second part that is that it is NOT O(n^2) I have to think a bit about the complexity of it (seems bigger than O(n))
However it's a simple solution that keeps the order of the array, removes unneeded values simply.
i've put in the print_arr function at each step of the loop so that you can see what's happening.
Hopefully the code is clear in its purpose, if you have questions please comment and I will further explanation.
Notes
I expressly did not use sizeof(*arr) because i wanted it to be a bit more clear as to what it is. In production code one would use sizeof(*arr) instead of sizeof(int) .... However I would not be able to create a consistent example (e.g. remove_by_value would have to be similarly made generic) so I didn't to keep the example simple to understand.

How to count the total possibilities of permute? (in C)

I'm new to programming, and i'm trying to complement this code in C to permute strings, currently it shows all the words exchanged and counts how many characters the word has.
But I would like it to count the number of lines generated by the permutation too, and in this part, the code is not working. I do not know what else to do!
Example: The word "hi", generates two lines: hi, and ih. (In this case, i want the program write "generated words: 2")
the code:
#include <string.h>
#include <stdio.h>
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else
{
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
}
int main()
{
char str[21];
int len;
int cont = 1;
int fatorial = 1;
printf("\nType a word: ");
scanf("%s", str);
len = strlen(str);
permute(str, 0, len - 1);
printf("\nNumber of letters: %d\n", len);
while (cont < len)
{
fatorial = fatorial * cont;
cont++;
}
printf("\nPossibilities:%d", fatorial);
return 0;
}
You could increment a counter in permute. Something like:
#include <string.h>
#include <stdio.h>
void
swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void
permute(char *a, int i, int n, int *count)
{
int j;
if( i == n ){
printf("%s\n", a);
*count += 1;
} else {
for( j = i; j <= n; j += 1 ){
swap(a + i, a + j);
permute(a, i + 1, n, count);
swap((a + i), (a + j));
}
}
}
int
main(int argc, char **argv)
{
char buf[1024];
char *str = argc > 1 ? argv[1] : buf;
int len;
int contador = 0;
if( argc < 2 ){
printf("\nType a word: ");
scanf("%1023s", buf);
}
len = strlen(str);
permute(str, 0, len - 1, &contador);
printf("\nNumber of words: %d\n", contador);
return 0;
}

Generate all combinations of letters and numbers for a specific length string in C?

I need to create a list of all combinations of lowercase letters and numbers for a certain length, in this case the length needs to be 9. For example: b0a6195c9
It only needs to generate the combinations for that string length, so only combinations that are 9 characters long.
/*
* C program to find all permutations of letters of a string
*/
#include <stdio.h>
#include <string.h>
/* Function to swap values at two pointers */
void swap (char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
/* End of swap() */
/* Function to print permutations of string */
void permute(char *a, int i, int n)
{
int j;
if (i == n)
printf("%s\n", a);
else {
for (j = i; j <= n; j++)
{
swap((a + i), (a + j));
permute(a, i + 1, n);
swap((a + i), (a + j)); //backtrack
}
}
}
/* The main() begins */
int main()
{
char a[20];
int n;
printf("Enter a string: ");
scanf("%s", a);
n = strlen(a);
printf("Permutaions:\n");
permute(a, 0, n - 1);
getchar();
return 0;
}
Is some of the working C code I've found that approaches the problem, however if you provide the lowercase alphabet and numbers it will generate strings of that length.
This is the desired kind of output, however I wouldn't want duplicates:
b0a6195c9
f8j36sg29
8jwb28shg

Storing strings in an array

The code given below prints all the possible combination of a given string. It produces strings recursively . Now i want to store each combination in an array using an array of pointer to each string . How do i initialize the pointer so that it points to string.
The code is :-
Input ABC
Output
ABC in b[0]
ACB in b[1]
BAC
BCA
CAB
CBA
and so on .
thanks :)
void permute(char *a, int i, int n)
{
int k=0;
char *b[100];
int j;
if (i == n)
{
// *b[k]=a;
printf("%s\n", a);
i++;
}
else
{
for (j = i; j <= n; j++)
{
swap((a+i), (a+j));
permute(a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
}
There is no point in pointing elements of b to a, since is a variable string (that is, it keeps changing). Possible output of such code would be that all elements of b would be last permutation of the string a.
You need dynamic allocation of string each time you find a new permutation.
That you can do manually using malloc(). Or can use strdup() to create duplicate strings for you (Remember to free() them at the end ofcourse).
/*Sample Code*/
if (i == n)
{
b[k] = strdup(a);
...
}
Remember, that you also need to pass k as the argument to the function permute(), since k is an automatic variable, newly created with value = 0, each time function permute() is called. There are other possibilities, make k global or static variable.
You could dynamically allocate an array that would hold individual char arrays (or C strings) representing each permutation. One of the things that would make this code generic is to find the value of total_permutations in the main() for a given string with strlen N, which would actually be factorial(N). Here:
void swap(char* A, char* B) {
char t;
t = *A;
*A = *B;
*B = t;
}
int permute(char **arr_of_chars, int count, char *a, int i, int n)
{
int k=0;
char *b[100];
int j;
if (i == n) {
// *b[k]=a;
printf("%s\n", a);
memcpy(arr_of_chars[count], a, strlen(a));
count++;
i++;
} else {
for (j = i; j <= n; j++) {
swap((a+i), (a+j));
count = permute(arr_of_chars, count, a, i+1, n);
swap((a+i), (a+j)); //backtrack
}
}
return count;
}
int main() {
char str[] = "";
char **arr_of_str = NULL;
int len_str = strlen(str);
int i = len_str;
int total_permutations = 1;
while (i > 0) { /* Get all the combinations */
total_permutations *= i;
i--;
}
arr_of_str = (char **) malloc(total_permutations * sizeof(char*));
for (i=0; i <total_permutations; i++) {
arr_of_str[i] = (char *) malloc(sizeof(char) * len_str);
}
permute(arr_of_str, 0, str, 0, (len_str-1));
for (i=0; i <total_permutations; i++) {
printf("%s \n", arr_of_str[i]);
free(arr_of_str[i]);
}
free(arr_of_str);
}

Resources