Description of the problem :
Compute the number of all the sequences which go up down from some input n.
So the user input n; with that n then I create an array of numbers 1..n and then number the sequences with that property
Example: n = 4
1 3 2 4
1 4 2 3
2 3 1 4
2 4 1 3
3 4 1 2
Answer: 5
My program works but for some reason I sometimes get 0 instead of the answer.
#include <stdio.h>
#include <stdlib.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void swap(int *fir, int *sec) {
int temp = *fir;
*fir = *sec;
*sec = temp;
}
void permute(int *array, int i, int length, int *count) {
if (length == 2) {
*count = 1;
return;
}
if (length == i) {
int v = 0, flag = 1;
while (v < length) {
if (v % 2 == 0) {
if (array[v] < array[v + 1]) {
v++;
} else {
flag = 0;
return;
}
}
if (v % 2 != 0) {
if (array[v] > array[v + 1]) {
v++;
} else {
flag = 0;
return;
}
}
}
if (flag == 1) {
/*
int a;
for (a = 0; a < length; a++)
printf("%d", array[a]);
printf("\n");
*/
*count = *count + 1;
}
}
int j = i;
for (j = i; j < length; j++) {
swap(array + i, array + j);
permute(array, i + 1, length, count);
swap(array + i, array + j);
}
return;
}
int main(int argc, char **argv) {
int n;
scanf("%d", &n);
int *arr = safeMalloc(n * sizeof(int));
int i;
for (i = 0; i < n; i++) {
arr[i] = i + 1;
}
int count = 0;
permute(arr, 0, n, &count);
printf("%d\n", count);
return 0;
}
You basically generate all permutations of the array elements and count the valid ones.
Your code has a minor flaw:
the loop while (v < length) { goes one step too far: you access tab[v + 1] so the loop should stop at v < length - 1. As currently coded, it has undefined behavior.
You can further simply the code:
there should be no need to special case length == 2.
flag useless as you always return when you clear it.
if (v % 2 != 0) is redundant: else would suffice.
Here is a fixed and simplified version:
#include <stdio.h>
#include <stdlib.h>
void *safeMalloc(int n) {
void *p = malloc(n);
if (p == NULL) {
printf("Error: malloc(%d) failed. Out of memory?\n", n);
exit(EXIT_FAILURE);
}
return p;
}
void swap(int *fir, int *sec) {
int temp = *fir;
*fir = *sec;
*sec = temp;
}
void permutate(int *array, int i, int length, int *count) {
if (i == length) {
for (int v = 0; v < length - 1; v++) {
if (v % 2 == 0) {
if (array[v] >= array[v + 1]) {
return;
}
} else {
if (array[v] <= array[v + 1]) {
return;
}
}
}
*count = *count + 1;
} else {
for (int j = i; j < length; j++) {
swap(array + i, array + j);
permutate(array, i + 1, length, count);
swap(array + i, array + j);
}
}
}
int main(int argc, char **argv) {
int n;
if (scanf("%d", &n) == 1 && n > 0) {
int *arr = safeMalloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
arr[i] = i + 1;
}
int count = 0;
permutate(arr, 0, n, &count);
printf("%d\n", count);
}
return 0;
}
if you call tab(n,k) the number of updown sequence of length n with k being the last number in your sequence, you can write a recursive formula and implement it like that:
int N = 5+1;
int** tab = new int*[N];
for (int n = 0; n < N; n++) {
tab[n] = new int[N];
for (int k = 0; k < N; k++) {
tab[n][k] = 0;
}
}
tab[1][1] = 1;
for (int n = 2; n < N; n++) {
for (int k = 1; k <= n; k++) {
if (n % 2 == 0) {
for (int j = 0; j < k; j++) {
tab[n][k] += tab[n-1][j];
}
}
else {
for (int j = k; j < n; j++) {
tab[n][k] += tab[n-1][j];
}
}
}
}
int res = 0;
for (int j = 0; j < N; j++) {
res += tab[N - 1][j];
}
You can solve this without iterating through the permutations. Say you're trying to calculate f(n). Where can the new, high number go? It has to go in an 'up' position, which is an even position. You can have any valid sequence of odd length preceding it, and any valid sequence following it.
Let's say we're calculating f(n,k) where the highest val is in position k, zero indexed. This is zero for k even. For odd k we get:
f(n,k) = choose(n-1, k) * f(k) * f(n - k - 1)
To get f(n), sum f(n,k) over odd k < n.
We have to calculate the first few by hand.
f(0) = 1
f(1) = 1
f(2) = 1
f(3) = f(3,1) = choose(2,1) * f(1) * f(1) = 2 * 1 *1 = 2
f(4) = f(4,1) + f(4,3) = choose(3,1) * f(1) * f(2) + choose(3,3) * f(3) * f(0) = 3*1*1 + 1*2*1 = 5
f(5) = f(5,1) + f(5,3) = choose(4,1) * f(1) * f(3) + choose(4,3) * f(3) * f(1) = 4*1*2 + 4*2*1 = 16
Related
I'm trying to write an iterative function that computes all the permutations of an array of numbers given in input.
Here is the code I've written so far.
void permute(int *a, int size){
int j=0, i, h=0, m;
bool flag=true;
int f = factorial(size);
int *arr, *res;
int counter=0;
arr = malloc(f*sizeof(int));
for(i=0; i<f; i++)
arr[i] = 0;
while (j < f) {
if(arr[j]<j)
{
if(j%2 == 0)
{
swap(a[0],a[j]);
} else {
swap(a[arr[j]], a[j]);
}
arr[j]++;
j=0;
} else{
arr[j] = 0;
j++;
}
printf("%d\n",a[j] );
}
}
The code doesn't compute well all the permutations and goes into a long loop. Can someone help me, please? Thanks to everyone.
Your code is close but includes some problems. For instance, the while loop
while (j < f) will assign j to a value out of bound of the array a.
Instead would you please try:
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
int y = 1;
for (i = 1; i <= x; i++) {
y *= i;
}
return y;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int *a, int size)
{
int i, j = 0;
int f = factorial(size);
int *arr;
arr = calloc(f, sizeof(int)); // the members are initialized to 0
// print the original array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
while (j < size) {
if (arr[j] < j) {
if (j % 2 == 0) {
swap(a + 0, a + j);
} else {
swap(a + arr[j], a + j);
}
// print the rearranged array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
arr[j]++;
j = 0;
} else {
arr[j] = 0;
j++;
}
}
free(arr);
}
int main()
{
int a[] = {1, 2, 3}; // example
permute(a, sizeof a / sizeof a[0]); // the 2nd argument is the array length
return 0;
}
Output of the example:
1 2 3
2 1 3
3 1 2
1 3 2
2 3 1
3 2 1
this is the program I made ,if I input [13,11,10,17,18] i get the output [12,13,17,11,10]. I do not understand what mistake I am making. somebody please help me understand.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d",&v);
ptr[i] = v;
}
i=0;
j=0;
while(i<5){
j++;
if (ptr[j]%2==0 && i%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (ptr[j]%2!=0 && i%2 !=0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
}
if (j==4){
i++;
j=0;
}
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
Ok, I tried to tell you how you should have written you program, but you didn't listen:
Make a https://stackoverflow.com/help/minimal-reproducible-example
A MCVE needs all the includes
No interactive stuff. You need to run and run and run your program in a debugger. You don't want to put data in manually every single time.
You want many tests, and you want to repeat them, so that when you fix one, you don't break another.
Make a function which does the job.
Free your memory!
Now to the solution: your idea of a solution was fine apart from the stuff about indexes. It's pretty similar to the one you will find down here. The only difference is that I put the odd numbers al the end to avoid checking elements multiple times.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
void evenodd(int *v, size_t n)
{
for (size_t i = 0; i < n; ++i) {
while (i < n && v[i] % 2 == 0) {
++i;
}
--n;
while (i < n && v[n] % 2) {
--n;
}
if (i < n) {
int tmp = v[i];
v[i] = v[n];
v[n] = tmp;
}
}
}
bool is_evenodd(int *v, size_t n)
{
size_t i = 0;
while (i < n && v[i] % 2 == 0) {
++i;
}
while (i < n && v[i] % 2 != 0) {
++i;
}
return i == n;
}
void main_test(const int *v, size_t n)
{
int *v1 = memcpy(malloc(n * sizeof(int)), v, n * sizeof(int));
evenodd(v1, n);
if (is_evenodd(v1, n)) {
printf("Ok!\n");
}
else {
printf("Fail!\n");
}
free(v1);
}
int main(void)
{
main_test((int[]) { 1 }, 0);
main_test((int[]) { 1 }, 1);
main_test((int[]) { 2 }, 1);
main_test((int[]) { 1, 2 }, 2);
main_test((int[]) { 1, 3 }, 2);
main_test((int[]) { 2, 1 }, 2);
main_test((int[]) { 2, 4 }, 2);
main_test((int[]) { 1, 3, 2 }, 3);
main_test((int[]) { 1, 4, 2 }, 3);
size_t n = 1000;
int *a = malloc(n * sizeof *a);
for (size_t i = 0; i < n; ++i) {
a[i] = rand();
}
main_test(a, n);
free(a);
return 0;
}
You can try the following code :
int even_index = 0; //start index
int odd_index = 4; //end index
for(int i=0;i<5;i++){
if(ptr[i] % 2 == 0){
int temp = ptr[even_index];
ptr[even_index++] = ptr[i]; //swapping values and incrementing even_index
ptr[i] = temp;
}else{
int temp = ptr[odd_index];
ptr[odd_index--] = ptr[i];
ptr[i] = temp;
}
}
or you can also count the number of even numbers in the digits during input and assign odd_value = even_num // number of even digits
ok so I solved it....
see the even numbers always end up in even indexes so we need to set a pointer on those even index(current index) and search for any even number after the current index.
if we find any(even number) we swap the current index value with the even number.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int* ptr;
int n,j,i,num,v;
printf("Enter number of elements:");
scanf("%d",&n);
printf("Entered number of elements: %d\n", n);
ptr = (int*)malloc(n * sizeof(int));
for (i = 0; i < n; ++i) {
scanf("%d", &v);
ptr[i] = v;
}
i=0;
j=0;
while(i<n && j<n){
if (ptr[j]%2==0){
num=ptr[i];
ptr[i]=ptr[j];
ptr[j]=num;
i+=2;
j=i;
}
j++;
}
printf("The elements of the array are: ");
for (i = 0; i < n; ++i) {
printf("%d, ", ptr[i]);
}
}
If this problem is to sort an array in order (descending) and then further place all even values before odd values I would recommend:
Sort the array
Swap and shift any odd numbers with the even numbers
Here's a naive implementation:
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (arr[i] < arr[j]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
int lastEven = 0;
for (int i = 0; i < len - 1; i++) {
if (arr[i] % 2 && (arr[i + 1] % 2 == 0)) {
tmp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = tmp;
lastEven = i;
} else if (arr[i] % 2 == 0 && lastEven-i > 1) {
for (int j = i; j > lastEven; j--) {
tmp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = tmp;
}
lastEven++;
}
}
Given the input [13,11,10,17,18] this will first sort the array ([18,17,13,11,10]) then separate the evens and odds ([18,10,17,13,11])
I am solving this challenge :
https://www.hackerrank.com/challenges/permutations-of-strings/problem
I am using this algorithm :
https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order
Suppose I enter my array of strings as {"a", "b", "c"}, then the output should be :
a b c
a c b
b c a
c b a
b a c
c a b
Since there are 3 distinct strings, there are 3! = 6 permutations.
The program is also supposed to handle duplicate cases, so if I enter {"a", "b", "b"}, there will only be 3! / 2! = 3 permutations.
Anyways when my program reaches c b a then it quits. Why? How can I fix that?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // to swap two strings
{
char* temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int next_permutation(int n, char **s)
{
/**
* Complete this method
* Return 0 when there is no next permutation and 1 otherwise
* Modify array s to its next permutation
*/
int k, i, l;
k = i = l = 0;
for(i = n - 2; i >= 0; i--) // first step
if(strcmp(s[i], s[i + 1]) < 0) {
k = i;
break;
}
if(i == -1)
return 0;
for(i = n - 1; i >= k + 1; i--) // second step
if(strcmp(s[k], s[i]) < 0) {
l = i;
break;
}
swap(&s[k], &s[l]); // third step
for(i = k + 1; i < n / 2; i++) // fourth step
swap(&s[i], &s[n - i - 1]);
return 1;
}
int main() // locked code
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char*));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}
This is the final code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char** s1, char** s2) // swaps two strings
{
char* temp = *s1;
*s1 = *s2;
*s2 = temp;
}
int next_permutation(int n, char **s) // function to complete
{
int k, i, l;
k = i = l = 0;
for(i = n - 2; i >= 0; i--) // step 1
if(strcmp(s[i], s[i + 1]) < 0) {
k = i;
break;
}
if(i == -1)
return 0;
for(i = n - 1; i >= k + 1; i--) // step 2
if(strcmp(s[k], s[i]) < 0) {
l = i;
break;
}
swap(&s[k], &s[l]); // step 3
int inner = k + 1 + n - 1; // step 4
int cond = inner / 2;
for(i = n - 1; i > cond; i--)
swap(&s[i], &s[inner - i]);
return 1;
}
int main() // locked code
{
char **s;
int n;
scanf("%d", &n);
s = calloc(n, sizeof(char*));
for (int i = 0; i < n; i++)
{
s[i] = calloc(11, sizeof(char));
scanf("%s", s[i]);
}
do
{
for (int i = 0; i < n; i++)
printf("%s%c", s[i], i == n - 1 ? '\n' : ' ');
} while (next_permutation(n, s));
for (int i = 0; i < n; i++)
free(s[i]);
free(s);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
void printingArr(int** arr, int rows);
void sortingEachOneOfThem(int** pArr, int rows);
void sortingTheWholeArray(int** pArr, int rows);
void bubbleSort(int* arr);
void freeArray(int **a, int m);
int main(void)
{
int** pArr = 0;
int numOfRows = 0;
int sizes = 0;
printf("Enter number of rows: ");
scanf("%d", &numOfRows);
pArr = (int**) malloc(sizeof(int*) * numOfRows);
if (pArr == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
for (int i = 0; i < numOfRows; i++)
{
printf("Enter array length for row %d: ",i);
scanf("%d", &sizes);
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
if (pArr[i] == NULL)
{
printf("Unsuccessful malloc!\n");
return 1;
}
pArr[i][0] = sizes;
for (int k = 1; k < sizes + 1; k++)
{
printf("Enter value for array: ");
scanf("%d", &pArr[i][k]);
}
}
printingArr(pArr, numOfRows);
sortingEachOneOfThem(pArr, numOfRows);
printingArr(pArr, numOfRows);
sortingTheWholeArray(pArr, numOfRows);
printingArr(pArr, numOfRows);
for (int i = 0; i < numOfRows; i++)
{
if (pArr[i] != NULL)
{
free(*(pArr + i));
}
}
//free(pArr);
system("pause");
return 0;
}
/*
this amazing, wonderfull piece of program prints the array given
input: int** arr, int rows
output: none
*/
void printingArr(int** arr, int rows)
{
int i = 0;
int k = 0;
for (i = 0; i < rows; i++)
{
for (k = 0; k <= arr[i][0]; k++)
{
printf("%d ", arr[i][k]);
}
printf("\n");
}
printf("\n");
}
/*
This beautiful function sorts the whole array, but its length of rows like a pyramid
input: int** arr, int rows
output: none
*/
void sortingTheWholeArray(int** pArr, int rows)
{
int* temp = 0;
int i = 0, k = 0;
for (i = 0; i < rows - 1; i++)
{
for (k = 0; k < rows - 1; k++)
{
if (pArr[k][0] > pArr[k + 1][0])
{
temp = pArr[k];
pArr[k] = pArr[k + 1];
pArr[k + 1] = temp;
}
}
}
}
/*
This little small function sorts every row of the array of arrays given to it
input: int** arr, int rows
output: none
*/
void sortingEachOneOfThem(int** pArr, int rows)
{
int i = 0;
for (i = 0; i < rows; i++)
{
bubbleSort(pArr[i]);
}
}
/*
This little piece of a code is a bubble sort, sorts the array given to it :)
input: int* arr, int rows
output: none
*/
void bubbleSort(int* arr)
{
int i = 1, k = 0;
for (i = 1; i < arr[0] - 1; i++)
{
for (k = 1; k <= arr[0] - i; k++)
{
if (arr[k] > arr[k + 1])
{
arr[k] += arr[k + 1];
arr[k + 1] = arr[k] - arr[k + 1];
arr[k] -= arr[k + 1];
}
}
}
}
the free at the end crashes my code, showing this error:
https://i.stack.imgur.com/nqxBG.png
the same usage of the function free() on another code worked good, but not here. I have tried running through it in step by step mode, it crashes at the first free. Dr. memory shows this: https://i.stack.imgur.com/rSZJr.png
another link: https:// i.stack. imgur.com/ZX2Ne.png (paste it without the spaces in the middle, Can't post more than 2 links)
what can I do?
This:
pArr[i] = (int*) malloc(sizeof(int) * sizes + 1);
under-allocates. Adding a single byte to the size of an array of int makes little sense. You probably meant:
pArr[i] = malloc((sizes + 1) * sizeof *pArri[i]);
Don't cast the return value of malloc(), and use sizeof on the left-hand side.
I'm trying to implement segmented sieve of Eratosthenes in C (im beginner programmer) and it just prints proper output but I'm getting SIGSEGV when I'm submitting in on SPOJ. Can you help me spot the leak?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
void segmented_sieve(int *m, int *n, int t) {
int count, i, j, l, sqrt_imax, hlp_imin;
count = i = j = l = sqrt_imax = hlp_imin = 0;
int *imin, *imax;
imin = m;
imax = n;
sqrt_imax = (int)sqrt((double)imax[t]);
int *sieve;
sieve = malloc((imax[t] + 1) * sizeof(*sieve));
memset(sieve, 1, (imax[t] + 1) * sizeof(*sieve));
for (i = 2; i <= sqrt_imax; ++i) {
for (j = i * i; j <= imax[t]; j += i)
sieve[j] = 0;
}
int *next;
next = malloc((int)sqrt(1000000000) * sizeof(*next));
for (i = 2; i <= sqrt_imax; ++i) {
if (sieve[i] > 0) {
++count;
next[count] = i;
}
}
for (i = 1; i <= count; ++i) {
if (imin[t] <= 2) {
imin[t] = 2;
for (j = next[i]; j <= sqrt_imax; j = next[i]) {
for (l = j * j; l <= n[t]; l += j)
sieve[l] = 0;
break;
}
}
else {
hlp_imin = (int)(m[t] / next[i]);
hlp_imin *= next[i];
for (j = next[i]; j <= sqrt_imax; j = next[i]) {
for (l = hlp_imin; l <= imax[t]; l += j)
sieve[l] = 0;
break;
}
}
}
for (i = imin[t]; i < imax[t]; ++i)
sieve[i] > 0 ? printf("%d\n", i) : 0;
free(sieve);
free(next);
}
int main()
{
int t, tmp, i;
t = tmp = i = 0;
scanf("%d", &t);
int *m;
m = malloc(t * sizeof(*m));
int *n;
n = malloc(t * sizeof(*n));
for (i = 0; i < t; ++i) {
scanf("%d", &tmp);
m[i] = tmp;
scanf("%d", &tmp);
n[i] = tmp;
}
for (i = 0; i < t; ++i) {
segmented_sieve(m, n, i);
printf("\n");
}
free(m);
free(n);
return 0;
}
I fixed it by changing int to char. now just getting TLE...
Think about what happens if you get two values imin = 2,000,000,000 and imax = 2,000,000,010. You should create a tiny sieve for just 11 numbers. But you allocate storage for 2 billion ints which is probably more than your computer can handle.